FlatCAMApp.py 381 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617
  1. # ######################################################### ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ######################################################### ##
  8. import urllib.request, urllib.parse, urllib.error
  9. import getopt
  10. import random
  11. import simplejson as json
  12. import lzma
  13. import threading
  14. from stat import S_IREAD, S_IRGRP, S_IROTH
  15. import subprocess
  16. import tkinter as tk
  17. from PyQt5 import QtPrintSupport
  18. import urllib.request, urllib.parse, urllib.error
  19. from contextlib import contextmanager
  20. import gc
  21. from xml.dom.minidom import parseString as parse_xml_string
  22. # ##################################### ##
  23. # # Imports part of FlatCAM # ##
  24. # ##################################### ##
  25. from ObjectCollection import *
  26. from FlatCAMObj import *
  27. from flatcamGUI.PlotCanvas import *
  28. from flatcamGUI.FlatCAMGUI import *
  29. from FlatCAMCommon import LoudDict
  30. from FlatCAMPostProc import load_postprocessors
  31. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  32. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  33. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  34. from FlatCAMProcess import *
  35. from FlatCAMWorkerStack import WorkerStack
  36. from flatcamGUI.VisPyVisuals import Color
  37. from vispy.gloo.util import _screenshot
  38. from vispy.io import write_png
  39. from flatcamTools import *
  40. from multiprocessing import Pool
  41. import tclCommands
  42. import gettext
  43. import FlatCAMTranslation as fcTranslate
  44. import builtins
  45. fcTranslate.apply_language('strings')
  46. if '_' not in builtins.__dict__:
  47. _ = gettext.gettext
  48. # ########################################
  49. # # App ###
  50. # ########################################
  51. class App(QtCore.QObject):
  52. """
  53. The main application class. The constructor starts the GUI.
  54. """
  55. # Get Cmd Line Options
  56. cmd_line_shellfile = ''
  57. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  58. try:
  59. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  60. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  61. except getopt.GetoptError:
  62. print(cmd_line_help)
  63. sys.exit(2)
  64. for opt, arg in cmd_line_options:
  65. if opt == '-h':
  66. print(cmd_line_help)
  67. sys.exit()
  68. elif opt == '--shellfile':
  69. cmd_line_shellfile = arg
  70. # Logging # ##
  71. log = logging.getLogger('base')
  72. log.setLevel(logging.DEBUG)
  73. # log.setLevel(logging.WARNING)
  74. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  75. handler = logging.StreamHandler()
  76. handler.setFormatter(formatter)
  77. log.addHandler(handler)
  78. # Version
  79. version = 8.918
  80. version_date = "2019/06/09"
  81. beta = True
  82. # current date now
  83. date = str(datetime.today()).rpartition('.')[0]
  84. date = ''.join(c for c in date if c not in ':-')
  85. date = date.replace(' ', '_')
  86. # URL for update checks and statistics
  87. version_url = "http://flatcam.org/version"
  88. # App URL
  89. app_url = "http://flatcam.org"
  90. # Manual URL
  91. manual_url = "http://flatcam.org/manual/index.html"
  92. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  93. # this variable will hold the project status
  94. # if True it will mean that the project was modified and not saved
  95. should_we_save = False
  96. # flag is True if saving action has been triggered
  97. save_in_progress = False
  98. # #################
  99. # # Signals ##
  100. # #################
  101. # Inform the user
  102. # Handled by:
  103. # * App.info() --> Print on the status bar
  104. inform = QtCore.pyqtSignal(str)
  105. app_quit = QtCore.pyqtSignal()
  106. # General purpose background task
  107. worker_task = QtCore.pyqtSignal(dict)
  108. # File opened
  109. # Handled by:
  110. # * register_folder()
  111. # * register_recent()
  112. # Note: Setting the parameters to unicode does not seem
  113. # to have an effect. Then are received as Qstring
  114. # anyway.
  115. # File type and filename
  116. file_opened = QtCore.pyqtSignal(str, str)
  117. # File type and filename
  118. file_saved = QtCore.pyqtSignal(str, str)
  119. # Percentage of progress
  120. progress = QtCore.pyqtSignal(int)
  121. plots_updated = QtCore.pyqtSignal()
  122. # Emitted by new_object() and passes the new object as argument, plot flag.
  123. # on_object_created() adds the object to the collection, plots on appropriate flag
  124. # and emits new_object_available.
  125. object_created = QtCore.pyqtSignal(object, bool, bool)
  126. # Emitted when a object has been changed (like scaled, mirrored)
  127. object_changed = QtCore.pyqtSignal(object)
  128. # Emitted after object has been plotted.
  129. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  130. object_plotted = QtCore.pyqtSignal(object)
  131. # Emitted when a new object has been added or deleted from/to the collection
  132. object_status_changed = QtCore.pyqtSignal(object, str)
  133. message = QtCore.pyqtSignal(str, str, str)
  134. # Emmited when shell command is finished(one command only)
  135. shell_command_finished = QtCore.pyqtSignal(object)
  136. # Emitted when multiprocess pool has been recreated
  137. pool_recreated = QtCore.pyqtSignal(object)
  138. # Emitted when an unhandled exception happens
  139. # in the worker task.
  140. thread_exception = QtCore.pyqtSignal(object)
  141. def __init__(self, user_defaults=True, post_gui=None):
  142. """
  143. Starts the application.
  144. :return: app
  145. :rtype: App
  146. """
  147. App.log.info("FlatCAM Starting...")
  148. self.main_thread = QtWidgets.QApplication.instance().thread()
  149. # ################ ##
  150. # # ## OS-specific # ##
  151. # ################ ##
  152. # Folder for user settings.
  153. if sys.platform == 'win32':
  154. from win32com.shell import shell, shellcon
  155. if platform.architecture()[0] == '32bit':
  156. App.log.debug("Win32!")
  157. else:
  158. App.log.debug("Win64!")
  159. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\FlatCAM'
  160. self.os = 'windows'
  161. else: # Linux/Unix/MacOS
  162. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  163. self.os = 'unix'
  164. # ############################ ##
  165. # # ## Setup folders and files # ##
  166. # ############################ ##
  167. if not os.path.exists(self.data_path):
  168. os.makedirs(self.data_path)
  169. App.log.debug('Created data folder: ' + self.data_path)
  170. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  171. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  172. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  173. if not os.path.exists(self.postprocessorpaths):
  174. os.makedirs(self.postprocessorpaths)
  175. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  176. # create current_defaults.FlatConfig file if there is none
  177. try:
  178. f = open(self.data_path + '/current_defaults.FlatConfig')
  179. f.close()
  180. except IOError:
  181. App.log.debug('Creating empty current_defaults.FlatConfig')
  182. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  183. json.dump({}, f)
  184. f.close()
  185. # create factory_defaults.FlatConfig file if there is none
  186. try:
  187. f = open(self.data_path + '/factory_defaults.FlatConfig')
  188. f.close()
  189. except IOError:
  190. App.log.debug('Creating empty factory_defaults.FlatConfig')
  191. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  192. json.dump({}, f)
  193. f.close()
  194. try:
  195. f = open(self.data_path + '/recent.json')
  196. f.close()
  197. except IOError:
  198. App.log.debug('Creating empty recent.json')
  199. f = open(self.data_path + '/recent.json', 'w')
  200. json.dump([], f)
  201. f.close()
  202. # Application directory. CHDIR to it. Otherwise, trying to load
  203. # GUI icons will fail as their path is relative.
  204. # This will fail under cx_freeze ...
  205. self.app_home = os.path.dirname(os.path.realpath(__file__))
  206. App.log.debug("Application path is " + self.app_home)
  207. App.log.debug("Started in " + os.getcwd())
  208. # cx_freeze workaround
  209. if os.path.isfile(self.app_home):
  210. self.app_home = os.path.dirname(self.app_home)
  211. os.chdir(self.app_home)
  212. # Create multiprocessing pool
  213. self.pool = Pool()
  214. # variable to store mouse coordinates
  215. self.mouse = [0, 0]
  216. # ################# ##
  217. # # Initialize GUI # ##
  218. # ################# ##
  219. # FlatCAM colors used in plotting
  220. self.FC_light_green = '#BBF268BF'
  221. self.FC_dark_green = '#006E20BF'
  222. self.FC_light_blue = '#a5a5ffbf'
  223. self.FC_dark_blue = '#0000ffbf'
  224. QtCore.QObject.__init__(self)
  225. self.ui = FlatCAMGUI(self.version, self.beta, self)
  226. # self.connect(self.ui,
  227. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  228. # self.save_geometry) PyQt4
  229. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  230. self.ui.final_save.connect(self.final_save)
  231. # ########### ##
  232. # # ## Data ## ##
  233. # ########### ##
  234. self.recent = []
  235. self.clipboard = QtWidgets.QApplication.clipboard()
  236. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  237. self.project_filename = None
  238. self.toggle_units_ignore = False
  239. # self.defaults_form = PreferencesUI()
  240. # when adding entries here read the comments in the method found bellow named:
  241. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  242. self.defaults_form_fields = {
  243. # General App
  244. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  245. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  246. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  247. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  248. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  249. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  250. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  251. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  252. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  253. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  254. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  255. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  256. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  257. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  258. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  259. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  260. # General GUI Preferences
  261. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  262. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  263. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  264. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  265. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  266. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  267. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  268. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  269. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  270. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  271. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  272. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  273. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  274. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  275. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  276. # General GUI Settings
  277. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  278. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  279. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  280. # Gerber General
  281. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  282. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  283. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  284. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  285. # Gerber Options
  286. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  287. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  288. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  289. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  290. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  291. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  292. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  293. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  294. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  295. # Gerber Advanced Options
  296. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  297. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  298. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  299. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  300. # Gerber Export
  301. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  302. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  303. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  304. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  305. # Gerber Editor
  306. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  307. # Excellon General
  308. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  309. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  310. "excellon_format_upper_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  311. "excellon_format_lower_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  312. "excellon_format_upper_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  313. "excellon_format_lower_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  314. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  315. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  316. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  317. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  318. # Excellon Options
  319. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  320. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  321. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  322. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  323. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_opt_group.spindledir_radio,
  324. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  325. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  326. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  327. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  328. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  329. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  330. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  331. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  332. # Excellon Advanced Options
  333. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  334. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  335. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  336. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  337. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  338. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  339. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  340. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  341. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  342. # Excellon Export
  343. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  344. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  345. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  346. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  347. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  348. # Excellon Editor
  349. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  350. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  351. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  352. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  353. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  354. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  355. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  356. "excellon_editor_circ_angle":
  357. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  358. # Geometry General
  359. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  360. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  361. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  362. # Geometry Options
  363. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  364. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  365. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  366. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  367. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  368. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_opt_group.spindledir_radio,
  369. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  370. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  371. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  372. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  373. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  374. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  375. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  376. # Geometry Advanced Options
  377. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  378. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  379. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  380. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  381. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  382. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  383. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  384. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  385. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  386. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  387. # Geometry Editor
  388. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  389. # CNCJob General
  390. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  391. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  392. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  393. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontsize_sp,
  394. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry,
  395. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  396. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  397. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  398. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  399. # CNC Job Options
  400. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  401. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  402. # CNC Job Advanced Options
  403. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  404. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  405. # NCC Tool
  406. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  407. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  408. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  409. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  410. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  411. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  412. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  413. # CutOut Tool
  414. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  415. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  416. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  417. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  418. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  419. # Paint Area Tool
  420. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  421. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  422. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  423. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  424. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  425. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  426. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  427. # 2-sided Tool
  428. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  429. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  430. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  431. # Film Tool
  432. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  433. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  434. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  435. # Panelize Tool
  436. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  437. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  438. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  439. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  440. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  441. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  442. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  443. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  444. # Calculators Tool
  445. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  446. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  447. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  448. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  449. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  450. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  451. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  452. # Transformations Tool
  453. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  454. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  455. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  456. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  457. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  458. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  459. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  460. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  461. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  462. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  463. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  464. # SolderPaste Dispensing Tool
  465. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  466. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  467. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  468. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  469. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  470. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  471. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  472. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  473. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  474. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  475. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  476. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  477. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  478. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  479. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  480. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo
  481. }
  482. # ########################## ##
  483. # # ## LOAD POSTPROCESSORS ## ##
  484. # ########################## ##
  485. self.postprocessors = load_postprocessors(self)
  486. for name in list(self.postprocessors.keys()):
  487. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  488. if name.partition('_')[0] == 'Paste':
  489. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  490. continue
  491. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  492. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  493. if name == 'hpgl':
  494. continue
  495. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  496. # ########################## ##
  497. # # ## LOAD LANGUAGES ## ##
  498. # ########################## ##
  499. self.languages = fcTranslate.load_languages()
  500. for name in sorted(self.languages.values()):
  501. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  502. self.defaults = LoudDict()
  503. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  504. self.defaults.update({
  505. # Global APP Preferences
  506. "global_serial": 0,
  507. "global_stats": {},
  508. "units": "IN",
  509. "global_app_level": 'b',
  510. "global_language": 'English',
  511. "global_version_check": True,
  512. "global_send_stats": True,
  513. "global_pan_button": '2',
  514. "global_mselect_key": 'Control',
  515. "global_project_at_startup": False,
  516. "global_project_autohide": True,
  517. "global_toggle_tooltips": True,
  518. "global_worker_number": 2,
  519. "global_tolerance": 0.01,
  520. "global_open_style": True,
  521. "global_compression_level": 3,
  522. "global_save_compressed": True,
  523. # Global GUI Preferences
  524. "global_gridx": 0.0393701,
  525. "global_gridy": 0.0393701,
  526. "global_snap_max": 0.001968504,
  527. "global_workspace": False,
  528. "global_workspaceT": "A4P",
  529. "global_grid_context_menu": {
  530. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  531. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  532. },
  533. "global_plot_fill": '#BBF268BF',
  534. "global_plot_line": '#006E20BF',
  535. "global_sel_fill": '#a5a5ffbf',
  536. "global_sel_line": '#0000ffbf',
  537. "global_alt_sel_fill": '#BBF268BF',
  538. "global_alt_sel_line": '#006E20BF',
  539. "global_draw_color": '#FF0000',
  540. "global_sel_draw_color": '#0000FF',
  541. "global_proj_item_color": '#000000',
  542. "global_proj_item_dis_color": '#b7b7cb',
  543. "global_toolbar_view": 511,
  544. "global_background_timeout": 300000, # Default value is 5 minutes
  545. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  546. # (python trace only for unknown errors),
  547. # 1 = show trace(show trace always),
  548. # 2 = (For the future).
  549. # Persistence
  550. "global_last_folder": None,
  551. "global_last_save_folder": None,
  552. # Default window geometry
  553. "global_def_win_x": 100,
  554. "global_def_win_y": 100,
  555. "global_def_win_w": 1024,
  556. "global_def_win_h": 650,
  557. "global_def_notebook_width": 1,
  558. # Constants...
  559. "global_defaults_save_period_ms": 20000, # Time between default saves.
  560. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  561. "global_shell_at_startup": False, # Show the shell at startup.
  562. "global_recent_limit": 10, # Max. items in recent list.
  563. "fit_key": 'V',
  564. "zoom_out_key": '-',
  565. "zoom_in_key": '=',
  566. "grid_toggle_key": 'G',
  567. "zoom_ratio": 1.5,
  568. "global_point_clipboard_format": "(%.4f, %.4f)",
  569. "global_zdownrate": None,
  570. # General GUI Settings
  571. "global_hover": False,
  572. "global_selection_shape": True,
  573. "global_layout": "compact",
  574. # Gerber General
  575. "gerber_plot": True,
  576. "gerber_solid": True,
  577. "gerber_multicolored": False,
  578. "gerber_isotooldia": 0.016,
  579. "gerber_isopasses": 1,
  580. "gerber_isooverlap": 0.15,
  581. # Gerber Options
  582. "gerber_combine_passes": False,
  583. "gerber_milling_type": "cl",
  584. "gerber_noncoppermargin": 0.1,
  585. "gerber_noncopperrounded": False,
  586. "gerber_bboxmargin": 0.1,
  587. "gerber_bboxrounded": False,
  588. "gerber_circle_steps": 128,
  589. "gerber_use_buffer_for_union": True,
  590. # Gerber Advanced Options
  591. "gerber_aperture_display": False,
  592. "gerber_aperture_scale_factor": 1.0,
  593. "gerber_aperture_buffer_factor": 0.0,
  594. "gerber_follow": False,
  595. # Gerber Export
  596. "gerber_exp_units": 'IN',
  597. "gerber_exp_integer": 2,
  598. "gerber_exp_decimals": 4,
  599. "gerber_exp_zeros": 'L',
  600. # Gerber Editor
  601. "gerber_editor_sel_limit": 30,
  602. # Excellon General
  603. "excellon_plot": True,
  604. "excellon_solid": True,
  605. "excellon_format_upper_in": 2,
  606. "excellon_format_lower_in": 4,
  607. "excellon_format_upper_mm": 3,
  608. "excellon_format_lower_mm": 3,
  609. "excellon_zeros": "L",
  610. "excellon_units": "INCH",
  611. "excellon_optimization_type": 'B',
  612. "excellon_search_time": 3,
  613. # Excellon Options
  614. "excellon_drillz": -0.1,
  615. "excellon_travelz": 0.1,
  616. "excellon_feedrate": 3.0,
  617. "excellon_spindlespeed": None,
  618. "excellon_spindledir": 'CW',
  619. "excellon_dwell": False,
  620. "excellon_dwelltime": 1,
  621. "excellon_toolchange": False,
  622. "excellon_toolchangez": 0.5,
  623. "excellon_ppname_e": 'default',
  624. "excellon_tooldia": 0.016,
  625. "excellon_slot_tooldia": 0.016,
  626. "excellon_gcode_type": "drills",
  627. # Excellon Advanced Options
  628. "excellon_offset": 0.0,
  629. "excellon_toolchangexy": "0.0, 0.0",
  630. "excellon_startz": None,
  631. "excellon_endz": 0.5,
  632. "excellon_feedrate_rapid": 3.0,
  633. "excellon_z_pdepth": -0.02,
  634. "excellon_feedrate_probe": 3.0,
  635. "excellon_f_plunge": False,
  636. "excellon_f_retract": False,
  637. # Excellon Export
  638. "excellon_exp_units": 'INCH',
  639. "excellon_exp_format": 'ndec',
  640. "excellon_exp_integer": 2,
  641. "excellon_exp_decimals": 4,
  642. "excellon_exp_zeros": 'LZ',
  643. # Excellon Editor
  644. "excellon_editor_sel_limit": 30,
  645. "excellon_editor_newdia": 0.039,
  646. "excellon_editor_array_size": 5,
  647. "excellon_editor_lin_dir": 'X',
  648. "excellon_editor_lin_pitch": 0.1,
  649. "excellon_editor_lin_angle": 0.0,
  650. "excellon_editor_circ_dir": 'CW',
  651. "excellon_editor_circ_angle": 12,
  652. # Geometry General
  653. "geometry_plot": True,
  654. "geometry_circle_steps": 128,
  655. "geometry_cnctooldia": 0.016,
  656. # Geometry Options
  657. "geometry_cutz": -0.002,
  658. "geometry_multidepth": False,
  659. "geometry_depthperpass": 0.002,
  660. "geometry_travelz": 0.1,
  661. "geometry_toolchange": False,
  662. "geometry_toolchangez": 0.5,
  663. "geometry_feedrate": 3.0,
  664. "geometry_feedrate_z": 3.0,
  665. "geometry_spindlespeed": None,
  666. "geometry_spindledir": 'CW',
  667. "geometry_dwell": False,
  668. "geometry_dwelltime": 1,
  669. "geometry_ppname_g": 'default',
  670. # Geometry Advanced Options
  671. "geometry_toolchangexy": "0.0, 0.0",
  672. "geometry_startz": None,
  673. "geometry_endz": 0.5,
  674. "geometry_feedrate_rapid": 3.0,
  675. "geometry_extracut": False,
  676. "geometry_z_pdepth": -0.02,
  677. "geometry_f_plunge": False,
  678. "geometry_feedrate_probe": 3.0,
  679. "geometry_segx": 0.0,
  680. "geometry_segy": 0.0,
  681. # Geometry Editor
  682. "geometry_editor_sel_limit": 30,
  683. # CNC Job General
  684. "cncjob_plot": True,
  685. "cncjob_plot_kind": 'all',
  686. "cncjob_annotation": True,
  687. "cncjob_annotation_fontsize": 9,
  688. "cncjob_annotation_fontcolor": '#990000',
  689. "cncjob_tooldia": 0.0393701,
  690. "cncjob_coords_decimals": 4,
  691. "cncjob_fr_decimals": 2,
  692. "cncjob_steps_per_circle": 128,
  693. # CNC Job Options
  694. "cncjob_prepend": "",
  695. "cncjob_append": "",
  696. # CNC Job Advanced Options
  697. "cncjob_toolchange_macro": "",
  698. "cncjob_toolchange_macro_enable": False,
  699. "tools_ncctools": "0.0393701, 0.019685",
  700. "tools_nccoverlap": 0.015748,
  701. "tools_nccmargin": 0.00393701,
  702. "tools_nccmethod": "seed",
  703. "tools_nccconnect": True,
  704. "tools_ncccontour": True,
  705. "tools_nccrest": False,
  706. "tools_cutouttooldia": 0.00393701,
  707. "tools_cutoutmargin": 0.00393701,
  708. "tools_cutoutgapsize": 0.005905512,
  709. "tools_gaps_ff": "8",
  710. "tools_cutout_convexshape": False,
  711. "tools_painttooldia": 0.07,
  712. "tools_paintoverlap": 0.15,
  713. "tools_paintmargin": 0.0,
  714. "tools_paintmethod": "seed",
  715. "tools_selectmethod": "single",
  716. "tools_pathconnect": True,
  717. "tools_paintcontour": True,
  718. "tools_2sided_mirror_axis": "X",
  719. "tools_2sided_axis_loc": "point",
  720. "tools_2sided_drilldia": 0.0393701,
  721. "tools_film_type": 'neg',
  722. "tools_film_boundary": 0.0393701,
  723. "tools_film_scale": 0,
  724. "tools_panelize_spacing_columns": 0,
  725. "tools_panelize_spacing_rows": 0,
  726. "tools_panelize_columns": 1,
  727. "tools_panelize_rows": 1,
  728. "tools_panelize_constrain": False,
  729. "tools_panelize_constrainx": 0.0,
  730. "tools_panelize_constrainy": 0.0,
  731. "tools_panelize_panel_type": 'gerber',
  732. "tools_calc_vshape_tip_dia": 0.007874,
  733. "tools_calc_vshape_tip_angle": 30,
  734. "tools_calc_vshape_cut_z": 0.000787,
  735. "tools_calc_electro_length": 10.0,
  736. "tools_calc_electro_width": 10.0,
  737. "tools_calc_electro_cdensity":13.0,
  738. "tools_calc_electro_growth": 10.0,
  739. "tools_transform_rotate": 90,
  740. "tools_transform_skew_x": 0.0,
  741. "tools_transform_skew_y": 0.0,
  742. "tools_transform_scale_x": 1.0,
  743. "tools_transform_scale_y": 1.0,
  744. "tools_transform_scale_link": True,
  745. "tools_transform_scale_reference": True,
  746. "tools_transform_offset_x": 0.0,
  747. "tools_transform_offset_y": 0.0,
  748. "tools_transform_mirror_reference": False,
  749. "tools_transform_mirror_point": (0, 0),
  750. "tools_solderpaste_tools": "0.0393701, 0.011811",
  751. "tools_solderpaste_new": 0.011811,
  752. "tools_solderpaste_z_start": 0.00019685039,
  753. "tools_solderpaste_z_dispense": 0.00393701,
  754. "tools_solderpaste_z_stop": 0.00019685039,
  755. "tools_solderpaste_z_travel": 0.00393701,
  756. "tools_solderpaste_z_toolchange": 0.0393701,
  757. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  758. "tools_solderpaste_frxy": 3.0,
  759. "tools_solderpaste_frz": 3.0,
  760. "tools_solderpaste_frz_dispense": 0.0393701,
  761. "tools_solderpaste_speedfwd": 20,
  762. "tools_solderpaste_dwellfwd": 1,
  763. "tools_solderpaste_speedrev": 10,
  764. "tools_solderpaste_dwellrev": 1,
  765. "tools_solderpaste_pp": 'Paste_1'
  766. })
  767. # ############################ ##
  768. # # ## Load defaults from file # ##
  769. # ############################ ##
  770. if user_defaults:
  771. self.load_defaults(filename='current_defaults')
  772. # ######################### ##
  773. # #### APPLY APP LANGUAGE # ##
  774. # ######################### ##
  775. ret_val = fcTranslate.apply_language('strings')
  776. if ret_val == "no language":
  777. self.inform.emit(_("[ERROR] Could not find the Language files. The App strings are missing."))
  778. log.debug("Could not find the Language files. The App strings are missing.")
  779. else:
  780. # make the current language the current selection on the language combobox
  781. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  782. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  783. # ################################ ##
  784. # # ## CREATE UNIQUE SERIAL NUMBER # ##
  785. # ################################ ##
  786. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  787. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  788. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  789. self.save_defaults(silent=True)
  790. self.propagate_defaults(silent=True)
  791. self.restore_main_win_geom()
  792. def auto_save_defaults():
  793. try:
  794. self.save_defaults(silent=True)
  795. self.propagate_defaults(silent=True)
  796. finally:
  797. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  798. # the following lines activates automatic defaults save
  799. # if user_defaults:
  800. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  801. # self.options_form = PreferencesUI()
  802. self.options_form_fields = {
  803. "units": self.ui.general_options_form.general_app_group.units_radio,
  804. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  805. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  806. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  807. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  808. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  809. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  810. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  811. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  812. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  813. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  814. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  815. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  816. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  817. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  818. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  819. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  820. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  821. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  822. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  823. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  824. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  825. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  826. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  827. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  828. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  829. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  830. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  831. "excellon_spindledir": self.ui.excellon_options_form.excellon_opt_group.spindledir_radio,
  832. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  833. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  834. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  835. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  836. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  837. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  838. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  839. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  840. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  841. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  842. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  843. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  844. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  845. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  846. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  847. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  848. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  849. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  850. "geometry_spindledir": self.ui.geometry_options_form.geometry_opt_group.spindledir_radio,
  851. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  852. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  853. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  854. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  855. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  856. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  857. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  858. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  859. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  860. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  861. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  862. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  863. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  864. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  865. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  866. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  867. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  868. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  869. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  870. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  871. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  872. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  873. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  874. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  875. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  876. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  877. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  878. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  879. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  880. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  881. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  882. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  883. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  884. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  885. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  886. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  887. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  888. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  889. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  890. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  891. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  892. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  893. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  894. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  895. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  896. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  897. }
  898. for name in list(self.postprocessors.keys()):
  899. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  900. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  901. self.options = LoudDict()
  902. self.options.set_change_callback(self.on_options_dict_change)
  903. self.options.update({
  904. "units": "IN",
  905. "global_gridx": 1.0,
  906. "global_gridy": 1.0,
  907. "global_snap_max": 0.05,
  908. "global_background_timeout": 300000, # Default value is 5 minutes
  909. "global_verbose_error_level": 0, # Shell verbosity:
  910. # 0 = default(python trace only for unknown errors),
  911. # 1 = show trace(show trace allways), 2 = (For the future).
  912. "gerber_plot": True,
  913. "gerber_solid": True,
  914. "gerber_multicolored": False,
  915. "gerber_isotooldia": 0.016,
  916. "gerber_isopasses": 1,
  917. "gerber_isooverlap": 0.15,
  918. "gerber_combine_passes": True,
  919. "gerber_noncoppermargin": 0.0,
  920. "gerber_noncopperrounded": False,
  921. "gerber_bboxmargin": 0.0,
  922. "gerber_bboxrounded": False,
  923. "excellon_plot": True,
  924. "excellon_solid": False,
  925. "excellon_format_upper_in": 2,
  926. "excellon_format_lower_in": 4,
  927. "excellon_format_upper_mm": 3,
  928. "excellon_format_lower_mm": 3,
  929. "excellon_units": 'INCH',
  930. "excellon_optimization_type": 'B',
  931. "excellon_search_time": 3,
  932. "excellon_zeros": "L",
  933. "excellon_drillz": -0.1,
  934. "excellon_travelz": 0.1,
  935. "excellon_feedrate": 3.0,
  936. "excellon_feedrate_rapid": 3.0,
  937. "excellon_spindlespeed": None,
  938. "excellon_spindledir": 'CW',
  939. "excellon_dwell": True,
  940. "excellon_dwelltime": 1000,
  941. "excellon_toolchange": False,
  942. "excellon_toolchangez": 1.0,
  943. "excellon_toolchangexy": "0.0, 0.0",
  944. "excellon_tooldia": 0.016,
  945. "excellon_ppname_e": 'default',
  946. "excellon_f_plunge": False,
  947. "excellon_startz": None,
  948. "excellon_endz": 2.0,
  949. "geometry_plot": True,
  950. "geometry_segx": 0.0,
  951. "geometry_segy": 0.0,
  952. "geometry_cutz": -0.002,
  953. "geometry_travelz": 0.1,
  954. "geometry_feedrate": 3.0,
  955. "geometry_feedrate_z": 3.0,
  956. "geometry_feedrate_rapid": 3.0,
  957. "geometry_spindlespeed": None,
  958. "geometry_spindledir": 'CW',
  959. "geometry_dwell": True,
  960. "geometry_dwelltime": 1000,
  961. "geometry_cnctooldia": 0.016,
  962. "geometry_toolchange": False,
  963. "geometry_toolchangez": 2.0,
  964. "geometry_toolchangexy": "0.0, 0.0",
  965. "geometry_startz": None,
  966. "geometry_endz": 2.0,
  967. "geometry_ppname_g": "default",
  968. "geometry_f_plunge": False,
  969. "geometry_depthperpass": 0.002,
  970. "geometry_multidepth": False,
  971. "geometry_extracut": False,
  972. "cncjob_plot": True,
  973. "cncjob_tooldia": 0.016,
  974. "cncjob_prepend": "",
  975. "cncjob_append": "",
  976. "tools_ncctools": "1.0, 0.5",
  977. "tools_nccoverlap": 0.4,
  978. "tools_nccmargin": 1,
  979. "tools_cutouttooldia": 0.07,
  980. "tools_cutoutmargin": 0.1,
  981. "tools_cutoutgapsize": 0.15,
  982. "tools_gaps_ff": "8",
  983. "tools_painttooldia": 0.07,
  984. "tools_paintoverlap": 0.15,
  985. "tools_paintmargin": 0.0,
  986. "tools_paintmethod": "seed",
  987. "tools_selectmethod": "single",
  988. "tools_pathconnect": True,
  989. "tools_paintcontour": True,
  990. "tools_2sided_mirror_axis": "X",
  991. "tools_2sided_axis_loc": 'point',
  992. "tools_2sided_drilldia": 1,
  993. "tools_film_type": 'neg',
  994. "tools_film_boundary": 1,
  995. "tools_film_scale": 0,
  996. "tools_panelize_spacing_columns": 0,
  997. "tools_panelize_spacing_rows": 0,
  998. "tools_panelize_columns": 1,
  999. "tools_panelize_rows": 1,
  1000. "tools_panelize_constrain": False,
  1001. "tools_panelize_constrainx": 0.0,
  1002. "tools_panelize_constrainy": 0.0
  1003. })
  1004. self.options.update(self.defaults) # Copy app defaults to project options
  1005. self.gen_form = None
  1006. self.ger_form = None
  1007. self.exc_form = None
  1008. self.geo_form = None
  1009. self.cnc_form = None
  1010. self.tools_form = None
  1011. self.on_options_combo_change(0) # Will show the initial form
  1012. # # ## Define OBJECT COLLECTION # ##
  1013. self.collection = ObjectCollection(self)
  1014. self.ui.project_tab_layout.addWidget(self.collection.view)
  1015. # ###
  1016. self.log.debug("Finished creating Object Collection.")
  1017. # ### Initialize the color box's color in Preferences -> Global -> Color
  1018. # Init Plot Colors
  1019. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1020. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1021. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1022. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1023. int(self.defaults['global_plot_fill'][7:9], 16))
  1024. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1025. int(self.defaults['global_plot_fill'][7:9], 16))
  1026. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1027. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1028. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1029. # Init Left-Right Selection colors
  1030. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1031. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1032. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1033. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1034. int(self.defaults['global_sel_fill'][7:9], 16))
  1035. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1036. int(self.defaults['global_sel_fill'][7:9], 16))
  1037. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1038. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1039. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1040. # Init Right-Left Selection colors
  1041. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1042. self.defaults['global_alt_sel_fill'])
  1043. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1044. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1045. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1046. int(self.defaults['global_sel_fill'][7:9], 16))
  1047. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1048. int(self.defaults['global_sel_fill'][7:9], 16))
  1049. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1050. self.defaults['global_alt_sel_line'])
  1051. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1052. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1053. # Init Draw color and Selection Draw Color
  1054. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1055. self.defaults['global_draw_color'])
  1056. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1057. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1058. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1059. self.defaults['global_sel_draw_color'])
  1060. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1061. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1062. # Init Project Items color
  1063. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1064. self.defaults['global_proj_item_color'])
  1065. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1066. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1067. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1068. self.defaults['global_proj_item_dis_color'])
  1069. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1070. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1071. # Init the Annotation CNC Job color
  1072. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(
  1073. self.defaults['cncjob_annotation_fontcolor'])
  1074. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  1075. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1076. # ### End of Data ## ##
  1077. # ### Plot Area ## ##
  1078. start_plot_time = time.time() # debug
  1079. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  1080. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  1081. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  1082. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  1083. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  1084. # Keys over plot enabled
  1085. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  1086. self.ui.splitter.setStretchFactor(1, 2)
  1087. # So it can receive key presses
  1088. self.plotcanvas.vispy_canvas.native.setFocus()
  1089. self.app_cursor = self.plotcanvas.new_cursor()
  1090. self.app_cursor.enabled = False
  1091. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1092. # depending on from where those tools are called different actions can be done
  1093. self.call_source = 'app'
  1094. end_plot_time = time.time()
  1095. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1096. # # ## EDITOR section
  1097. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1098. self.exc_editor = FlatCAMExcEditor(self)
  1099. self.grb_editor = FlatCAMGrbEditor(self)
  1100. # # ## Adjust tabs width ## ##
  1101. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1102. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1103. self.collection.view.setMinimumWidth(290)
  1104. self.log.debug("Finished adding FlatCAM Editor's.")
  1105. # # ## Worker ## ##
  1106. if self.defaults["global_worker_number"]:
  1107. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1108. else:
  1109. self.workers = WorkerStack(workers_number=2)
  1110. self.worker_task.connect(self.workers.add_task)
  1111. # # ## Signal handling # ##
  1112. # # ## Custom signals
  1113. self.inform.connect(self.info)
  1114. self.app_quit.connect(self.quit_application)
  1115. self.message.connect(self.message_dialog)
  1116. self.progress.connect(self.set_progress_bar)
  1117. self.object_created.connect(self.on_object_created)
  1118. self.object_changed.connect(self.on_object_changed)
  1119. self.object_plotted.connect(self.on_object_plotted)
  1120. self.plots_updated.connect(self.on_plots_updated)
  1121. self.file_opened.connect(self.register_recent)
  1122. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1123. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1124. # # ## Standard signals
  1125. # # ## Menu
  1126. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1127. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1128. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1129. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1130. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1131. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1132. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1133. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1134. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1135. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1136. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1137. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1138. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1139. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1140. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1141. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1142. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1143. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1144. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1145. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1146. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1147. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1148. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1149. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1150. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1151. self.ui.menufile_exit.triggered.connect(self.final_save)
  1152. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1153. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1154. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1155. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1156. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1157. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1158. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1159. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1160. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1161. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1162. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1163. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1164. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1165. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1166. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1167. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1168. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1169. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1170. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1171. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1172. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1173. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1174. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1175. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1176. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1177. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1178. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1179. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1180. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1181. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1182. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1183. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1184. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1185. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1186. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1187. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1188. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1189. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1190. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1191. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1192. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1193. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1194. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1195. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1196. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1197. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1198. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1199. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1200. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1201. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1202. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1203. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1204. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1205. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1206. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1207. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1208. # ToolBar signals
  1209. self.connect_toolbar_signals()
  1210. # Context Menu
  1211. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1212. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1213. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1214. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1215. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1216. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1217. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1218. self.ui.clearplot.triggered.connect(self.clear_plots)
  1219. self.ui.replot.triggered.connect(self.plot_all)
  1220. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1221. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1222. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1223. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1224. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1225. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1226. # Preferences Plot Area TAB
  1227. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1228. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1229. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1230. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1231. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1232. # ############################ ##
  1233. # # ## GUI PREFERENCES SIGNALS # ##
  1234. # ############################ ##
  1235. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1236. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1237. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1238. )
  1239. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1240. lambda: self.on_toggle_units(no_pref=False))
  1241. # ############################ ##
  1242. # # ## GUI PREFERENCES SIGNALS # ##
  1243. # ############################ ##
  1244. # Setting plot colors signals
  1245. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1246. self.on_pf_color_entry)
  1247. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1248. self.on_pf_color_button)
  1249. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1250. self.on_pf_color_spinner)
  1251. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1252. self.on_pf_color_slider)
  1253. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1254. self.on_pl_color_entry)
  1255. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1256. self.on_pl_color_button)
  1257. # Setting selection (left - right) colors signals
  1258. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1259. self.on_sf_color_entry)
  1260. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1261. self.on_sf_color_button)
  1262. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1263. self.on_sf_color_spinner)
  1264. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1265. self.on_sf_color_slider)
  1266. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1267. self.on_sl_color_entry)
  1268. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1269. self.on_sl_color_button)
  1270. # Setting selection (right - left) colors signals
  1271. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1272. self.on_alt_sf_color_entry)
  1273. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1274. self.on_alt_sf_color_button)
  1275. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1276. self.on_alt_sf_color_spinner)
  1277. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1278. self.on_alt_sf_color_slider)
  1279. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1280. self.on_alt_sl_color_entry)
  1281. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1282. self.on_alt_sl_color_button)
  1283. # Setting Editor Draw colors signals
  1284. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1285. self.on_draw_color_entry)
  1286. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1287. self.on_draw_color_button)
  1288. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1289. self.on_sel_draw_color_entry)
  1290. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1291. self.on_sel_draw_color_button)
  1292. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1293. self.on_proj_color_entry)
  1294. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1295. self.on_proj_color_button)
  1296. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1297. self.on_proj_color_dis_entry)
  1298. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1299. self.on_proj_color_dis_button)
  1300. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1301. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1302. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1303. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1304. self.on_cnc_custom_parameters)
  1305. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.editingFinished.connect(
  1306. self.on_annotation_fontcolor_entry)
  1307. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.clicked.connect(
  1308. self.on_annotation_fontcolor_button)
  1309. # Modify G-CODE Plot Area TAB
  1310. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1311. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1312. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1313. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1314. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1315. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1316. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1317. # Object list
  1318. self.collection.view.activated.connect(self.on_row_activated)
  1319. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1320. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1321. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1322. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1323. self.on_excellon_defaults_button)
  1324. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1325. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1326. self.on_excellon_options_button)
  1327. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1328. self.tool_tab_locked = False
  1329. # decide if to show or hide the Notebook side of the screen at startup
  1330. if self.defaults["global_project_at_startup"] is True:
  1331. self.ui.splitter.setSizes([1, 1])
  1332. else:
  1333. self.ui.splitter.setSizes([0, 1])
  1334. # ################# ##
  1335. # # ## Other setups # ##
  1336. # ################# ##
  1337. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1338. self.setup_obj_classes()
  1339. self.setup_recent_items()
  1340. self.setup_component_editor()
  1341. # ########## ##
  1342. # # ## Shell # ##
  1343. # ########## ##
  1344. # # ##
  1345. # Auto-complete KEYWORDS
  1346. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1347. 'aligndrill', 'clear',
  1348. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1349. 'export_gcode',
  1350. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1351. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1352. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1353. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1354. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1355. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1356. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1357. ]
  1358. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1359. 'holes', 'grid', 'minoffset', 'gridoffset', 'axisoffset', 'dia', 'dist',
  1360. 'gridoffsetx', 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate',
  1361. 'feedrate_rapid', 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g',
  1362. 'outname', 'margin', 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed',
  1363. 'toolchange', 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble',
  1364. 'filename', 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads',
  1365. 'x', 'y', 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value',
  1366. 'angle_x', 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1367. ]
  1368. self.tcl_keywords = [
  1369. "after", "append", "apply", "array", "auto_execok", "auto_import", "auto_load", "auto_mkindex",
  1370. "auto_qualify", "auto_reset", "bgerror", "binary", "break", "case", "catch", "cd", "chan", "clock", "close",
  1371. "concat", "continue", "coroutine", "dict", "encoding", "eof", "error", "eval", "exec", "exit", "expr",
  1372. "fblocked", "fconfigure", "fcopy", "file", "fileevent", "flush", "for", "foreach", "format", "gets", "glob",
  1373. "global", "history", "if", "incr", "info", "interp", "join", "lappend", "lassign", "lindex", "linsert",
  1374. "list", "llength", "load", "lrange", "lrepeat", "lreplace", "lreverse", "lsearch", "lset", "lsort",
  1375. "mathfunc", "mathop", "memory", "my", "namespace", "next", "nextto", "open", "package", "parray", "pid",
  1376. "pkg_mkIndex", "platform", "proc", "puts", "pwd", "read", "refchan", "regexp", "regsub", "rename", "return",
  1377. "scan", "seek", "self", "set", "socket", "source", "split", "string", "subst", "switch", "tailcall",
  1378. "tcl_endOfWord", "tcl_findLibrary", "tcl_startOfNextWord", "tcl_startOfPreviousWord", "tcl_wordBreakAfter",
  1379. "tcl_wordBreakBefore", "tell", "throw", "time", "tm", "trace", "transchan", "try", "unknown", "unload",
  1380. "unset", "update", "uplevel", "upvar", "variable", "vwait", "while", "yield", "yieldto", "zlib",
  1381. "attemptckalloc", "attemptckrealloc", "ckalloc", "ckfree", "ckrealloc", "Tcl_Access", "Tcl_AddErrorInfo",
  1382. "Tcl_AddObjErrorInfo", "Tcl_AlertNotifier", "Tcl_Alloc", "Tcl_AllocStatBuf", "Tcl_AllowExceptions",
  1383. "Tcl_AppendAllObjTypes", "Tcl_AppendElement", "Tcl_AppendExportList", "Tcl_AppendFormatToObj",
  1384. "Tcl_AppendLimitedToObj", "Tcl_AppendObjToErrorInfo", "Tcl_AppendObjToObj", "Tcl_AppendPrintfToObj",
  1385. "Tcl_AppendResult", "Tcl_AppendResultVA", "Tcl_AppendStringsToObj", "Tcl_AppendStringsToObjVA",
  1386. "Tcl_AppendToObj", "Tcl_AppendUnicodeToObj", "Tcl_AppInit", "Tcl_AsyncCreate", "Tcl_AsyncDelete",
  1387. "Tcl_AsyncInvoke", "Tcl_AsyncMark", "Tcl_AsyncReady", "Tcl_AttemptAlloc", "Tcl_AttemptRealloc",
  1388. "Tcl_AttemptSetObjLength", "Tcl_BackgroundError", "Tcl_BackgroundException", "Tcl_Backslash",
  1389. "Tcl_BadChannelOption", "Tcl_CallWhenDeleted", "Tcl_Canceled", "Tcl_CancelEval", "Tcl_CancelIdleCall",
  1390. "Tcl_ChannelBlockModeProc", "Tcl_ChannelBuffered", "Tcl_ChannelClose2Proc", "Tcl_ChannelCloseProc",
  1391. "Tcl_ChannelFlushProc", "Tcl_ChannelGetHandleProc", "Tcl_ChannelGetOptionProc", "Tcl_ChannelHandlerProc",
  1392. "Tcl_ChannelInputProc", "Tcl_ChannelName", "Tcl_ChannelOutputProc", "Tcl_ChannelSeekProc",
  1393. "Tcl_ChannelSetOptionProc", "Tcl_ChannelThreadActionProc", "Tcl_ChannelTruncateProc", "Tcl_ChannelVersion",
  1394. "Tcl_ChannelWatchProc", "Tcl_ChannelWideSeekProc", "Tcl_Chdir", "Tcl_ClassGetMetadata",
  1395. "Tcl_ClassSetConstructor", "Tcl_ClassSetDestructor", "Tcl_ClassSetMetadata", "Tcl_ClearChannelHandlers",
  1396. "Tcl_Close", "Tcl_CommandComplete", "Tcl_CommandTraceInfo", "Tcl_Concat", "Tcl_ConcatObj",
  1397. "Tcl_ConditionFinalize", "Tcl_ConditionNotify", "Tcl_ConditionWait", "Tcl_ConvertCountedElement",
  1398. "Tcl_ConvertElement", "Tcl_ConvertToType", "Tcl_CopyObjectInstance", "Tcl_CreateAlias",
  1399. "Tcl_CreateAliasObj", "Tcl_CreateChannel", "Tcl_CreateChannelHandler", "Tcl_CreateCloseHandler",
  1400. "Tcl_CreateCommand", "Tcl_CreateEncoding", "Tcl_CreateEnsemble", "Tcl_CreateEventSource",
  1401. "Tcl_CreateExitHandler", "Tcl_CreateFileHandler", "Tcl_CreateHashEntry", "Tcl_CreateInterp",
  1402. "Tcl_CreateMathFunc", "Tcl_CreateNamespace", "Tcl_CreateObjCommand", "Tcl_CreateObjTrace",
  1403. "Tcl_CreateSlave", "Tcl_CreateThread", "Tcl_CreateThreadExitHandler", "Tcl_CreateTimerHandler",
  1404. "Tcl_CreateTrace", "Tcl_CutChannel", "Tcl_DecrRefCount", "Tcl_DeleteAssocData", "Tcl_DeleteChannelHandler",
  1405. "Tcl_DeleteCloseHandler", "Tcl_DeleteCommand", "Tcl_DeleteCommandFromToken", "Tcl_DeleteEvents",
  1406. "Tcl_DeleteEventSource", "Tcl_DeleteExitHandler", "Tcl_DeleteFileHandler", "Tcl_DeleteHashEntry",
  1407. "Tcl_DeleteHashTable", "Tcl_DeleteInterp", "Tcl_DeleteNamespace", "Tcl_DeleteThreadExitHandler",
  1408. "Tcl_DeleteTimerHandler", "Tcl_DeleteTrace", "Tcl_DetachChannel", "Tcl_DetachPids", "Tcl_DictObjDone",
  1409. "Tcl_DictObjFirst", "Tcl_DictObjGet", "Tcl_DictObjNext", "Tcl_DictObjPut", "Tcl_DictObjPutKeyList",
  1410. "Tcl_DictObjRemove", "Tcl_DictObjRemoveKeyList", "Tcl_DictObjSize", "Tcl_DiscardInterpState",
  1411. "Tcl_DiscardResult", "Tcl_DontCallWhenDeleted", "Tcl_DoOneEvent", "Tcl_DoWhenIdle", "Tcl_DStringAppend",
  1412. "Tcl_DStringAppendElement", "Tcl_DStringEndSublist", "Tcl_DStringFree", "Tcl_DStringGetResult",
  1413. "Tcl_DStringInit", "Tcl_DStringLength", "Tcl_DStringResult", "Tcl_DStringSetLength",
  1414. "Tcl_DStringStartSublist", "Tcl_DStringTrunc", "Tcl_DStringValue", "Tcl_DumpActiveMemory",
  1415. "Tcl_DuplicateObj", "Tcl_Eof", "Tcl_ErrnoId", "Tcl_ErrnoMsg", "Tcl_Eval", "Tcl_EvalEx", "Tcl_EvalFile",
  1416. "Tcl_EvalObjEx", "Tcl_EvalObjv", "Tcl_EvalTokens", "Tcl_EvalTokensStandard", "Tcl_EventuallyFree",
  1417. "Tcl_Exit", "Tcl_ExitThread", "Tcl_Export", "Tcl_ExposeCommand", "Tcl_ExprBoolean", "Tcl_ExprBooleanObj",
  1418. "Tcl_ExprDouble", "Tcl_ExprDoubleObj", "Tcl_ExprLong", "Tcl_ExprLongObj", "Tcl_ExprObj", "Tcl_ExprString",
  1419. "Tcl_ExternalToUtf", "Tcl_ExternalToUtfDString", "Tcl_Finalize", "Tcl_FinalizeNotifier",
  1420. "Tcl_FinalizeThread", "Tcl_FindCommand", "Tcl_FindEnsemble", "Tcl_FindExecutable", "Tcl_FindHashEntry",
  1421. "Tcl_FindNamespace", "Tcl_FirstHashEntry", "Tcl_Flush", "Tcl_ForgetImport", "Tcl_Format",
  1422. "Tcl_Free· Tcl_FreeEncoding", "Tcl_FreeParse", "Tcl_FreeResult", "Tcl_FSAccess", "Tcl_FSChdir",
  1423. "Tcl_FSConvertToPathType", "Tcl_FSCopyDirectory", "Tcl_FSCopyFile", "Tcl_FSCreateDirectory", "Tcl_FSData",
  1424. "Tcl_FSDeleteFile", "Tcl_FSEqualPaths", "Tcl_FSEvalFile", "Tcl_FSEvalFileEx", "Tcl_FSFileAttrsGet",
  1425. "Tcl_FSFileAttrsSet", "Tcl_FSFileAttrStrings", "Tcl_FSFileSystemInfo", "Tcl_FSGetCwd",
  1426. "Tcl_FSGetFileSystemForPath", "Tcl_FSGetInternalRep", "Tcl_FSGetNativePath", "Tcl_FSGetNormalizedPath",
  1427. "Tcl_FSGetPathType", "Tcl_FSGetTranslatedPath", "Tcl_FSGetTranslatedStringPath", "Tcl_FSJoinPath",
  1428. "Tcl_FSJoinToPath", "Tcl_FSLink· Tcl_FSListVolumes", "Tcl_FSLoadFile", "Tcl_FSLstat",
  1429. "Tcl_FSMatchInDirectory", "Tcl_FSMountsChanged", "Tcl_FSNewNativePath", "Tcl_FSOpenFileChannel",
  1430. "Tcl_FSPathSeparator", "Tcl_FSRegister", "Tcl_FSRemoveDirectory", "Tcl_FSRenameFile", "Tcl_FSSplitPath",
  1431. "Tcl_FSStat", "Tcl_FSUnloadFile", "Tcl_FSUnregister", "Tcl_FSUtime", "Tcl_GetAccessTimeFromStat",
  1432. "Tcl_GetAlias", "Tcl_GetAliasObj", "Tcl_GetAssocData", "Tcl_GetBignumFromObj", "Tcl_GetBlocksFromStat",
  1433. "Tcl_GetBlockSizeFromStat", "Tcl_GetBoolean", "Tcl_GetBooleanFromObj", "Tcl_GetByteArrayFromObj",
  1434. "Tcl_GetChangeTimeFromStat", "Tcl_GetChannel", "Tcl_GetChannelBufferSize", "Tcl_GetChannelError",
  1435. "Tcl_GetChannelErrorInterp", "Tcl_GetChannelHandle", "Tcl_GetChannelInstanceData", "Tcl_GetChannelMode",
  1436. "Tcl_GetChannelName", "Tcl_GetChannelNames", "Tcl_GetChannelNamesEx", "Tcl_GetChannelOption",
  1437. "Tcl_GetChannelThread", "Tcl_GetChannelType", "Tcl_GetCharLength", "Tcl_GetClassAsObject",
  1438. "Tcl_GetCommandFromObj", "Tcl_GetCommandFullName", "Tcl_GetCommandInfo", "Tcl_GetCommandInfoFromToken",
  1439. "Tcl_GetCommandName", "Tcl_GetCurrentNamespace", "Tcl_GetCurrentThread", "Tcl_GetCwd",
  1440. "Tcl_GetDefaultEncodingDir", "Tcl_GetDeviceTypeFromStat", "Tcl_GetDouble", "Tcl_GetDoubleFromObj",
  1441. "Tcl_GetEncoding", "Tcl_GetEncodingFromObj", "Tcl_GetEncodingName", "Tcl_GetEncodingNameFromEnvironment",
  1442. "Tcl_GetEncodingNames", "Tcl_GetEncodingSearchPath", "Tcl_GetEnsembleFlags", "Tcl_GetEnsembleMappingDict",
  1443. "Tcl_GetEnsembleNamespace", "Tcl_GetEnsembleParameterList", "Tcl_GetEnsembleSubcommandList",
  1444. "Tcl_GetEnsembleUnknownHandler", "Tcl_GetErrno", "Tcl_GetErrorLine", "Tcl_GetFSDeviceFromStat",
  1445. "Tcl_GetFSInodeFromStat", "Tcl_GetGlobalNamespace", "Tcl_GetGroupIdFromStat", "Tcl_GetHashKey",
  1446. "Tcl_GetHashValue", "Tcl_GetHostName", "Tcl_GetIndexFromObj", "Tcl_GetIndexFromObjStruct", "Tcl_GetInt",
  1447. "Tcl_GetInterpPath", "Tcl_GetIntFromObj", "Tcl_GetLinkCountFromStat", "Tcl_GetLongFromObj", "Tcl_GetMaster",
  1448. "Tcl_GetMathFuncInfo", "Tcl_GetModeFromStat", "Tcl_GetModificationTimeFromStat", "Tcl_GetNameOfExecutable",
  1449. "Tcl_GetNamespaceUnknownHandler", "Tcl_GetObjectAsClass", "Tcl_GetObjectCommand", "Tcl_GetObjectFromObj",
  1450. "Tcl_GetObjectName", "Tcl_GetObjectNamespace", "Tcl_GetObjResult", "Tcl_GetObjType", "Tcl_GetOpenFile",
  1451. "Tcl_GetPathType", "Tcl_GetRange", "Tcl_GetRegExpFromObj", "Tcl_GetReturnOptions", "Tcl_Gets",
  1452. "Tcl_GetServiceMode", "Tcl_GetSizeFromStat", "Tcl_GetSlave", "Tcl_GetsObj", "Tcl_GetStackedChannel",
  1453. "Tcl_GetStartupScript", "Tcl_GetStdChannel", "Tcl_GetString", "Tcl_GetStringFromObj", "Tcl_GetStringResult",
  1454. "Tcl_GetThreadData", "Tcl_GetTime", "Tcl_GetTopChannel", "Tcl_GetUniChar", "Tcl_GetUnicode",
  1455. "Tcl_GetUnicodeFromObj", "Tcl_GetUserIdFromStat", "Tcl_GetVar", "Tcl_GetVar2", "Tcl_GetVar2Ex",
  1456. "Tcl_GetVersion", "Tcl_GetWideIntFromObj", "Tcl_GlobalEval", "Tcl_GlobalEvalObj", "Tcl_HashStats",
  1457. "Tcl_HideCommand", "Tcl_Import", "Tcl_IncrRefCount", "Tcl_Init", "Tcl_InitCustomHashTable",
  1458. "Tcl_InitHashTable", "Tcl_InitMemory", "Tcl_InitNotifier", "Tcl_InitObjHashTable", "Tcl_InitStubs",
  1459. "Tcl_InputBlocked", "Tcl_InputBuffered", "Tcl_InterpActive", "Tcl_InterpDeleted", "Tcl_InvalidateStringRep",
  1460. "Tcl_IsChannelExisting", "Tcl_IsChannelRegistered", "Tcl_IsChannelShared", "Tcl_IsEnsemble", "Tcl_IsSafe",
  1461. "Tcl_IsShared", "Tcl_IsStandardChannel", "Tcl_JoinPath", "Tcl_JoinThread", "Tcl_LimitAddHandler",
  1462. "Tcl_LimitCheck", "Tcl_LimitExceeded", "Tcl_LimitGetCommands", "Tcl_LimitGetGranularity",
  1463. "Tcl_LimitGetTime", "Tcl_LimitReady", "Tcl_LimitRemoveHandler", "Tcl_LimitSetCommands",
  1464. "Tcl_LimitSetGranularity", "Tcl_LimitSetTime", "Tcl_LimitTypeEnabled", "Tcl_LimitTypeExceeded",
  1465. "Tcl_LimitTypeReset", "Tcl_LimitTypeSet", "Tcl_LinkVar", "Tcl_ListMathFuncs", "Tcl_ListObjAppendElement",
  1466. "Tcl_ListObjAppendList", "Tcl_ListObjGetElements", "Tcl_ListObjIndex", "Tcl_ListObjLength",
  1467. "Tcl_ListObjReplace", "Tcl_LogCommandInfo", "Tcl_Main", "Tcl_MakeFileChannel", "Tcl_MakeSafe",
  1468. "Tcl_MakeTcpClientChannel", "Tcl_Merge", "Tcl_MethodDeclarerClass", "Tcl_MethodDeclarerObject",
  1469. "Tcl_MethodIsPublic", "Tcl_MethodIsType", "Tcl_MethodName", "Tcl_MutexFinalize", "Tcl_MutexLock",
  1470. "Tcl_MutexUnlock", "Tcl_NewBignumObj", "Tcl_NewBooleanObj", "Tcl_NewByteArrayObj", "Tcl_NewDictObj",
  1471. "Tcl_NewDoubleObj", "Tcl_NewInstanceMethod", "Tcl_NewIntObj", "Tcl_NewListObj", "Tcl_NewLongObj",
  1472. "Tcl_NewMethod", "Tcl_NewObj", "Tcl_NewObjectInstance", "Tcl_NewStringObj", "Tcl_NewUnicodeObj",
  1473. "Tcl_NewWideIntObj", "Tcl_NextHashEntry", "Tcl_NotifyChannel", "Tcl_NRAddCallback", "Tcl_NRCallObjProc",
  1474. "Tcl_NRCmdSwap", "Tcl_NRCreateCommand", "Tcl_NREvalObj", "Tcl_NREvalObjv", "Tcl_NumUtfChars",
  1475. "Tcl_ObjectContextInvokeNext", "Tcl_ObjectContextIsFiltering", "Tcl_ObjectContextMethod",
  1476. "Tcl_ObjectContextObject", "Tcl_ObjectContextSkippedArgs", "Tcl_ObjectDeleted", "Tcl_ObjectGetMetadata",
  1477. "Tcl_ObjectGetMethodNameMapper", "Tcl_ObjectSetMetadata", "Tcl_ObjectSetMethodNameMapper", "Tcl_ObjGetVar2",
  1478. "Tcl_ObjPrintf", "Tcl_ObjSetVar2", "Tcl_OpenCommandChannel", "Tcl_OpenFileChannel", "Tcl_OpenTcpClient",
  1479. "Tcl_OpenTcpServer", "Tcl_OutputBuffered", "Tcl_Panic", "Tcl_PanicVA", "Tcl_ParseArgsObjv",
  1480. "Tcl_ParseBraces", "Tcl_ParseCommand", "Tcl_ParseExpr", "Tcl_ParseQuotedString", "Tcl_ParseVar",
  1481. "Tcl_ParseVarName", "Tcl_PkgPresent", "Tcl_PkgPresentEx", "Tcl_PkgProvide", "Tcl_PkgProvideEx",
  1482. "Tcl_PkgRequire", "Tcl_PkgRequireEx", "Tcl_PkgRequireProc", "Tcl_PosixError", "Tcl_Preserve",
  1483. "Tcl_PrintDouble", "Tcl_PutEnv", "Tcl_QueryTimeProc", "Tcl_QueueEvent", "Tcl_Read", "Tcl_ReadChars",
  1484. "Tcl_ReadRaw", "Tcl_Realloc", "Tcl_ReapDetachedProcs", "Tcl_RecordAndEval", "Tcl_RecordAndEvalObj",
  1485. "Tcl_RegExpCompile", "Tcl_RegExpExec", "Tcl_RegExpExecObj", "Tcl_RegExpGetInfo", "Tcl_RegExpMatch",
  1486. "Tcl_RegExpMatchObj", "Tcl_RegExpRange", "Tcl_RegisterChannel", "Tcl_RegisterConfig", "Tcl_RegisterObjType",
  1487. "Tcl_Release", "Tcl_ResetResult", "Tcl_RestoreInterpState", "Tcl_RestoreResult", "Tcl_SaveInterpState",
  1488. "Tcl_SaveResult", "Tcl_ScanCountedElement", "Tcl_ScanElement", "Tcl_Seek", "Tcl_ServiceAll",
  1489. "Tcl_ServiceEvent", "Tcl_ServiceModeHook", "Tcl_SetAssocData", "Tcl_SetBignumObj", "Tcl_SetBooleanObj",
  1490. "Tcl_SetByteArrayLength", "Tcl_SetByteArrayObj", "Tcl_SetChannelBufferSize", "Tcl_SetChannelError",
  1491. "Tcl_SetChannelErrorInterp", "Tcl_SetChannelOption", "Tcl_SetCommandInfo", "Tcl_SetCommandInfoFromToken",
  1492. "Tcl_SetDefaultEncodingDir", "Tcl_SetDoubleObj", "Tcl_SetEncodingSearchPath", "Tcl_SetEnsembleFlags",
  1493. "Tcl_SetEnsembleMappingDict", "Tcl_SetEnsembleParameterList", "Tcl_SetEnsembleSubcommandList",
  1494. "Tcl_SetEnsembleUnknownHandler", "Tcl_SetErrno", "Tcl_SetErrorCode", "Tcl_SetErrorCodeVA",
  1495. "Tcl_SetErrorLine", "Tcl_SetExitProc", "Tcl_SetHashValue", "Tcl_SetIntObj", "Tcl_SetListObj",
  1496. "Tcl_SetLongObj", "Tcl_SetMainLoop", "Tcl_SetMaxBlockTime", "Tcl_SetNamespaceUnknownHandler",
  1497. "Tcl_SetNotifier", "Tcl_SetObjErrorCode", "Tcl_SetObjLength", "Tcl_SetObjResult", "Tcl_SetPanicProc",
  1498. "Tcl_SetRecursionLimit", "Tcl_SetResult", "Tcl_SetReturnOptions", "Tcl_SetServiceMode",
  1499. "Tcl_SetStartupScript", "Tcl_SetStdChannel", "Tcl_SetStringObj", "Tcl_SetSystemEncoding", "Tcl_SetTimeProc",
  1500. "Tcl_SetTimer", "Tcl_SetUnicodeObj", "Tcl_SetVar", "Tcl_SetVar2", "Tcl_SetVar2Ex", "Tcl_SetWideIntObj",
  1501. "Tcl_SignalId", "Tcl_SignalMsg", "Tcl_Sleep", "Tcl_SourceRCFile", "Tcl_SpliceChannel", "Tcl_SplitList",
  1502. "Tcl_SplitPath", "Tcl_StackChannel", "Tcl_StandardChannels", "Tcl_Stat", "Tcl_StaticPackage",
  1503. "Tcl_StringCaseMatch", "Tcl_StringMatch", "Tcl_SubstObj", "Tcl_TakeBignumFromObj", "Tcl_Tell",
  1504. "Tcl_ThreadAlert", "Tcl_ThreadQueueEvent", "Tcl_TraceCommand", "Tcl_TraceVar", "Tcl_TraceVar2",
  1505. "Tcl_TransferResult", "Tcl_TranslateFileName", "Tcl_TruncateChannel", "Tcl_Ungets", "Tcl_UniChar",
  1506. "Tcl_UniCharAtIndex", "Tcl_UniCharCaseMatch", "Tcl_UniCharIsAlnum", "Tcl_UniCharIsAlpha",
  1507. "Tcl_UniCharIsControl", "Tcl_UniCharIsDigit", "Tcl_UniCharIsGraph", "Tcl_UniCharIsLower",
  1508. "Tcl_UniCharIsPrint", "Tcl_UniCharIsPunct", "Tcl_UniCharIsSpace", "Tcl_UniCharIsUpper",
  1509. "Tcl_UniCharIsWordChar", "Tcl_UniCharLen", "Tcl_UniCharNcasecmp", "Tcl_UniCharNcmp", "Tcl_UniCharToLower",
  1510. "Tcl_UniCharToTitle", "Tcl_UniCharToUpper", "Tcl_UniCharToUtf", "Tcl_UniCharToUtfDString", "Tcl_UnlinkVar",
  1511. "Tcl_UnregisterChannel", "Tcl_UnsetVar", "Tcl_UnsetVar2", "Tcl_UnstackChannel", "Tcl_UntraceCommand",
  1512. "Tcl_UntraceVar", "Tcl_UntraceVar2", "Tcl_UpdateLinkedVar", "Tcl_UpVar", "Tcl_UpVar2", "Tcl_UtfAtIndex",
  1513. "Tcl_UtfBackslash", "Tcl_UtfCharComplete", "Tcl_UtfFindFirst", "Tcl_UtfFindLast", "Tcl_UtfNext",
  1514. "Tcl_UtfPrev", "Tcl_UtfToExternal", "Tcl_UtfToExternalDString", "Tcl_UtfToLower", "Tcl_UtfToTitle",
  1515. "Tcl_UtfToUniChar", "Tcl_UtfToUniCharDString", "Tcl_UtfToUpper", "Tcl_ValidateAllMemory", "Tcl_VarEval",
  1516. "Tcl_VarEvalVA", "Tcl_VarTraceInfo", "Tcl_VarTraceInfo2", "Tcl_WaitForEvent", "Tcl_WaitPid",
  1517. "Tcl_WinTCharToUtf", "Tcl_WinUtfToTChar", "Tcl_Write", "Tcl_WriteChars", "Tcl_WriteObj", "Tcl_WriteRaw",
  1518. "Tcl_WrongNumArgs", "Tcl_ZlibAdler32", "Tcl_ZlibCRC32", "Tcl_ZlibDeflate", "Tcl_ZlibInflate",
  1519. "Tcl_ZlibStreamChecksum", "Tcl_ZlibStreamClose", "Tcl_ZlibStreamEof", "Tcl_ZlibStreamGet",
  1520. "Tcl_ZlibStreamGetCommandName", "Tcl_ZlibStreamInit", "Tcl_ZlibStreamPut", "dde", "http", "msgcat",
  1521. "registry", "tcltest", "Tcl_AllocHashEntryProc", "Tcl_AppInitProc", "Tcl_ArgvInfo", "Tcl_AsyncProc",
  1522. "Tcl_ChannelProc", "Tcl_ChannelType", "Tcl_CloneProc", "Tcl_CloseProc", "Tcl_CmdDeleteProc", "Tcl_CmdInfo",
  1523. "Tcl_CmdObjTraceDeleteProc", "Tcl_CmdObjTraceProc", "Tcl_CmdProc", "Tcl_CmdTraceProc",
  1524. "Tcl_CommandTraceProc", "Tcl_CompareHashKeysProc", "Tcl_Config", "Tcl_DriverBlockModeProc",
  1525. "Tcl_DriverClose2Proc", "Tcl_DriverCloseProc", "Tcl_DriverFlushProc", "Tcl_DriverGetHandleProc",
  1526. "Tcl_DriverGetOptionProc", "Tcl_DriverHandlerProc", "Tcl_DriverInputProc", "Tcl_DriverOutputProc",
  1527. "Tcl_DriverSeekProc", "Tcl_DriverSetOptionProc", "Tcl_DriverThreadActionProc", "Tcl_DriverTruncateProc",
  1528. "Tcl_DriverWatchProc", "Tcl_DriverWideSeekProc", "Tcl_DupInternalRepProc", "Tcl_EncodingConvertProc",
  1529. "Tcl_EncodingFreeProc", "Tcl_EncodingType", "Tcl_Event", "Tcl_EventCheckProc", "Tcl_EventDeleteProc",
  1530. "Tcl_EventProc", "Tcl_EventSetupProc", "Tcl_ExitProc", "Tcl_FileProc", "Tcl_Filesystem",
  1531. "Tcl_FreeHashEntryProc", "Tcl_FreeInternalRepProc", "Tcl_FreeProc", "Tcl_FSAccessProc", "Tcl_FSChdirProc",
  1532. "Tcl_FSCopyDirectoryProc", "Tcl_FSCopyFileProc", "Tcl_FSCreateDirectoryProc", "Tcl_FSCreateInternalRepProc",
  1533. "Tcl_FSDeleteFileProc", "Tcl_FSDupInternalRepProc", "Tcl_FSFileAttrsGetProc", "Tcl_FSFileAttrsSetProc",
  1534. "Tcl_FSFilesystemPathTypeProc", "Tcl_FSFilesystemSeparatorProc", "Tcl_FSFreeInternalRepProc",
  1535. "Tcl_FSGetCwdProc", "Tcl_FSInternalToNormalizedProc", "Tcl_FSLinkProc", "Tcl_FSListVolumesProc",
  1536. "Tcl_FSLoadFileProc", "Tcl_FSLstatProc", "Tcl_FSMatchInDirectoryProc", "Tcl_FSNormalizePathProc",
  1537. "Tcl_FSOpenFileChannelProc", "Tcl_FSPathInFilesystemProc", "Tcl_FSRemoveDirectoryProc",
  1538. "Tcl_FSRenameFileProc", "Tcl_FSStatProc", "Tcl_FSUnloadFileProc", "Tcl_FSUtimeProc", "Tcl_GlobTypeData",
  1539. "Tcl_HashKeyType", "Tcl_IdleProc", "Tcl_Interp", "Tcl_InterpDeleteProc", "Tcl_LimitHandlerDeleteProc",
  1540. "Tcl_LimitHandlerProc", "Tcl_MainLoopProc", "Tcl_MathProc", "Tcl_MethodCallProc", "Tcl_MethodDeleteProc",
  1541. "Tcl_MethodType", "Tcl_NamespaceDeleteProc", "Tcl_NotifierProcs", "Tcl_Obj", "Tcl_ObjCmdProc",
  1542. "Tcl_ObjectMapMethodNameProc", "Tcl_ObjectMetadataDeleteProc", "Tcl_ObjType", "Tcl_PackageInitProc",
  1543. "Tcl_PackageUnloadProc", "Tcl_PanicProc", "Tcl_RegExpIndices", "Tcl_RegExpInfo", "Tcl_ScaleTimeProc",
  1544. "Tcl_SetFromAnyProc", "Tcl_TcpAcceptProc", "Tcl_Time", "Tcl_TimerProc", "Tcl_Token", "Tcl_UpdateStringProc",
  1545. "Tcl_Value", "Tcl_VarTraceProc", "argc", "argv", "argv0", "auto_path", "env", "errorCode", "errorInfo",
  1546. "filename", "re_syntax", "safe", "Tcl", "tcl_interactive", "tcl_library", "TCL_MEM_DEBUG",
  1547. "tcl_nonwordchars", "tcl_patchLevel", "tcl_pkgPath", "tcl_platform", "tcl_precision", "tcl_rcFileName",
  1548. "tcl_traceCompile", "tcl_traceEval", "tcl_version", "tcl_wordchars"
  1549. ]
  1550. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1551. self.shell = FCShell(self, version=self.version)
  1552. self.shell._edit.set_model_data(self.myKeywords)
  1553. self.ui.code_editor.set_model_data(self.myKeywords)
  1554. self.shell.setWindowIcon(self.ui.app_icon)
  1555. self.shell.setWindowTitle("FlatCAM Shell")
  1556. self.shell.resize(*self.defaults["global_shell_shape"])
  1557. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1558. self.shell.append_output("(Type help to get started)\n\n")
  1559. self.init_tcl()
  1560. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1561. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1562. self.ui.shell_dock.setWidget(self.shell)
  1563. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1564. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1565. QtWidgets.QDockWidget.DockWidgetFloatable |
  1566. QtWidgets.QDockWidget.DockWidgetClosable)
  1567. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1568. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1569. if self.defaults["global_shell_at_startup"]:
  1570. self.ui.shell_dock.show()
  1571. else:
  1572. self.ui.shell_dock.hide()
  1573. # ###################### ##
  1574. # # ## Tools and Plugins # ##
  1575. # ###################### ##
  1576. self.dblsidedtool = None
  1577. self.measurement_tool = None
  1578. self.panelize_tool = None
  1579. self.film_tool = None
  1580. self.paste_tool = None
  1581. self.calculator_tool = None
  1582. self.sub_tool = None
  1583. self.move_tool = None
  1584. self.cutout_tool = None
  1585. self.ncclear_tool = None
  1586. self.paint_tool = None
  1587. self.transform_tool = None
  1588. self.properties_tool = None
  1589. self.pdf_tool = None
  1590. self.image_tool = None
  1591. self.pcb_wizard_tool = None
  1592. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1593. self.install_tools()
  1594. # # ## System Font Parsing # ##
  1595. # self.f_parse = ParseFont(self)
  1596. # self.parse_system_fonts()
  1597. # test if the program was started with a script as parameter
  1598. if self.cmd_line_shellfile:
  1599. try:
  1600. with open(self.cmd_line_shellfile, "r") as myfile:
  1601. cmd_line_shellfile_text = myfile.read()
  1602. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1603. except Exception as ext:
  1604. print("ERROR: ", ext)
  1605. sys.exit(2)
  1606. # ######################## ##
  1607. # # ## Check for updates ## ##
  1608. # ######################## ##
  1609. # Separate thread (Not worker)
  1610. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1611. if (self.beta is False or self.beta is None) and \
  1612. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1613. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1614. self.thr2 = QtCore.QThread()
  1615. self.worker_task.emit({'fcn': self.version_check,
  1616. 'params': []})
  1617. self.thr2.start(QtCore.QThread.LowPriority)
  1618. # ################################# ##
  1619. # # ## Variables for global usage ## ##
  1620. # ################################# ##
  1621. # coordinates for relative position display
  1622. self.rel_point1 = (0, 0)
  1623. self.rel_point2 = (0, 0)
  1624. # variable to store coordinates
  1625. self.pos = (0, 0)
  1626. self.pos_jump = (0, 0)
  1627. # decide if we have a double click or single click
  1628. self.doubleclick = False
  1629. # variable to store if a command is active (then the var is not None) and which one it is
  1630. self.command_active = None
  1631. # variable to store the status of moving selection action
  1632. # None value means that it's not an selection action
  1633. # True value = a selection from left to right
  1634. # False value = a selection from right to left
  1635. self.selection_type = None
  1636. # List to store the objects that are currently loaded in FlatCAM
  1637. # This list is updated on each object creation or object delete
  1638. self.all_objects_list = []
  1639. # List to store the objects that are selected
  1640. self.sel_objects_list = []
  1641. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1642. self.key_modifiers = None
  1643. # Variable to hold the status of the axis
  1644. self.toggle_axis = True
  1645. # Variable to store the status of the fullscreen event
  1646. self.toggle_fscreen = False
  1647. # Variable to store the status of the code editor
  1648. self.toggle_codeeditor = False
  1649. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1650. self.click_noproject = False
  1651. self.cursor = None
  1652. # Variable to store the GCODE that was edited
  1653. self.gcode_edited = ""
  1654. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1655. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1656. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1657. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1658. ]
  1659. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1660. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1661. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1662. 'mpf'
  1663. ]
  1664. self.svg_list = ['svg']
  1665. self.dxf_list = ['dxf']
  1666. self.pdf_list = ['pdf']
  1667. self.prj_list = ['flatprj']
  1668. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1669. # flag for polygons not cleared
  1670. self.poly_not_cleared = False
  1671. # VisPy visuals
  1672. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.vispy_canvas.view.scene, layers=1)
  1673. self.isHovering = False
  1674. self.notHovering = True
  1675. # # ## Save defaults to factory_defaults.FlatConfig file # ##
  1676. # # ## It's done only once after install ########### ##
  1677. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1678. fac_def_from_file = factory_file.read()
  1679. factory_defaults = json.loads(fac_def_from_file)
  1680. # if the file contain an empty dictionary then save the factory defaults into the file
  1681. if not factory_defaults:
  1682. self.save_factory_defaults(silent=False)
  1683. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1684. initial_lay = 'compact'
  1685. self.on_layout(lay=initial_lay)
  1686. # Set the combobox in Preferences to the current layout
  1687. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1688. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1689. factory_file.close()
  1690. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1691. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1692. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1693. # Post-GUI initialization: Experimental attempt
  1694. # to perform unit tests on the GUI.
  1695. # if post_gui is not None:
  1696. # post_gui(self)
  1697. App.log.debug("END of constructor. Releasing control.")
  1698. # accept a project file as command line parameter
  1699. # the path/file_name must be enclosed in quotes if it contain spaces
  1700. for argument in App.args:
  1701. if '.FlatPrj' in argument:
  1702. try:
  1703. project_name = str(argument)
  1704. if project_name == "":
  1705. self.inform.emit(_("Open cancelled."))
  1706. else:
  1707. # self.open_project(project_name)
  1708. run_from_arg = True
  1709. self.worker_task.emit({'fcn': self.open_project,
  1710. 'params': [project_name, run_from_arg]})
  1711. except Exception as e:
  1712. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1713. if '.FlatConfig' in argument:
  1714. try:
  1715. file_name = str(argument)
  1716. if file_name == "":
  1717. self.inform.emit(_("Open Config file failed."))
  1718. else:
  1719. # run_from_arg = True
  1720. # self.worker_task.emit({'fcn': self.open_config_file,
  1721. # 'params': [file_name, run_from_arg]})
  1722. self.open_config_file(file_name, run_from_arg=True)
  1723. except Exception as e:
  1724. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1725. if '.FlatScript' in argument:
  1726. try:
  1727. file_name = str(argument)
  1728. if file_name == "":
  1729. self.inform.emit(_("Open Script file failed."))
  1730. else:
  1731. # run_from_arg = True
  1732. # self.worker_task.emit({'fcn': self.open_script_file,
  1733. # 'params': [file_name, run_from_arg]})
  1734. self.on_filerunscript(name=file_name)
  1735. except Exception as e:
  1736. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1737. def defaults_read_form(self):
  1738. for option in self.defaults_form_fields:
  1739. try:
  1740. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1741. except Exception as e:
  1742. log.debug("App.defaults_read_form() --> %s" % str(e))
  1743. def defaults_write_form(self, factor=None):
  1744. for option in self.defaults:
  1745. self.defaults_write_form_field(option, factor=factor)
  1746. # try:
  1747. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1748. # except KeyError:
  1749. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1750. # # TODO: Rethink this?
  1751. # pass
  1752. def defaults_write_form_field(self, field, factor=None):
  1753. try:
  1754. if factor is None:
  1755. self.defaults_form_fields[field].set_value(self.defaults[field])
  1756. else:
  1757. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  1758. except KeyError:
  1759. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  1760. # TODO: Rethink this?
  1761. pass
  1762. except AttributeError:
  1763. log.debug(field)
  1764. def clear_pool(self):
  1765. self.pool.close()
  1766. self.pool = Pool()
  1767. self.pool_recreated.emit(self.pool)
  1768. gc.collect()
  1769. # the order that the tools are installed is important as they can depend on each other install position
  1770. def install_tools(self):
  1771. self.dblsidedtool = DblSidedTool(self)
  1772. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1773. self.measurement_tool = Measurement(self)
  1774. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1775. self.panelize_tool = Panelize(self)
  1776. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1777. self.film_tool = Film(self)
  1778. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1779. self.paste_tool = SolderPaste(self)
  1780. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  1781. self.calculator_tool = ToolCalculator(self)
  1782. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1783. self.sub_tool = ToolSub(self)
  1784. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menuedit_convert,
  1785. before=self.ui.menuedit_convert_sg2mg)
  1786. self.move_tool = ToolMove(self)
  1787. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1788. before=self.ui.menueditorigin)
  1789. self.cutout_tool = CutOut(self)
  1790. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  1791. before=self.measurement_tool.menuAction)
  1792. self.ncclear_tool = NonCopperClear(self)
  1793. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  1794. before=self.measurement_tool.menuAction, separator=True)
  1795. self.paint_tool = ToolPaint(self)
  1796. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1797. before=self.measurement_tool.menuAction, separator=True)
  1798. self.transform_tool = ToolTransform(self)
  1799. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1800. self.properties_tool = Properties(self)
  1801. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1802. self.pdf_tool = ToolPDF(self)
  1803. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  1804. separator=True)
  1805. self.image_tool = ToolImage(self)
  1806. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1807. separator=True)
  1808. self.pcb_wizard_tool = PcbWizard(self)
  1809. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  1810. self.log.debug("Tools are installed.")
  1811. def remove_tools(self):
  1812. for act in self.ui.menutool.actions():
  1813. self.ui.menutool.removeAction(act)
  1814. def init_tools(self):
  1815. log.debug("init_tools()")
  1816. # delete the data currently in the Tools Tab and the Tab itself
  1817. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1818. if widget is not None:
  1819. widget.deleteLater()
  1820. self.ui.notebook.removeTab(2)
  1821. # rebuild the Tools Tab
  1822. self.ui.tool_tab = QtWidgets.QWidget()
  1823. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1824. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1825. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1826. self.ui.tool_scroll_area = VerticalScrollArea()
  1827. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1828. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1829. # first remove all of them
  1830. self.remove_tools()
  1831. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1832. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1833. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1834. # third install all of them
  1835. self.install_tools()
  1836. self.log.debug("Tools are initialized.")
  1837. # def parse_system_fonts(self):
  1838. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1839. # 'params': []})
  1840. def connect_toolbar_signals(self):
  1841. # Toolbar
  1842. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1843. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1844. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1845. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1846. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1847. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1848. self.ui.replot_btn.triggered.connect(self.plot_all)
  1849. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1850. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1851. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1852. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1853. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1854. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1855. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1856. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1857. self.ui.delete_btn.triggered.connect(self.on_delete)
  1858. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  1859. # Tools Toolbar Signals
  1860. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1861. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1862. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1863. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1864. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1865. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1866. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1867. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1868. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1869. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1870. def object2editor(self):
  1871. """
  1872. Send the current Geometry or Excellon object (if any) into the editor.
  1873. :return: None
  1874. """
  1875. self.report_usage("object2editor()")
  1876. edited_object = self.collection.get_active()
  1877. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  1878. isinstance(edited_object, FlatCAMExcellon):
  1879. pass
  1880. else:
  1881. self.inform.emit(_("[WARNING_NOTCL] Select a Geometry, Gerber or Excellon Object to edit."))
  1882. return
  1883. if isinstance(edited_object, FlatCAMGeometry):
  1884. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1885. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1886. if edited_object.multigeo is True:
  1887. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  1888. if len(edited_tools) > 1:
  1889. self.inform.emit(_("[WARNING_NOTCL] Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  1890. "is not possible.\n"
  1891. "Edit only one geometry at a time."))
  1892. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=edited_tools[0])
  1893. else:
  1894. self.geo_editor.edit_fcgeometry(edited_object)
  1895. # we set the notebook to hidden
  1896. self.ui.splitter.setSizes([0, 1])
  1897. # set call source to the Editor we go into
  1898. self.call_source = 'geo_editor'
  1899. elif isinstance(edited_object, FlatCAMExcellon):
  1900. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1901. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1902. self.exc_editor.edit_fcexcellon(edited_object)
  1903. # set call source to the Editor we go into
  1904. self.call_source = 'exc_editor'
  1905. if self.ui.splitter.sizes()[0] == 0:
  1906. self.ui.splitter.setSizes([1, 1])
  1907. elif isinstance(edited_object, FlatCAMGerber):
  1908. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1909. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1910. self.grb_editor.edit_fcgerber(edited_object)
  1911. # set call source to the Editor we go into
  1912. self.call_source = 'grb_editor'
  1913. if self.ui.splitter.sizes()[0] == 0:
  1914. self.ui.splitter.setSizes([1, 1])
  1915. # # make sure that we can't select another object while in Editor Mode:
  1916. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1917. self.ui.project_frame.setDisabled(True)
  1918. # delete any selection shape that might be active as they are not relevant in Editor
  1919. self.delete_selection_shape()
  1920. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1921. self.ui.plot_tab_area.protectTab(0)
  1922. self.inform.emit(_("[WARNING_NOTCL] Editor is activated ..."))
  1923. self.should_we_save = True
  1924. def editor2object(self, cleanup=None):
  1925. """
  1926. Transfers the Geometry or Excellon from the editor to the current object.
  1927. :return: None
  1928. """
  1929. self.report_usage("editor2object()")
  1930. # do not update a geometry or excellon object unless it comes out of an editor
  1931. if self.call_source != 'app':
  1932. edited_obj = self.collection.get_active()
  1933. if cleanup is None:
  1934. msgbox = QtWidgets.QMessageBox()
  1935. msgbox.setText(_("Do you want to save the edited object?"))
  1936. msgbox.setWindowTitle(_("Close Editor"))
  1937. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  1938. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1939. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1940. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1941. msgbox.setDefaultButton(bt_yes)
  1942. msgbox.exec_()
  1943. response = msgbox.clickedButton()
  1944. if response == bt_yes:
  1945. # clean the Tools Tab
  1946. self.ui.tool_scroll_area.takeWidget()
  1947. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1948. self.ui.notebook.setTabText(2, "Tool")
  1949. if isinstance(edited_obj, FlatCAMGeometry):
  1950. obj_type = "Geometry"
  1951. if cleanup is None:
  1952. self.geo_editor.update_fcgeometry(edited_obj)
  1953. self.geo_editor.update_options(edited_obj)
  1954. self.geo_editor.deactivate()
  1955. # update the geo object options so it is including the bounding box values
  1956. try:
  1957. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1958. edited_obj.options['xmin'] = xmin
  1959. edited_obj.options['ymin'] = ymin
  1960. edited_obj.options['xmax'] = xmax
  1961. edited_obj.options['ymax'] = ymax
  1962. except AttributeError as e:
  1963. self.inform.emit(_("[WARNING] Object empty after edit."))
  1964. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1965. elif isinstance(edited_obj, FlatCAMGerber):
  1966. obj_type = "Gerber"
  1967. if cleanup is None:
  1968. self.grb_editor.update_fcgerber()
  1969. self.grb_editor.update_options(edited_obj)
  1970. self.grb_editor.deactivate_grb_editor()
  1971. # delete the old object (the source object) if it was an empty one
  1972. if len(edited_obj.solid_geometry) == 0:
  1973. old_name = edited_obj.options['name']
  1974. self.collection.set_active(old_name)
  1975. self.collection.delete_active()
  1976. elif isinstance(edited_obj, FlatCAMExcellon):
  1977. obj_type = "Excellon"
  1978. if cleanup is None:
  1979. self.exc_editor.update_fcexcellon(edited_obj)
  1980. self.exc_editor.update_options(edited_obj)
  1981. self.exc_editor.deactivate()
  1982. else:
  1983. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1984. return
  1985. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  1986. elif response == bt_no:
  1987. # clean the Tools Tab
  1988. self.ui.tool_scroll_area.takeWidget()
  1989. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1990. self.ui.notebook.setTabText(2, "Tool")
  1991. if isinstance(edited_obj, FlatCAMGeometry):
  1992. self.geo_editor.deactivate()
  1993. elif isinstance(edited_obj, FlatCAMGerber):
  1994. self.grb_editor.deactivate_grb_editor()
  1995. elif isinstance(edited_obj, FlatCAMExcellon):
  1996. self.exc_editor.deactivate()
  1997. # set focus on the project tab
  1998. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  1999. else:
  2000. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  2001. return
  2002. elif response == bt_cancel:
  2003. return
  2004. else:
  2005. if isinstance(edited_obj, FlatCAMGeometry):
  2006. self.geo_editor.deactivate()
  2007. elif isinstance(edited_obj, FlatCAMGerber):
  2008. self.grb_editor.deactivate_grb_editor()
  2009. elif isinstance(edited_obj, FlatCAMExcellon):
  2010. self.exc_editor.deactivate()
  2011. else:
  2012. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  2013. return
  2014. # if notebook is hidden we show it
  2015. if self.ui.splitter.sizes()[0] == 0:
  2016. self.ui.splitter.setSizes([1, 1])
  2017. # restore the call_source to app
  2018. self.call_source = 'app'
  2019. edited_obj.plot()
  2020. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2021. self.ui.plot_tab_area.protectTab(0)
  2022. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2023. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2024. self.ui.project_frame.setDisabled(False)
  2025. def get_last_folder(self):
  2026. return self.defaults["global_last_folder"]
  2027. def get_last_save_folder(self):
  2028. loc = self.defaults["global_last_save_folder"]
  2029. if loc is None:
  2030. loc = self.defaults["global_last_folder"]
  2031. if loc is None:
  2032. loc = os.path.dirname(__file__)
  2033. return loc
  2034. def report_usage(self, resource):
  2035. """
  2036. Increments usage counter for the given resource
  2037. in self.defaults['global_stats'].
  2038. :param resource: Name of the resource.
  2039. :return: None
  2040. """
  2041. if resource in self.defaults['global_stats']:
  2042. self.defaults['global_stats'][resource] += 1
  2043. else:
  2044. self.defaults['global_stats'][resource] = 1
  2045. def init_tcl(self):
  2046. if hasattr(self, 'tcl'):
  2047. # self.tcl = None
  2048. # TODO we need to clean non default variables and procedures here
  2049. # new object cannot be used here as it will not remember values created for next passes,
  2050. # because tcl was execudted in old instance of TCL
  2051. pass
  2052. else:
  2053. self.tcl = tk.Tcl()
  2054. self.setup_shell()
  2055. self.log.debug("TCL Shell has been initialized.")
  2056. # TODO: This shouldn't be here.
  2057. class TclErrorException(Exception):
  2058. """
  2059. this exception is defined here, to be able catch it if we ssuccessfully handle all errors from shell command
  2060. """
  2061. pass
  2062. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2063. """
  2064. Shows a message on the FlatCAM Shell
  2065. :param msg: Message to display.
  2066. :param show: Opens the shell.
  2067. :param error: Shows the message as an error.
  2068. :param warning: Shows the message as an warning.
  2069. :param warning: Shows the message as an success.
  2070. :param selected: Indicate that something was selected on canvas
  2071. :return: None
  2072. """
  2073. if show:
  2074. self.ui.shell_dock.show()
  2075. try:
  2076. if error:
  2077. self.shell.append_error(msg + "\n")
  2078. elif warning:
  2079. self.shell.append_warning(msg + "\n")
  2080. elif success:
  2081. self.shell.append_success(msg + "\n")
  2082. elif selected:
  2083. self.shell.append_selected(msg + "\n")
  2084. else:
  2085. self.shell.append_output(msg + "\n")
  2086. except AttributeError:
  2087. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2088. def raise_tcl_unknown_error(self, unknownException):
  2089. """
  2090. Raise exception if is different type than TclErrorException
  2091. this is here mainly to show unknown errors inside TCL shell console.
  2092. :param unknownException:
  2093. :return:
  2094. """
  2095. if not isinstance(unknownException, self.TclErrorException):
  2096. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2097. else:
  2098. raise unknownException
  2099. def display_tcl_error(self, error, error_info=None):
  2100. """
  2101. Escape bracket [ with '\' otherwise there is error
  2102. "ERROR: missing close-bracket" instead of real error
  2103. :param error: it may be text or exception
  2104. :param error_info: Some informations about the error
  2105. :return: None
  2106. """
  2107. if isinstance(error, Exception):
  2108. exc_type, exc_value, exc_traceback = error_info
  2109. if not isinstance(error, self.TclErrorException):
  2110. show_trace = 1
  2111. else:
  2112. show_trace = int(self.defaults['global_verbose_error_level'])
  2113. if show_trace > 0:
  2114. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2115. trc_formated = []
  2116. for a in reversed(trc):
  2117. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2118. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2119. else:
  2120. text = "%s" % error
  2121. else:
  2122. text = error
  2123. text = text.replace('[', '\\[').replace('"', '\\"')
  2124. self.tcl.eval('return -code error "%s"' % text)
  2125. def raise_tcl_error(self, text):
  2126. """
  2127. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2128. :param text: text of error
  2129. :return: raise exception
  2130. """
  2131. self.display_tcl_error(text)
  2132. raise self.TclErrorException(text)
  2133. def exec_command(self, text):
  2134. """
  2135. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2136. Also handles execution in separated threads
  2137. :param text:
  2138. :return: output if there was any
  2139. """
  2140. self.report_usage('exec_command')
  2141. result = self.exec_command_test(text, False)
  2142. # MS: added this method call so the geometry is updated once the TCL command is executed
  2143. self.plot_all()
  2144. return result
  2145. def exec_command_test(self, text, reraise=True):
  2146. """
  2147. Same as exec_command(...) with additional control over exceptions.
  2148. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2149. :param text: Input command
  2150. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2151. :return: Output from the command
  2152. """
  2153. text = str(text)
  2154. try:
  2155. self.shell.open_proccessing() # Disables input box.
  2156. result = self.tcl.eval(str(text))
  2157. if result != 'None':
  2158. self.shell.append_output(result + '\n')
  2159. except tk.TclError as e:
  2160. # This will display more precise answer if something in TCL shell fails
  2161. result = self.tcl.eval("set errorInfo")
  2162. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2163. self.shell.append_error('ERROR: ' + result + '\n')
  2164. # Show error in console and just return or in test raise exception
  2165. if reraise:
  2166. raise e
  2167. finally:
  2168. self.shell.close_proccessing()
  2169. pass
  2170. return result
  2171. # """
  2172. # Code below is unsused. Saved for later.
  2173. # """
  2174. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2175. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2176. # self.log.debug(parts)
  2177. # try:
  2178. # if parts[0] not in commands:
  2179. # self.shell.append_error("Unknown command\n")
  2180. # return
  2181. #
  2182. # #import inspect
  2183. # #inspect.getargspec(someMethod)
  2184. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2185. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2186. # self.shell.append_error(
  2187. # "Command %s takes %d arguments. %d given.\n" %
  2188. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2189. # )
  2190. # return
  2191. #
  2192. # cmdfcn = commands[parts[0]]["fcn"]
  2193. # cmdconv = commands[parts[0]]["converters"]
  2194. # if len(parts) - 1 > 0:
  2195. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2196. # else:
  2197. # retval = cmdfcn()
  2198. # retfcn = commands[parts[0]]["retfcn"]
  2199. # if retval and retfcn(retval):
  2200. # self.shell.append_output(retfcn(retval) + "\n")
  2201. #
  2202. # except Exception as e:
  2203. # #self.shell.append_error(''.join(traceback.format_exc()))
  2204. # #self.shell.append_error("?\n")
  2205. # self.shell.append_error(str(e) + "\n")
  2206. def info(self, msg):
  2207. """
  2208. Informs the user. Normally on the status bar, optionally
  2209. also on the shell.
  2210. :param msg: Text to write.
  2211. :return: None
  2212. """
  2213. # Type of message in brackets at the beginning of the message.
  2214. match = re.search("\[([^\]]+)\](.*)", msg)
  2215. if match:
  2216. level = match.group(1)
  2217. msg_ = match.group(2)
  2218. self.ui.fcinfo.set_status(str(msg_), level=level)
  2219. if level.lower() == "error":
  2220. self.shell_message(msg, error=True, show=True)
  2221. elif level.lower() == "warning":
  2222. self.shell_message(msg, warning=True, show=True)
  2223. elif level.lower() == "error_notcl":
  2224. self.shell_message(msg, error=True, show=False)
  2225. elif level.lower() == "warning_notcl":
  2226. self.shell_message(msg, warning=True, show=False)
  2227. elif level.lower() == "success":
  2228. self.shell_message(msg, success=True, show=False)
  2229. elif level.lower() == "selected":
  2230. self.shell_message(msg, selected=True, show=False)
  2231. else:
  2232. self.shell_message(msg, show=False)
  2233. else:
  2234. self.ui.fcinfo.set_status(str(msg), level="info")
  2235. # make sure that if the message is to clear the infobar with a space
  2236. # is not printed over and over on the shell
  2237. if msg != '':
  2238. self.shell_message(msg)
  2239. def restore_toolbar_view(self):
  2240. tb = self.defaults["global_toolbar_view"]
  2241. if tb & 1:
  2242. self.ui.toolbarfile.setVisible(True)
  2243. else:
  2244. self.ui.toolbarfile.setVisible(False)
  2245. if tb & 2:
  2246. self.ui.toolbargeo.setVisible(True)
  2247. else:
  2248. self.ui.toolbargeo.setVisible(False)
  2249. if tb & 4:
  2250. self.ui.toolbarview.setVisible(True)
  2251. else:
  2252. self.ui.toolbarview.setVisible(False)
  2253. if tb & 8:
  2254. self.ui.toolbartools.setVisible(True)
  2255. else:
  2256. self.ui.toolbartools.setVisible(False)
  2257. if tb & 16:
  2258. self.ui.exc_edit_toolbar.setVisible(True)
  2259. else:
  2260. self.ui.exc_edit_toolbar.setVisible(False)
  2261. if tb & 32:
  2262. self.ui.geo_edit_toolbar.setVisible(True)
  2263. else:
  2264. self.ui.geo_edit_toolbar.setVisible(False)
  2265. if tb & 64:
  2266. self.ui.grb_edit_toolbar.setVisible(True)
  2267. else:
  2268. self.ui.grb_edit_toolbar.setVisible(False)
  2269. if tb & 128:
  2270. self.ui.snap_toolbar.setVisible(True)
  2271. else:
  2272. self.ui.snap_toolbar.setVisible(False)
  2273. if tb & 256:
  2274. self.ui.toolbarshell.setVisible(True)
  2275. else:
  2276. self.ui.toolbarshell.setVisible(False)
  2277. def load_defaults(self, filename):
  2278. """
  2279. Loads the aplication's default settings from current_defaults.FlatConfig into
  2280. ``self.defaults``.
  2281. :return: None
  2282. """
  2283. try:
  2284. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2285. options = f.read()
  2286. f.close()
  2287. except IOError:
  2288. self.log.error("Could not load defaults file.")
  2289. self.inform.emit(_("[ERROR] Could not load defaults file."))
  2290. # in case the defaults file can't be loaded, show all toolbars
  2291. self.defaults["global_toolbar_view"] = 511
  2292. return
  2293. try:
  2294. defaults = json.loads(options)
  2295. except:
  2296. # in case the defaults file can't be loaded, show all toolbars
  2297. self.defaults["global_toolbar_view"] = 511
  2298. e = sys.exc_info()[0]
  2299. App.log.error(str(e))
  2300. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  2301. return
  2302. self.defaults.update(defaults)
  2303. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2304. # restore the toolbar view
  2305. self.restore_toolbar_view()
  2306. def on_import_preferences(self):
  2307. """
  2308. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2309. ``self.defaults``.
  2310. :return: None
  2311. """
  2312. self.report_usage("on_import_preferences")
  2313. App.log.debug("on_import_preferences()")
  2314. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2315. try:
  2316. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2317. directory=self.data_path,
  2318. filter=filter_)
  2319. except TypeError:
  2320. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2321. filter=filter_)
  2322. filename = str(filename)
  2323. if filename == "":
  2324. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences import cancelled."))
  2325. else:
  2326. try:
  2327. f = open(filename)
  2328. options = f.read()
  2329. f.close()
  2330. except IOError:
  2331. self.log.error("Could not load defaults file.")
  2332. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2333. return
  2334. try:
  2335. defaults_from_file = json.loads(options)
  2336. except Exception as e:
  2337. e = sys.exc_info()[0]
  2338. App.log.error(str(e))
  2339. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2340. return
  2341. self.defaults.update(defaults_from_file)
  2342. self.inform.emit(_("[success] Imported Defaults from %s") %filename)
  2343. def on_export_preferences(self):
  2344. self.report_usage("on_export_preferences")
  2345. App.log.debug("on_export_preferences()")
  2346. defaults_file_content = None
  2347. self.date = str(datetime.today()).rpartition('.')[0]
  2348. self.date = ''.join(c for c in self.date if c not in ':-')
  2349. self.date = self.date.replace(' ', '_')
  2350. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  2351. try:
  2352. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2353. caption=_("Export FlatCAM Preferences"),
  2354. directory=self.data_path + '/preferences_' + self.date,
  2355. filter=filter
  2356. )
  2357. except TypeError:
  2358. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2359. filter=filter)
  2360. filename = str(filename)
  2361. defaults_from_file = {}
  2362. if filename == "":
  2363. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences export cancelled."))
  2364. return
  2365. else:
  2366. try:
  2367. f = open(filename, 'w')
  2368. defaults_file_content = f.read()
  2369. f.close()
  2370. except IOError:
  2371. App.log.debug('Creating a new preferences file ...')
  2372. f = open(filename, 'w')
  2373. json.dump({}, f)
  2374. f.close()
  2375. except:
  2376. e = sys.exc_info()[0]
  2377. App.log.error("Could not load defaults file.")
  2378. App.log.error(str(e))
  2379. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2380. return
  2381. try:
  2382. defaults_from_file = json.loads(defaults_file_content)
  2383. except:
  2384. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2385. # Update options
  2386. self.defaults_read_form()
  2387. defaults_from_file.update(self.defaults)
  2388. self.propagate_defaults(silent=True)
  2389. # Save update options
  2390. try:
  2391. f = open(filename, "w")
  2392. json.dump(defaults_from_file, f)
  2393. f.close()
  2394. except:
  2395. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2396. return
  2397. if self.defaults["global_open_style"] is False:
  2398. self.file_opened.emit("preferences", filename)
  2399. self.file_saved.emit("preferences", filename)
  2400. self.inform.emit("[success] Exported Defaults to %s" % filename)
  2401. def on_preferences_open_folder(self):
  2402. self.report_usage("on_preferences_open_folder()")
  2403. if sys.platform == 'win32':
  2404. subprocess.Popen('explorer %s' % self.data_path)
  2405. elif sys.platform == 'darwin':
  2406. os.system('open "%s"' % self.data_path)
  2407. else:
  2408. subprocess.Popen(['xdg-open', self.data_path])
  2409. self.inform.emit("[success] FlatCAM Preferences Folder opened.")
  2410. def save_geometry(self, x, y, width, height, notebook_width):
  2411. self.defaults["global_def_win_x"] = x
  2412. self.defaults["global_def_win_y"] = y
  2413. self.defaults["global_def_win_w"] = width
  2414. self.defaults["global_def_win_h"] = height
  2415. self.defaults["global_def_notebook_width"] = notebook_width
  2416. self.save_defaults()
  2417. def message_dialog(self, title, message, kind="info"):
  2418. icon = {"info": QtWidgets.QMessageBox.Information,
  2419. "warning": QtWidgets.QMessageBox.Warning,
  2420. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2421. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2422. dlg.setText(message)
  2423. dlg.exec_()
  2424. def register_recent(self, kind, filename):
  2425. self.log.debug("register_recent()")
  2426. self.log.debug(" %s" % kind)
  2427. self.log.debug(" %s" % filename)
  2428. record = {'kind': str(kind), 'filename': str(filename)}
  2429. if record in self.recent:
  2430. return
  2431. self.recent.insert(0, record)
  2432. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2433. self.recent.pop()
  2434. try:
  2435. f = open(self.data_path + '/recent.json', 'w')
  2436. except IOError:
  2437. App.log.error("Failed to open recent items file for writing.")
  2438. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent files file for writing.'))
  2439. return
  2440. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2441. f.close()
  2442. # Re-build the recent items menu
  2443. self.setup_recent_items()
  2444. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2445. """
  2446. Creates a new specialized FlatCAMObj and attaches it to the application,
  2447. this is, updates the GUI accordingly, any other records and plots it.
  2448. This method is thread-safe.
  2449. Notes:
  2450. * If the name is in use, the self.collection will modify it
  2451. when appending it to the collection. There is no need to handle
  2452. name conflicts here.
  2453. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2454. :type kind: str
  2455. :param name: Name for the object.
  2456. :type name: str
  2457. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2458. The function is called with 2 parameters: the new object and the App instance.
  2459. :type initialize: function
  2460. :return: None
  2461. :rtype: None
  2462. """
  2463. App.log.debug("new_object()")
  2464. obj_plot = plot
  2465. obj_autoselected = autoselected
  2466. t0 = time.time() # Debug
  2467. # ## Create object
  2468. classdict = {
  2469. "gerber": FlatCAMGerber,
  2470. "excellon": FlatCAMExcellon,
  2471. "cncjob": FlatCAMCNCjob,
  2472. "geometry": FlatCAMGeometry
  2473. }
  2474. App.log.debug("Calling object constructor...")
  2475. obj = classdict[kind](name)
  2476. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2477. # Set options from "Project options" form
  2478. self.options_read_form()
  2479. # IMPORTANT
  2480. # The key names in defaults and options dictionary's are not random:
  2481. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2482. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2483. # the options from project options form into the self.options. After that, below, depending on the type of
  2484. # object that is created, it will strip the name of the object and the underline (if the original key was
  2485. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2486. # "toolchange"
  2487. for option in self.options:
  2488. if option.find(kind + "_") == 0:
  2489. oname = option[len(kind) + 1:]
  2490. obj.options[oname] = self.options[option]
  2491. obj.isHovering = False
  2492. obj.notHovering = True
  2493. # Initialize as per user request
  2494. # User must take care to implement initialize
  2495. # in a thread-safe way as is is likely that we
  2496. # have been invoked in a separate thread.
  2497. t1 = time.time()
  2498. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2499. try:
  2500. return_value = initialize(obj, self)
  2501. except Exception as e:
  2502. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2503. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2504. msg += traceback.format_exc()
  2505. self.inform.emit(msg)
  2506. # if str(e) == "Empty Geometry":
  2507. # self.inform.emit("[ERROR_NOTCL] )
  2508. # else:
  2509. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2510. return "fail"
  2511. t2 = time.time()
  2512. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2513. if return_value == 'fail':
  2514. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2515. return "fail"
  2516. # Check units and convert if necessary
  2517. # This condition CAN be true because initialize() can change obj.units
  2518. if self.options["units"].upper() != obj.units.upper():
  2519. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2520. obj.convert_units(self.options["units"])
  2521. t3 = time.time()
  2522. self.log.debug("%f seconds converting units." % (t3 - t2))
  2523. # Create the bounding box for the object and then add the results to the obj.options
  2524. try:
  2525. xmin, ymin, xmax, ymax = obj.bounds()
  2526. obj.options['xmin'] = xmin
  2527. obj.options['ymin'] = ymin
  2528. obj.options['xmax'] = xmax
  2529. obj.options['ymax'] = ymax
  2530. except:
  2531. log.warning("The object has no bounds properties.")
  2532. # don't plot objects with no bounds, there is nothing to plot
  2533. self.plot = False
  2534. pass
  2535. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2536. # Move the object to the main thread and let the app know that it is available.
  2537. obj.moveToThread(self.main_thread)
  2538. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2539. return obj
  2540. def new_excellon_object(self):
  2541. self.report_usage("new_excellon_object()")
  2542. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2543. def new_geometry_object(self):
  2544. self.report_usage("new_geometry_object()")
  2545. def initialize(obj, self):
  2546. obj.multitool = False
  2547. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2548. def new_gerber_object(self):
  2549. self.report_usage("new_gerber_object()")
  2550. def initialize(grb_obj, self):
  2551. grb_obj.multitool = False
  2552. grb_obj.source_file = []
  2553. grb_obj.multigeo = False
  2554. grb_obj.follow = False
  2555. grb_obj.apertures = {}
  2556. grb_obj.solid_geometry = []
  2557. try:
  2558. grb_obj.options['xmin'] = 0
  2559. grb_obj.options['ymin'] = 0
  2560. grb_obj.options['xmax'] = 0
  2561. grb_obj.options['ymax'] = 0
  2562. except KeyError:
  2563. pass
  2564. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2565. def on_object_created(self, obj, plot, autoselect):
  2566. """
  2567. Event callback for object creation.
  2568. :param obj: The newly created FlatCAM object.
  2569. :return: None
  2570. """
  2571. t0 = time.time() # DEBUG
  2572. self.log.debug("on_object_created()")
  2573. # The Collection might change the name if there is a collision
  2574. self.collection.append(obj)
  2575. # after adding the object to the collection always update the list of objects that are in the collection
  2576. self.all_objects_list = self.collection.get_list()
  2577. # self.inform.emit('[selected] %s created & selected: %s' %
  2578. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2579. if obj.kind == 'gerber':
  2580. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2581. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  2582. elif obj.kind == 'excellon':
  2583. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2584. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  2585. elif obj.kind == 'cncjob':
  2586. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2587. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  2588. elif obj.kind == 'geometry':
  2589. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2590. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  2591. # update the SHELL auto-completer model with the name of the new object
  2592. self.myKeywords.append(obj.options['name'])
  2593. self.shell._edit.set_model_data(self.myKeywords)
  2594. self.ui.code_editor.set_model_data(self.myKeywords)
  2595. if autoselect:
  2596. # select the just opened object but deselect the previous ones
  2597. self.collection.set_all_inactive()
  2598. self.collection.set_active(obj.options["name"])
  2599. # here it is done the object plotting
  2600. def worker_task(t_obj):
  2601. with self.proc_container.new("Plotting"):
  2602. if isinstance(t_obj, FlatCAMCNCjob):
  2603. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2604. else:
  2605. t_obj.plot()
  2606. t1 = time.time() # DEBUG
  2607. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2608. self.object_plotted.emit(t_obj)
  2609. # Send to worker
  2610. # self.worker.add_task(worker_task, [self])
  2611. if plot is True:
  2612. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2613. def on_object_changed(self, obj):
  2614. # update the bounding box data from obj.options
  2615. xmin, ymin, xmax, ymax = obj.bounds()
  2616. obj.options['xmin'] = xmin
  2617. obj.options['ymin'] = ymin
  2618. obj.options['xmax'] = xmax
  2619. obj.options['ymax'] = ymax
  2620. log.debug("Object changed, updating the bounding box data on self.options")
  2621. # delete the old selection shape
  2622. self.delete_selection_shape()
  2623. self.should_we_save = True
  2624. def on_object_plotted(self, obj):
  2625. self.on_zoom_fit(None)
  2626. def options_read_form(self):
  2627. for option in self.options_form_fields:
  2628. self.options[option] = self.options_form_fields[option].get_value()
  2629. def options_write_form(self):
  2630. for option in self.options:
  2631. self.options_write_form_field(option)
  2632. def options_write_form_field(self, field):
  2633. try:
  2634. self.options_form_fields[field].set_value(self.options[field])
  2635. except KeyError:
  2636. # Changed from error to debug. This allows to have data stored
  2637. # which is not user-editable.
  2638. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2639. pass
  2640. def on_about(self):
  2641. """
  2642. Displays the "about" dialog.
  2643. :return: None
  2644. """
  2645. self.report_usage("on_about")
  2646. version = self.version
  2647. version_date = self.version_date
  2648. beta = self.beta
  2649. class AboutDialog(QtWidgets.QDialog):
  2650. def __init__(self, parent=None):
  2651. QtWidgets.QDialog.__init__(self, parent)
  2652. # Icon and title
  2653. self.setWindowIcon(parent.app_icon)
  2654. self.setWindowTitle("FlatCAM")
  2655. layout1 = QtWidgets.QVBoxLayout()
  2656. self.setLayout(layout1)
  2657. layout2 = QtWidgets.QHBoxLayout()
  2658. layout1.addLayout(layout2)
  2659. logo = QtWidgets.QLabel()
  2660. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2661. layout2.addWidget(logo, stretch=0)
  2662. title = QtWidgets.QLabel(
  2663. _(
  2664. "<font size=8><B>FlatCAM</B></font><BR>"
  2665. "Version {version} {beta} ({date}) - {arch} <BR>"
  2666. "<BR>"
  2667. "2D Computer-Aided Printed Circuit Board<BR>"
  2668. "Manufacturing.<BR>"
  2669. "<BR>"
  2670. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2671. "<BR>"
  2672. "<B> Main Contributors:</B><BR>"
  2673. "Denis Hayrullin<BR>"
  2674. "Kamil Sopko<BR>"
  2675. "Marius Stanciu<BR>"
  2676. "Matthieu Berthomé<BR>"
  2677. "and many others found "
  2678. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2679. "<BR>"
  2680. "Development is done "
  2681. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2682. "DOWNLOAD area "
  2683. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2684. ""
  2685. ).format(version=version,
  2686. beta=('BETA' if beta else ''),
  2687. date=version_date,
  2688. arch=platform.architecture()[0])
  2689. )
  2690. title.setOpenExternalLinks(True)
  2691. layout2.addWidget(title, stretch=1)
  2692. layout3 = QtWidgets.QHBoxLayout()
  2693. layout1.addLayout(layout3)
  2694. layout3.addStretch()
  2695. okbtn = QtWidgets.QPushButton("Close")
  2696. layout3.addWidget(okbtn)
  2697. okbtn.clicked.connect(self.accept)
  2698. AboutDialog(self.ui).exec_()
  2699. def on_file_savedefaults(self):
  2700. """
  2701. Callback for menu item File->Save Defaults. Saves application default options
  2702. ``self.defaults`` to current_defaults.FlatConfig.
  2703. :return: None
  2704. """
  2705. self.save_defaults()
  2706. # def on_app_exit(self):
  2707. # self.report_usage("on_app_exit()")
  2708. #
  2709. # if self.collection.get_list():
  2710. # msgbox = QtWidgets.QMessageBox()
  2711. # # msgbox.setText("<B>Save changes ...</B>")
  2712. # msgbox.setText("There are files/objects opened in FlatCAM. "
  2713. # "\n"
  2714. # "Do you want to Save the project?")
  2715. # msgbox.setWindowTitle("Save changes")
  2716. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2717. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2718. # QtWidgets.QMessageBox.Cancel)
  2719. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2720. #
  2721. # response = msgbox.exec_()
  2722. #
  2723. # if response == QtWidgets.QMessageBox.Yes:
  2724. # self.on_file_saveprojectas(thread=False)
  2725. # elif response == QtWidgets.QMessageBox.Cancel:
  2726. # return
  2727. # self.save_defaults()
  2728. # else:
  2729. # self.save_defaults()
  2730. # log.debug("Application defaults saved ... Exit event.")
  2731. # QtWidgets.qApp.quit()
  2732. def save_defaults(self, silent=False):
  2733. """
  2734. Saves application default options
  2735. ``self.defaults`` to current_defaults.FlatConfig.
  2736. :return: None
  2737. """
  2738. self.report_usage("save_defaults")
  2739. # Read options from file
  2740. try:
  2741. f = open(self.data_path + "/current_defaults.FlatConfig")
  2742. defaults_file_content = f.read()
  2743. f.close()
  2744. except:
  2745. e = sys.exc_info()[0]
  2746. App.log.error("Could not load defaults file.")
  2747. App.log.error(str(e))
  2748. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2749. return
  2750. try:
  2751. defaults = json.loads(defaults_file_content)
  2752. except:
  2753. e = sys.exc_info()[0]
  2754. App.log.error("Failed to parse defaults file.")
  2755. App.log.error(str(e))
  2756. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2757. return
  2758. # Update options
  2759. self.defaults_read_form()
  2760. defaults.update(self.defaults)
  2761. self.propagate_defaults(silent=True)
  2762. # Save the toolbar view
  2763. tb_status = 0
  2764. if self.ui.toolbarfile.isVisible():
  2765. tb_status += 1
  2766. if self.ui.toolbargeo.isVisible():
  2767. tb_status += 2
  2768. if self.ui.toolbarview.isVisible():
  2769. tb_status += 4
  2770. if self.ui.toolbartools.isVisible():
  2771. tb_status += 8
  2772. if self.ui.exc_edit_toolbar.isVisible():
  2773. tb_status += 16
  2774. if self.ui.geo_edit_toolbar.isVisible():
  2775. tb_status += 32
  2776. if self.ui.grb_edit_toolbar.isVisible():
  2777. tb_status += 64
  2778. if self.ui.snap_toolbar.isVisible():
  2779. tb_status += 128
  2780. if self.ui.toolbarshell.isVisible():
  2781. tb_status += 256
  2782. self.defaults["global_toolbar_view"] = tb_status
  2783. # Save update options
  2784. try:
  2785. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2786. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  2787. f.close()
  2788. except:
  2789. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2790. return
  2791. if not silent:
  2792. self.inform.emit(_("[success] Defaults saved."))
  2793. def save_factory_defaults(self, silent=False):
  2794. """
  2795. Saves application factory default options
  2796. ``self.defaults`` to factory_defaults.FlatConfig.
  2797. It's a one time job done just after the first install.
  2798. :return: None
  2799. """
  2800. self.report_usage("save_factory_defaults")
  2801. # Read options from file
  2802. try:
  2803. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2804. factory_defaults_file_content = f_f_def.read()
  2805. f_f_def.close()
  2806. except:
  2807. e = sys.exc_info()[0]
  2808. App.log.error("Could not load factory defaults file.")
  2809. App.log.error(str(e))
  2810. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  2811. return
  2812. try:
  2813. factory_defaults = json.loads(factory_defaults_file_content)
  2814. except:
  2815. e = sys.exc_info()[0]
  2816. App.log.error("Failed to parse factory defaults file.")
  2817. App.log.error(str(e))
  2818. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  2819. return
  2820. # Update options
  2821. self.defaults_read_form()
  2822. factory_defaults.update(self.defaults)
  2823. self.propagate_defaults(silent=True)
  2824. # Save update options
  2825. try:
  2826. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2827. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  2828. f_f_def_s.close()
  2829. except:
  2830. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  2831. return
  2832. if silent is False:
  2833. self.inform.emit(_("Factory defaults saved."))
  2834. def final_save(self):
  2835. if self.save_in_progress:
  2836. self.inform.emit(_("[WARNING_NOTCL] Application is saving the project. Please wait ..."))
  2837. return
  2838. if self.should_we_save and self.collection.get_list():
  2839. msgbox = QtWidgets.QMessageBox()
  2840. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2841. "\n"
  2842. "Do you want to Save the project?"))
  2843. msgbox.setWindowTitle(_("Save changes"))
  2844. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2845. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2846. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2847. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2848. msgbox.setDefaultButton(bt_yes)
  2849. msgbox.exec_()
  2850. response = msgbox.clickedButton()
  2851. if response == bt_yes:
  2852. self.on_file_saveprojectas(thread=True, quit=True)
  2853. elif response == bt_no:
  2854. self.quit_application()
  2855. elif response == bt_cancel:
  2856. return
  2857. else:
  2858. self.quit_application()
  2859. def quit_application(self):
  2860. self.save_defaults()
  2861. log.debug("App.final_save() --> App Defaults saved.")
  2862. # save toolbar state to file
  2863. settings = QSettings("Open Source", "FlatCAM")
  2864. settings.setValue('saved_gui_state', self.ui.saveState())
  2865. settings.setValue('maximized_gui', self.ui.isMaximized())
  2866. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  2867. # This will write the setting to the platform specific storage.
  2868. del settings
  2869. log.debug("App.final_save() --> App UI state saved.")
  2870. QtWidgets.qApp.quit()
  2871. def on_toggle_shell(self):
  2872. """
  2873. toggle shell if is visible close it if closed open it
  2874. :return:
  2875. """
  2876. self.report_usage("on_toggle_shell()")
  2877. if self.ui.shell_dock.isVisible():
  2878. self.ui.shell_dock.hide()
  2879. else:
  2880. self.ui.shell_dock.show()
  2881. def on_edit_join(self, name=None):
  2882. """
  2883. Callback for Edit->Join. Joins the selected geometry objects into
  2884. a new one.
  2885. :return: None
  2886. """
  2887. self.report_usage("on_edit_join()")
  2888. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2889. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2890. tooldias = []
  2891. geo_type_list = []
  2892. objs = self.collection.get_selected()
  2893. for obj in objs:
  2894. geo_type_list.append(obj.multigeo)
  2895. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2896. if len(set(geo_type_list)) != 1:
  2897. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2898. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2899. "convert from one to another and retry joining \n"
  2900. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2901. "the result may not be what was expected. \n"
  2902. "Check the generated GCODE."))
  2903. return
  2904. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2905. if True in geo_type_list:
  2906. def initialize(obj, app):
  2907. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2908. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2909. for v in obj.tools.values():
  2910. v['data']['name'] = obj_name_multi
  2911. self.new_object("geometry", obj_name_multi, initialize)
  2912. else:
  2913. def initialize(obj, app):
  2914. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2915. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2916. for v in obj.tools.values():
  2917. v['data']['name'] = obj_name_single
  2918. self.new_object("geometry", obj_name_single, initialize)
  2919. self.should_we_save = True
  2920. def on_edit_join_exc(self):
  2921. """
  2922. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2923. a new one.
  2924. :return: None
  2925. """
  2926. self.report_usage("on_edit_join_exc()")
  2927. objs = self.collection.get_selected()
  2928. for obj in objs:
  2929. if not isinstance(obj, FlatCAMExcellon):
  2930. self.inform.emit(_("[ERROR_NOTCL] Failed. Excellon joining works only on Excellon objects."))
  2931. return
  2932. def initialize(obj, app):
  2933. FlatCAMExcellon.merge(objs, obj)
  2934. self.new_object("excellon", 'Combo_Excellon', initialize)
  2935. self.should_we_save = True
  2936. def on_edit_join_grb(self):
  2937. """
  2938. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2939. a new one.
  2940. :return: None
  2941. """
  2942. self.report_usage("on_edit_join_grb()")
  2943. objs = self.collection.get_selected()
  2944. for obj in objs:
  2945. if not isinstance(obj, FlatCAMGerber):
  2946. self.inform.emit(_("[ERROR_NOTCL] Failed. Gerber joining works only on Gerber objects."))
  2947. return
  2948. def initialize(obj, app):
  2949. FlatCAMGerber.merge(objs, obj)
  2950. self.new_object("gerber", 'Combo_Gerber', initialize)
  2951. self.should_we_save = True
  2952. def on_convert_singlegeo_to_multigeo(self):
  2953. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2954. obj = self.collection.get_active()
  2955. if obj is None:
  2956. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2957. return
  2958. if not isinstance(obj, FlatCAMGeometry):
  2959. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2960. return
  2961. obj.multigeo = True
  2962. for tooluid, dict_value in obj.tools.items():
  2963. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2964. if not isinstance(obj.solid_geometry, list):
  2965. obj.solid_geometry = [obj.solid_geometry]
  2966. obj.solid_geometry[:] = []
  2967. obj.plot()
  2968. self.should_we_save = True
  2969. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  2970. def on_convert_multigeo_to_singlegeo(self):
  2971. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2972. obj = self.collection.get_active()
  2973. if obj is None:
  2974. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2975. return
  2976. if not isinstance(obj, FlatCAMGeometry):
  2977. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2978. return
  2979. obj.multigeo = False
  2980. total_solid_geometry = []
  2981. for tooluid, dict_value in obj.tools.items():
  2982. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2983. # clear the original geometry
  2984. dict_value['solid_geometry'][:] = []
  2985. obj.solid_geometry = deepcopy(total_solid_geometry)
  2986. obj.plot()
  2987. self.should_we_save = True
  2988. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  2989. def on_options_dict_change(self, field):
  2990. self.options_write_form_field(field)
  2991. if field == "units":
  2992. self.set_screen_units(self.options['units'])
  2993. def on_defaults_dict_change(self, field):
  2994. self.defaults_write_form_field(field)
  2995. if field == "units":
  2996. self.set_screen_units(self.defaults['units'])
  2997. def set_screen_units(self, units):
  2998. self.ui.units_label.setText("[" + units.lower() + "]")
  2999. def on_toggle_units(self, no_pref=False):
  3000. """
  3001. Callback for the Units radio-button change in the Options tab.
  3002. Changes the application's default units or the current project's units.
  3003. If changing the project's units, the change propagates to all of
  3004. the objects in the project.
  3005. :return: None
  3006. """
  3007. self.report_usage("on_toggle_units")
  3008. if self.toggle_units_ignore:
  3009. return
  3010. # If option is the same, then ignore
  3011. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == \
  3012. self.defaults["units"].upper():
  3013. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3014. return
  3015. # Options to scale
  3016. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3017. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  3018. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3019. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  3020. "excellon_z_pdepth",
  3021. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3022. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3023. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  3024. "geometry_feedrate_probe",
  3025. 'cncjob_tooldia',
  3026. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3027. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin",
  3028. "tools_2sided_drilldia", "tools_film_boundary",
  3029. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3030. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3031. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3032. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3033. "tools_transform_offset_y",
  3034. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3035. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3036. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3037. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3038. 'global_gridx', 'global_gridy', 'global_snap_max']
  3039. def scale_options(sfactor):
  3040. for dim in dimensions:
  3041. if dim == 'excellon_toolchangexy':
  3042. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  3043. coords_xy[0] *= sfactor
  3044. coords_xy[1] *= sfactor
  3045. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3046. elif dim == 'geometry_toolchangexy':
  3047. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  3048. coords_xy[0] *= sfactor
  3049. coords_xy[1] *= sfactor
  3050. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3051. elif dim == 'tools_ncctools':
  3052. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  3053. ncctols[0] *= sfactor
  3054. ncctols[1] *= sfactor
  3055. self.options['tools_ncctools'] = "%f, %f" % (ncctols[0], ncctols[1])
  3056. elif dim == 'tools_solderpaste_tools':
  3057. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  3058. sp_tools[0] *= sfactor
  3059. sp_tools[1] *= sfactor
  3060. self.options['tools_solderpaste_tools'] = "%f, %f" % (sp_tools[0], sp_tools[1])
  3061. elif dim == 'tools_solderpaste_xy_toolchange':
  3062. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  3063. sp_coords[0] *= sfactor
  3064. sp_coords[1] *= sfactor
  3065. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  3066. else:
  3067. try:
  3068. self.options[dim] = float(self.options[dim]) * sfactor
  3069. except Exception as e:
  3070. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  3071. def scale_defaults(sfactor):
  3072. for dim in dimensions:
  3073. if dim == 'excellon_toolchangexy':
  3074. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  3075. coords_xy[0] *= sfactor
  3076. coords_xy[1] *= sfactor
  3077. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3078. elif dim == 'geometry_toolchangexy':
  3079. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  3080. coords_xy[0] *= sfactor
  3081. coords_xy[1] *= sfactor
  3082. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3083. elif dim == 'tools_ncctools':
  3084. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  3085. ncctols[0] *= sfactor
  3086. ncctols[1] *= sfactor
  3087. self.defaults['tools_ncctools'] = "%.4f, %.4f" % (ncctols[0], ncctols[1])
  3088. elif dim == 'tools_solderpaste_tools':
  3089. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  3090. sp_tools[0] *= sfactor
  3091. sp_tools[1] *= sfactor
  3092. self.defaults['tools_solderpaste_tools'] = "%.4f, %.4f" % (sp_tools[0], sp_tools[1])
  3093. elif dim == 'tools_solderpaste_xy_toolchange':
  3094. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  3095. sp_coords[0] *= sfactor
  3096. sp_coords[1] *= sfactor
  3097. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  3098. else:
  3099. try:
  3100. self.defaults[dim] = float(self.defaults[dim]) * sfactor
  3101. except Exception as e:
  3102. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3103. # The scaling factor depending on choice of units.
  3104. factor = 1/25.4
  3105. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3106. factor = 25.4
  3107. # Changing project units. Warn user.
  3108. msgbox = QtWidgets.QMessageBox()
  3109. msgbox.setWindowTitle("Toggle Units")
  3110. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  3111. msgbox.setText("<B>Change project units ...</B>")
  3112. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  3113. "properties of all objects to be scaled accordingly.\nContinue?")
  3114. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3115. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3116. msgbox.setDefaultButton(bt_ok)
  3117. msgbox.exec_()
  3118. response = msgbox.clickedButton()
  3119. if response == bt_ok:
  3120. if no_pref is False:
  3121. self.options_read_form()
  3122. scale_options(factor)
  3123. self.options_write_form()
  3124. self.defaults_read_form()
  3125. scale_defaults(factor)
  3126. self.defaults_write_form()
  3127. self.should_we_save = True
  3128. # change this only if the workspace is active
  3129. if self.defaults['global_workspace'] is True:
  3130. self.plotcanvas.draw_workspace()
  3131. # adjust the grid values on the main toolbar
  3132. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  3133. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  3134. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3135. for obj in self.collection.get_list():
  3136. obj.convert_units(units)
  3137. # make that the properties stored in the object are also updated
  3138. self.object_changed.emit(obj)
  3139. obj.build_ui()
  3140. current = self.collection.get_active()
  3141. if current is not None:
  3142. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3143. if not isinstance(current, FlatCAMGeometry):
  3144. current.to_form()
  3145. self.plot_all()
  3146. self.inform.emit(_("[success] Converted units to %s") % units)
  3147. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  3148. self.set_screen_units(units)
  3149. else:
  3150. # Undo toggling
  3151. self.toggle_units_ignore = True
  3152. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3153. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3154. else:
  3155. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3156. self.toggle_units_ignore = False
  3157. self.inform.emit(_("[WARNING_NOTCL] Units conversion cancelled."))
  3158. self.options_read_form()
  3159. self.defaults_read_form()
  3160. def on_toggle_units_click(self):
  3161. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3162. if self.defaults["units"] == 'MM':
  3163. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3164. else:
  3165. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3166. self.on_toggle_units(no_pref=True)
  3167. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3168. lambda: self.on_toggle_units(no_pref=False))
  3169. def on_fullscreen(self):
  3170. self.report_usage("on_fullscreen()")
  3171. if self.toggle_fscreen is False:
  3172. if sys.platform == 'win32':
  3173. self.ui.showFullScreen()
  3174. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3175. tb.setVisible(False)
  3176. self.ui.splitter_left.setVisible(False)
  3177. self.toggle_fscreen = True
  3178. else:
  3179. if sys.platform == 'win32':
  3180. self.ui.showNormal()
  3181. self.restore_toolbar_view()
  3182. self.ui.splitter_left.setVisible(True)
  3183. self.toggle_fscreen = False
  3184. def on_toggle_plotarea(self):
  3185. self.report_usage("on_toggle_plotarea()")
  3186. try:
  3187. name = self.ui.plot_tab_area.widget(0).objectName()
  3188. except AttributeError:
  3189. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3190. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3191. self.ui.plot_tab_area.protectTab(0)
  3192. return
  3193. if name != 'plotarea':
  3194. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3195. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3196. self.ui.plot_tab_area.protectTab(0)
  3197. else:
  3198. self.ui.plot_tab_area.closeTab(0)
  3199. def on_toggle_notebook(self):
  3200. if self.ui.splitter.sizes()[0] == 0:
  3201. self.ui.splitter.setSizes([1, 1])
  3202. else:
  3203. self.ui.splitter.setSizes([0, 1])
  3204. def on_toggle_axis(self):
  3205. self.report_usage("on_toggle_axis()")
  3206. if self.toggle_axis is False:
  3207. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3208. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3209. self.plotcanvas.redraw()
  3210. self.toggle_axis = True
  3211. else:
  3212. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3213. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3214. self.plotcanvas.redraw()
  3215. self.toggle_axis = False
  3216. def on_toggle_grid(self):
  3217. self.report_usage("on_toggle_grid()")
  3218. self.ui.grid_snap_btn.trigger()
  3219. def on_options_combo_change(self, sel):
  3220. """
  3221. Called when the combo box to choose between application defaults and
  3222. project option changes value. The corresponding variables are
  3223. copied to the UI.
  3224. :param sel: The option index that was chosen.
  3225. :return: None
  3226. """
  3227. # combo_sel = self.ui.notebook.combo_options.get_active()
  3228. App.log.debug("Options --> %s" % sel)
  3229. # form = [self.defaults_form, self.options_form][sel]
  3230. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  3231. if sel == 0:
  3232. self.gen_form = self.ui.general_defaults_form
  3233. self.ger_form = self.ui.gerber_defaults_form
  3234. self.exc_form = self.ui.excellon_defaults_form
  3235. self.geo_form = self.ui.geometry_defaults_form
  3236. self.cnc_form = self.ui.cncjob_defaults_form
  3237. self.tools_form = self.ui.tools_defaults_form
  3238. elif sel == 1:
  3239. self.gen_form = self.ui.general_options_form
  3240. self.ger_form = self.ui.gerber_options_form
  3241. self.exc_form = self.ui.excellon_options_form
  3242. self.geo_form = self.ui.geometry_options_form
  3243. self.cnc_form = self.ui.cncjob_options_form
  3244. self.tools_form = self.ui.tools_options_form
  3245. else:
  3246. return
  3247. try:
  3248. self.ui.general_scroll_area.takeWidget()
  3249. except:
  3250. self.log.debug("Nothing to remove")
  3251. self.ui.general_scroll_area.setWidget(self.gen_form)
  3252. self.gen_form.show()
  3253. try:
  3254. self.ui.gerber_scroll_area.takeWidget()
  3255. except:
  3256. self.log.debug("Nothing to remove")
  3257. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  3258. self.ger_form.show()
  3259. try:
  3260. self.ui.excellon_scroll_area.takeWidget()
  3261. except:
  3262. self.log.debug("Nothing to remove")
  3263. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  3264. self.exc_form.show()
  3265. try:
  3266. self.ui.geometry_scroll_area.takeWidget()
  3267. except:
  3268. self.log.debug("Nothing to remove")
  3269. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  3270. self.geo_form.show()
  3271. try:
  3272. self.ui.cncjob_scroll_area.takeWidget()
  3273. except:
  3274. self.log.debug("Nothing to remove")
  3275. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  3276. self.cnc_form.show()
  3277. try:
  3278. self.ui.tools_scroll_area.takeWidget()
  3279. except:
  3280. self.log.debug("Nothing to remove")
  3281. self.ui.tools_scroll_area.setWidget(self.tools_form)
  3282. self.tools_form.show()
  3283. self.log.debug("Finished GUI form initialization.")
  3284. # self.options2form()
  3285. def on_excellon_defaults_button(self):
  3286. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  3287. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  3288. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  3289. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  3290. self.defaults_form_fields["excellon_zeros"].set_value('L')
  3291. self.defaults_form_fields["excellon_units"].set_value('INCH')
  3292. log.debug("Excellon app defaults loaded ...")
  3293. def on_excellon_options_button(self):
  3294. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  3295. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  3296. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  3297. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  3298. self.options_form_fields["excellon_zeros"].set_value('L')
  3299. self.options_form_fields["excellon_units"].set_value('INCH')
  3300. log.debug("Excellon options defaults loaded ...")
  3301. # Setting plot colors handlers
  3302. def on_pf_color_entry(self):
  3303. self.defaults['global_plot_fill'] = self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  3304. self.defaults['global_plot_fill'][7:9]
  3305. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3306. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  3307. def on_pf_color_button(self):
  3308. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  3309. c_dialog = QtWidgets.QColorDialog()
  3310. plot_fill_color = c_dialog.getColor(initial=current_color)
  3311. if plot_fill_color.isValid() is False:
  3312. return
  3313. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3314. "background-color:%s" % str(plot_fill_color.name()))
  3315. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  3316. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  3317. self.defaults['global_plot_fill'] = new_val
  3318. def on_pf_color_spinner(self):
  3319. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  3320. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  3321. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  3322. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3323. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  3324. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3325. def on_pf_color_slider(self):
  3326. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  3327. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  3328. def on_pl_color_entry(self):
  3329. self.defaults['global_plot_line'] = self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  3330. self.defaults['global_plot_line'][7:9]
  3331. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3332. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  3333. def on_pl_color_button(self):
  3334. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  3335. # print(current_color)
  3336. c_dialog = QtWidgets.QColorDialog()
  3337. plot_line_color = c_dialog.getColor(initial=current_color)
  3338. if plot_line_color.isValid() is False:
  3339. return
  3340. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3341. "background-color:%s" % str(plot_line_color.name()))
  3342. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  3343. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  3344. self.defaults['global_plot_line'] = new_val_line
  3345. # Setting selection colors (left - right) handlers
  3346. def on_sf_color_entry(self):
  3347. self.defaults['global_sel_fill'] = self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  3348. self.defaults['global_sel_fill'][7:9]
  3349. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3350. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  3351. def on_sf_color_button(self):
  3352. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  3353. c_dialog = QtWidgets.QColorDialog()
  3354. plot_fill_color = c_dialog.getColor(initial=current_color)
  3355. if plot_fill_color.isValid() is False:
  3356. return
  3357. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3358. "background-color:%s" % str(plot_fill_color.name()))
  3359. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  3360. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  3361. self.defaults['global_sel_fill'] = new_val
  3362. def on_sf_color_spinner(self):
  3363. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  3364. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  3365. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  3366. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3367. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  3368. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3369. def on_sf_color_slider(self):
  3370. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  3371. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  3372. def on_sl_color_entry(self):
  3373. self.defaults['global_sel_line'] = self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  3374. self.defaults['global_sel_line'][7:9]
  3375. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3376. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  3377. def on_sl_color_button(self):
  3378. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  3379. c_dialog = QtWidgets.QColorDialog()
  3380. plot_line_color = c_dialog.getColor(initial=current_color)
  3381. if plot_line_color.isValid() is False:
  3382. return
  3383. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3384. "background-color:%s" % str(plot_line_color.name()))
  3385. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  3386. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  3387. self.defaults['global_sel_line'] = new_val_line
  3388. # Setting selection colors (right - left) handlers
  3389. def on_alt_sf_color_entry(self):
  3390. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  3391. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  3392. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3393. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  3394. def on_alt_sf_color_button(self):
  3395. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  3396. c_dialog = QtWidgets.QColorDialog()
  3397. plot_fill_color = c_dialog.getColor(initial=current_color)
  3398. if plot_fill_color.isValid() is False:
  3399. return
  3400. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3401. "background-color:%s" % str(plot_fill_color.name()))
  3402. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  3403. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  3404. self.defaults['global_alt_sel_fill'] = new_val
  3405. def on_alt_sf_color_spinner(self):
  3406. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  3407. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  3408. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  3409. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3410. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  3411. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3412. def on_alt_sf_color_slider(self):
  3413. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  3414. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  3415. def on_alt_sl_color_entry(self):
  3416. self.defaults['global_alt_sel_line'] = \
  3417. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  3418. self.defaults['global_alt_sel_line'][7:9]
  3419. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3420. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  3421. def on_alt_sl_color_button(self):
  3422. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  3423. c_dialog = QtWidgets.QColorDialog()
  3424. plot_line_color = c_dialog.getColor(initial=current_color)
  3425. if plot_line_color.isValid() is False:
  3426. return
  3427. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3428. "background-color:%s" % str(plot_line_color.name()))
  3429. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  3430. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  3431. self.defaults['global_alt_sel_line'] = new_val_line
  3432. # Setting Editor colors
  3433. def on_draw_color_entry(self):
  3434. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3435. .draw_color_entry.get_value()
  3436. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3437. "background-color:%s" % str(self.defaults['global_draw_color']))
  3438. def on_draw_color_button(self):
  3439. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  3440. c_dialog = QtWidgets.QColorDialog()
  3441. draw_color = c_dialog.getColor(initial=current_color)
  3442. if draw_color.isValid() is False:
  3443. return
  3444. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3445. "background-color:%s" % str(draw_color.name()))
  3446. new_val = str(draw_color.name())
  3447. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  3448. self.defaults['global_draw_color'] = new_val
  3449. def on_sel_draw_color_entry(self):
  3450. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3451. .sel_draw_color_entry.get_value()
  3452. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3453. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  3454. def on_sel_draw_color_button(self):
  3455. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  3456. c_dialog = QtWidgets.QColorDialog()
  3457. sel_draw_color = c_dialog.getColor(initial=current_color)
  3458. if sel_draw_color.isValid() is False:
  3459. return
  3460. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3461. "background-color:%s" % str(sel_draw_color.name()))
  3462. new_val_sel = str(sel_draw_color.name())
  3463. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  3464. self.defaults['global_sel_draw_color'] = new_val_sel
  3465. def on_proj_color_entry(self):
  3466. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  3467. .proj_color_entry.get_value()
  3468. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3469. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  3470. def on_proj_color_button(self):
  3471. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  3472. c_dialog = QtWidgets.QColorDialog()
  3473. proj_color = c_dialog.getColor(initial=current_color)
  3474. if proj_color.isValid() is False:
  3475. return
  3476. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3477. "background-color:%s" % str(proj_color.name()))
  3478. new_val_sel = str(proj_color.name())
  3479. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  3480. self.defaults['global_proj_item_color'] = new_val_sel
  3481. def on_proj_color_dis_entry(self):
  3482. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  3483. .proj_color_dis_entry.get_value()
  3484. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3485. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  3486. def on_proj_color_dis_button(self):
  3487. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  3488. c_dialog = QtWidgets.QColorDialog()
  3489. proj_color = c_dialog.getColor(initial=current_color)
  3490. if proj_color.isValid() is False:
  3491. return
  3492. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3493. "background-color:%s" % str(proj_color.name()))
  3494. new_val_sel = str(proj_color.name())
  3495. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  3496. self.defaults['global_proj_item_dis_color'] = new_val_sel
  3497. def on_annotation_fontcolor_entry(self):
  3498. self.defaults['cncjob_annotation_fontcolor'] = \
  3499. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.get_value()
  3500. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  3501. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  3502. def on_annotation_fontcolor_button(self):
  3503. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  3504. c_dialog = QtWidgets.QColorDialog()
  3505. annotation_color = c_dialog.getColor(initial=current_color)
  3506. if annotation_color.isValid() is False:
  3507. return
  3508. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  3509. "background-color:%s" % str(annotation_color.name()))
  3510. new_val_sel = str(annotation_color.name())
  3511. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(new_val_sel)
  3512. self.defaults['global_proj_item_dis_color'] = new_val_sel
  3513. def on_deselect_all(self):
  3514. self.collection.set_all_inactive()
  3515. self.delete_selection_shape()
  3516. def on_workspace_modified(self):
  3517. self.save_defaults(silent=True)
  3518. self.plotcanvas.draw_workspace()
  3519. def on_workspace(self):
  3520. self.report_usage("on_workspace()")
  3521. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3522. self.plotcanvas.restore_workspace()
  3523. else:
  3524. self.plotcanvas.delete_workspace()
  3525. self.save_defaults(silent=True)
  3526. def on_workspace_menu(self):
  3527. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3528. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  3529. else:
  3530. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  3531. self.on_workspace()
  3532. def on_layout(self, index=None, lay=None):
  3533. self.report_usage("on_layout()")
  3534. if lay:
  3535. current_layout = lay
  3536. else:
  3537. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  3538. settings = QSettings("Open Source", "FlatCAM")
  3539. settings.setValue('layout', current_layout)
  3540. # This will write the setting to the platform specific storage.
  3541. del settings
  3542. # first remove the toolbars:
  3543. try:
  3544. self.ui.removeToolBar(self.ui.toolbarfile)
  3545. self.ui.removeToolBar(self.ui.toolbargeo)
  3546. self.ui.removeToolBar(self.ui.toolbarview)
  3547. self.ui.removeToolBar(self.ui.toolbarshell)
  3548. self.ui.removeToolBar(self.ui.toolbartools)
  3549. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  3550. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  3551. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  3552. self.ui.removeToolBar(self.ui.snap_toolbar)
  3553. self.ui.removeToolBar(self.ui.toolbarshell)
  3554. except:
  3555. pass
  3556. if current_layout == 'standard':
  3557. # ## TOOLBAR INSTALLATION # ##
  3558. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3559. self.ui.toolbarfile.setObjectName('File_TB')
  3560. self.ui.addToolBar(self.ui.toolbarfile)
  3561. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3562. self.ui.toolbargeo.setObjectName('Edit_TB')
  3563. self.ui.addToolBar(self.ui.toolbargeo)
  3564. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3565. self.ui.toolbarview.setObjectName('View_TB')
  3566. self.ui.addToolBar(self.ui.toolbarview)
  3567. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3568. self.ui.toolbarshell.setObjectName('Shell_TB')
  3569. self.ui.addToolBar(self.ui.toolbarshell)
  3570. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3571. self.ui.toolbartools.setObjectName('Tools_TB')
  3572. self.ui.addToolBar(self.ui.toolbartools)
  3573. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3574. self.ui.exc_edit_toolbar.setVisible(False)
  3575. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3576. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  3577. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3578. self.ui.geo_edit_toolbar.setVisible(False)
  3579. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3580. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  3581. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3582. self.ui.grb_edit_toolbar.setVisible(False)
  3583. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3584. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  3585. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3586. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3587. # self.ui.snap_toolbar.setMaximumHeight(30)
  3588. self.ui.addToolBar(self.ui.snap_toolbar)
  3589. self.ui.corner_snap_btn.setVisible(False)
  3590. self.ui.snap_magnet.setVisible(False)
  3591. elif current_layout == 'compact':
  3592. # ## TOOLBAR INSTALLATION # ##
  3593. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3594. self.ui.toolbarfile.setObjectName('File_TB')
  3595. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  3596. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3597. self.ui.toolbargeo.setObjectName('Edit_TB')
  3598. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  3599. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3600. self.ui.toolbarview.setObjectName('View_TB')
  3601. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  3602. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3603. self.ui.toolbarshell.setObjectName('Shell_TB')
  3604. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  3605. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3606. self.ui.toolbartools.setObjectName('Tools_TB')
  3607. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  3608. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3609. # self.ui.geo_edit_toolbar.setVisible(False)
  3610. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3611. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  3612. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3613. # self.ui.grb_edit_toolbar.setVisible(False)
  3614. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3615. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  3616. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3617. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3618. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  3619. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3620. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3621. self.ui.snap_toolbar.setMaximumHeight(30)
  3622. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  3623. self.ui.corner_snap_btn.setVisible(True)
  3624. self.ui.snap_magnet.setVisible(True)
  3625. # add all the actions to the toolbars
  3626. self.ui.populate_toolbars()
  3627. # reconnect all the signals to the toolbar actions
  3628. self.connect_toolbar_signals()
  3629. self.ui.grid_snap_btn.setChecked(True)
  3630. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  3631. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  3632. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  3633. self.ui.grid_gap_link_cb.setChecked(True)
  3634. def on_cnc_custom_parameters(self, signal_text):
  3635. if signal_text == 'Parameters':
  3636. return
  3637. else:
  3638. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  3639. def on_save_button(self):
  3640. self.save_defaults(silent=False)
  3641. # load the defaults so they are updated into the app
  3642. self.load_defaults(filename='current_defaults')
  3643. # Re-fresh project options
  3644. self.on_options_app2project()
  3645. def handlePrint(self):
  3646. self.report_usage("handlePrint()")
  3647. dialog = QtPrintSupport.QPrintDialog()
  3648. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  3649. self.ui.code_editor.document().print_(dialog.printer())
  3650. def handlePreview(self):
  3651. self.report_usage("handlePreview()")
  3652. dialog = QtPrintSupport.QPrintPreviewDialog()
  3653. dialog.paintRequested.connect(self.ui.code_editor.print_)
  3654. dialog.exec_()
  3655. def handleTextChanged(self):
  3656. # enable = not self.ui.code_editor.document().isEmpty()
  3657. # self.ui.buttonPrint.setEnabled(enable)
  3658. # self.ui.buttonPreview.setEnabled(enable)
  3659. pass
  3660. def handleOpen(self, filt=None):
  3661. self.report_usage("handleOpen()")
  3662. if filt:
  3663. _filter_ = filt
  3664. else:
  3665. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3666. "All Files (*.*)"
  3667. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  3668. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  3669. if path:
  3670. file = QtCore.QFile(path)
  3671. if file.open(QtCore.QIODevice.ReadOnly):
  3672. stream = QtCore.QTextStream(file)
  3673. self.gcode_edited = stream.readAll()
  3674. self.ui.code_editor.setPlainText(self.gcode_edited)
  3675. file.close()
  3676. def handleSaveGCode(self, name=None, filt=None):
  3677. self.report_usage("handleSaveGCode()")
  3678. if filt:
  3679. _filter_ = filt
  3680. else:
  3681. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3682. "All Files (*.*)"
  3683. if name:
  3684. obj_name = name
  3685. else:
  3686. try:
  3687. obj_name = self.collection.get_active().options['name']
  3688. except AttributeError:
  3689. obj_name = 'file'
  3690. if filt is None:
  3691. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  3692. try:
  3693. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3694. caption=_("Export G-Code ..."),
  3695. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  3696. filter=_filter_
  3697. )[0])
  3698. except TypeError:
  3699. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  3700. if filename == "":
  3701. self.inform.emit(_("[WARNING_NOTCL] Export Code cancelled."))
  3702. return
  3703. else:
  3704. try:
  3705. my_gcode = self.ui.code_editor.toPlainText()
  3706. with open(filename, 'w') as f:
  3707. for line in my_gcode:
  3708. f.write(line)
  3709. except FileNotFoundError:
  3710. self.inform.emit(_("[WARNING] No such file or directory"))
  3711. return
  3712. # Just for adding it to the recent files list.
  3713. if self.defaults["global_open_style"] is False:
  3714. self.file_opened.emit("cncjob", filename)
  3715. self.file_saved.emit("cncjob", filename)
  3716. self.inform.emit(_("Saved to: %s") % filename)
  3717. def handleFindGCode(self):
  3718. self.report_usage("handleFindGCode()")
  3719. flags = QtGui.QTextDocument.FindCaseSensitively
  3720. text_to_be_found = self.ui.entryFind.get_value()
  3721. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  3722. if r is False:
  3723. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3724. def handleReplaceGCode(self):
  3725. self.report_usage("handleReplaceGCode()")
  3726. old = self.ui.entryFind.get_value()
  3727. new = self.ui.entryReplace.get_value()
  3728. if self.ui.sel_all_cb.isChecked():
  3729. while True:
  3730. cursor = self.ui.code_editor.textCursor()
  3731. cursor.beginEditBlock()
  3732. flags = QtGui.QTextDocument.FindCaseSensitively
  3733. # self.ui.editor is the QPlainTextEdit
  3734. r = self.ui.code_editor.find(str(old), flags)
  3735. if r:
  3736. qc = self.ui.code_editor.textCursor()
  3737. if qc.hasSelection():
  3738. qc.insertText(new)
  3739. else:
  3740. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3741. break
  3742. # Mark end of undo block
  3743. cursor.endEditBlock()
  3744. else:
  3745. cursor = self.ui.code_editor.textCursor()
  3746. cursor.beginEditBlock()
  3747. qc = self.ui.code_editor.textCursor()
  3748. if qc.hasSelection():
  3749. qc.insertText(new)
  3750. # Mark end of undo block
  3751. cursor.endEditBlock()
  3752. def on_tool_add_keypress(self):
  3753. # ## Current application units in Upper Case
  3754. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3755. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3756. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3757. if notebook_widget_name == 'selected_tab':
  3758. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3759. # Tool add works for Geometry only if Advanced is True in Preferences
  3760. if self.defaults["global_app_level"] == 'a':
  3761. tool_add_popup = FCInputDialog(title="New Tool ...",
  3762. text='Enter a Tool Diameter:',
  3763. min=0.0000, max=99.9999, decimals=4)
  3764. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3765. val, ok = tool_add_popup.get_value()
  3766. if ok:
  3767. if float(val) == 0:
  3768. self.inform.emit(
  3769. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3770. return
  3771. self.collection.get_active().on_tool_add(dia=float(val))
  3772. else:
  3773. self.inform.emit(
  3774. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3775. else:
  3776. msgbox = QtWidgets.QMessageBox()
  3777. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3778. "Go to Preferences -> General - Show Advanced Options."))
  3779. msgbox.setWindowTitle("Tool adding ...")
  3780. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  3781. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3782. msgbox.setDefaultButton(bt_ok)
  3783. msgbox.exec_()
  3784. # work only if the notebook tab on focus is the Tools_Tab
  3785. if notebook_widget_name == 'tool_tab':
  3786. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3787. tool_add_popup = FCInputDialog(title="New Tool ...",
  3788. text='Enter a Tool Diameter:',
  3789. min=0.0000, max=99.9999, decimals=4)
  3790. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3791. val, ok = tool_add_popup.get_value()
  3792. # and only if the tool is NCC Tool
  3793. if tool_widget == self.ncclear_tool.toolName:
  3794. if ok:
  3795. if float(val) == 0:
  3796. self.inform.emit(
  3797. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3798. return
  3799. self.ncclear_tool.on_tool_add(dia=float(val))
  3800. else:
  3801. self.inform.emit(
  3802. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3803. # and only if the tool is Paint Area Tool
  3804. elif tool_widget == self.paint_tool.toolName:
  3805. if ok:
  3806. if float(val) == 0:
  3807. self.inform.emit(
  3808. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3809. return
  3810. self.paint_tool.on_tool_add(dia=float(val))
  3811. else:
  3812. self.inform.emit(
  3813. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3814. # and only if the tool is Solder Paste Dispensing Tool
  3815. elif tool_widget == self.paste_tool.toolName:
  3816. if ok:
  3817. if float(val) == 0:
  3818. self.inform.emit(
  3819. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3820. return
  3821. self.paste_tool.on_tool_add(dia=float(val))
  3822. else:
  3823. self.inform.emit(
  3824. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3825. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3826. # See description bellow.
  3827. def on_delete_keypress(self):
  3828. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3829. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3830. if notebook_widget_name == 'selected_tab':
  3831. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3832. self.collection.get_active().on_tool_delete()
  3833. # work only if the notebook tab on focus is the Tools_Tab
  3834. elif notebook_widget_name == 'tool_tab':
  3835. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3836. # and only if the tool is NCC Tool
  3837. if tool_widget == self.ncclear_tool.toolName:
  3838. self.ncclear_tool.on_tool_delete()
  3839. # and only if the tool is Paint Tool
  3840. elif tool_widget == self.paint_tool.toolName:
  3841. self.paint_tool.on_tool_delete()
  3842. # and only if the tool is Solder Paste Dispensing Tool
  3843. elif tool_widget == self.paste_tool.toolName:
  3844. self.paste_tool.on_tool_delete()
  3845. else:
  3846. self.on_delete()
  3847. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3848. # some screens you have to be careful where you hover with your mouse.
  3849. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3850. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3851. # Complicated, I know :)
  3852. def on_delete(self):
  3853. """
  3854. Delete the currently selected FlatCAMObjs.
  3855. :return: None
  3856. """
  3857. self.report_usage("on_delete()")
  3858. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3859. # a geometry object before we update it.
  3860. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3861. if self.collection.get_active():
  3862. self.log.debug("on_delete()")
  3863. self.report_usage("on_delete")
  3864. while (self.collection.get_active()):
  3865. obj_active = self.collection.get_active()
  3866. # if the deleted object is FlatCAMGerber then make sure to delete the possbile mark shapes
  3867. if isinstance(obj_active, FlatCAMGerber):
  3868. for el in obj_active.mark_shapes:
  3869. obj_active.mark_shapes[el].clear(update=True)
  3870. obj_active.mark_shapes[el].enabled = False
  3871. obj_active.mark_shapes[el] = None
  3872. self.delete_first_selected()
  3873. self.inform.emit(_("Object(s) deleted ..."))
  3874. # make sure that the selection shape is deleted, too
  3875. self.delete_selection_shape()
  3876. else:
  3877. self.inform.emit(_("Failed. No object(s) selected..."))
  3878. else:
  3879. self.inform.emit(_("Save the work in Editor and try again ..."))
  3880. def on_set_origin(self):
  3881. """
  3882. Set the origin to the left mouse click position
  3883. :return: None
  3884. """
  3885. # display the message for the user
  3886. # and ask him to click on the desired position
  3887. self.report_usage("on_set_origin()")
  3888. self.inform.emit(_('Click to set the origin ...'))
  3889. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3890. def on_jump_to(self, custom_location=None, fit_center=True):
  3891. """
  3892. Jump to a location by setting the mouse cursor location
  3893. :return:
  3894. """
  3895. self.report_usage("on_jump_to()")
  3896. if not custom_location:
  3897. dia_box = Dialog_box(title=_("Jump to ..."),
  3898. label=_("Enter the coordinates in format X,Y:"),
  3899. icon=QtGui.QIcon('share/jump_to16.png'))
  3900. if dia_box.ok is True:
  3901. try:
  3902. location = eval(dia_box.location)
  3903. if not isinstance(location, tuple):
  3904. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3905. return
  3906. except:
  3907. return
  3908. else:
  3909. return
  3910. else:
  3911. location = custom_location
  3912. if fit_center:
  3913. self.plotcanvas.fit_center(loc=location)
  3914. cursor = QtGui.QCursor()
  3915. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3916. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3917. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3918. self.inform.emit(_("[success] Done."))
  3919. def on_copy_object(self):
  3920. self.report_usage("on_copy_object()")
  3921. def initialize(obj_init, app):
  3922. obj_init.solid_geometry = obj.solid_geometry
  3923. try:
  3924. obj_init.follow_geometry = obj.follow_geometry
  3925. except AttributeError:
  3926. pass
  3927. try:
  3928. obj_init.apertures = obj.apertures
  3929. except AttributeError:
  3930. pass
  3931. try:
  3932. if obj.tools:
  3933. obj_init.tools = obj.tools
  3934. except Exception as e:
  3935. log.debug("App.on_copy_object() --> %s" % str(e))
  3936. def initialize_excellon(obj_init, app):
  3937. obj_init.tools = obj.tools
  3938. # drills are offset, so they need to be deep copied
  3939. obj_init.drills = deepcopy(obj.drills)
  3940. # slots are offset, so they need to be deep copied
  3941. obj_init.slots = deepcopy(obj.slots)
  3942. obj_init.create_geometry()
  3943. for obj in self.collection.get_selected():
  3944. obj_name = obj.options["name"]
  3945. try:
  3946. if isinstance(obj, FlatCAMExcellon):
  3947. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3948. elif isinstance(obj,FlatCAMGerber):
  3949. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3950. elif isinstance(obj,FlatCAMGeometry):
  3951. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3952. except Exception as e:
  3953. return "Operation failed: %s" % str(e)
  3954. def on_copy_object2(self, custom_name):
  3955. def initialize_geometry(obj_init, app):
  3956. obj_init.solid_geometry = obj.solid_geometry
  3957. try:
  3958. obj_init.follow_geometry = obj.follow_geometry
  3959. except AttributeError:
  3960. pass
  3961. try:
  3962. obj_init.apertures = obj.apertures
  3963. except AttributeError:
  3964. pass
  3965. try:
  3966. if obj.tools:
  3967. obj_init.tools = obj.tools
  3968. except Exception as e:
  3969. log.debug("on_copy_object2() --> %s" % str(e))
  3970. def initialize_gerber(obj_init, app):
  3971. obj_init.solid_geometry = obj.solid_geometry
  3972. obj_init.apertures = deepcopy(obj.apertures)
  3973. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3974. def initialize_excellon(obj_init, app):
  3975. obj_init.tools = obj.tools
  3976. # drills are offset, so they need to be deep copied
  3977. obj_init.drills = deepcopy(obj.drills)
  3978. # slots are offset, so they need to be deep copied
  3979. obj_init.slots = deepcopy(obj.slots)
  3980. obj_init.create_geometry()
  3981. for obj in self.collection.get_selected():
  3982. obj_name = obj.options["name"]
  3983. try:
  3984. if isinstance(obj, FlatCAMExcellon):
  3985. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3986. elif isinstance(obj,FlatCAMGerber):
  3987. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3988. elif isinstance(obj,FlatCAMGeometry):
  3989. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3990. except Exception as e:
  3991. return "Operation failed: %s" % str(e)
  3992. def on_rename_object(self, text):
  3993. self.report_usage("on_rename_object()")
  3994. named_obj = self.collection.get_active()
  3995. for obj in named_obj:
  3996. if obj is list:
  3997. self.on_rename_object(text)
  3998. else:
  3999. try:
  4000. obj.options['name'] = text
  4001. except Exception as e:
  4002. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4003. def convert_any2geo(self):
  4004. self.report_usage("convert_any2geo()")
  4005. def initialize(obj_init, app):
  4006. obj_init.solid_geometry = obj.solid_geometry
  4007. try:
  4008. obj_init.follow_geometry = obj.follow_geometry
  4009. except AttributeError:
  4010. pass
  4011. try:
  4012. obj_init.apertures = obj.apertures
  4013. except AttributeError:
  4014. pass
  4015. try:
  4016. if obj.tools:
  4017. obj_init.tools = obj.tools
  4018. except AttributeError:
  4019. pass
  4020. def initialize_excellon(obj_init, app):
  4021. # objs = self.collection.get_selected()
  4022. # FlatCAMGeometry.merge(objs, obj)
  4023. solid_geo = []
  4024. for tool in obj.tools:
  4025. for geo in obj.tools[tool]['solid_geometry']:
  4026. solid_geo.append(geo)
  4027. obj_init.solid_geometry = deepcopy(solid_geo)
  4028. if not self.collection.get_selected():
  4029. log.warning("App.convert_any2geo --> No object selected")
  4030. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4031. return
  4032. for obj in self.collection.get_selected():
  4033. obj_name = obj.options["name"]
  4034. try:
  4035. if isinstance(obj, FlatCAMExcellon):
  4036. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4037. else:
  4038. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4039. except Exception as e:
  4040. return "Operation failed: %s" % str(e)
  4041. def convert_any2gerber(self):
  4042. self.report_usage("convert_any2gerber()")
  4043. def initialize_geometry(obj_init, app):
  4044. apertures = {}
  4045. apid = 0
  4046. apertures[str(apid)] = {}
  4047. apertures[str(apid)]['geometry'] = []
  4048. for obj_orig in obj.solid_geometry:
  4049. new_elem = dict()
  4050. new_elem['solid'] = obj_orig
  4051. new_elem['follow'] = obj_orig.exterior
  4052. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4053. apertures[str(apid)]['size'] = 0.0
  4054. apertures[str(apid)]['type'] = 'C'
  4055. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4056. obj_init.apertures = deepcopy(apertures)
  4057. def initialize_excellon(obj_init, app):
  4058. apertures = {}
  4059. apid = 10
  4060. for tool in obj.tools:
  4061. apertures[str(apid)] = {}
  4062. apertures[str(apid)]['geometry'] = []
  4063. for geo in obj.tools[tool]['solid_geometry']:
  4064. new_el = dict()
  4065. new_el['solid'] = geo
  4066. new_el['follow'] = geo.exterior
  4067. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4068. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4069. apertures[str(apid)]['type'] = 'C'
  4070. apid += 1
  4071. # create solid_geometry
  4072. solid_geometry = []
  4073. for apid in apertures:
  4074. for geo_el in apertures[apid]['geometry']:
  4075. solid_geometry.append(geo_el['solid'])
  4076. solid_geometry = MultiPolygon(solid_geometry)
  4077. solid_geometry = solid_geometry.buffer(0.0000001)
  4078. obj_init.solid_geometry = deepcopy(solid_geometry)
  4079. obj_init.apertures = deepcopy(apertures)
  4080. # clear the working objects (perhaps not necessary due of Python GC)
  4081. apertures.clear()
  4082. if not self.collection.get_selected():
  4083. log.warning("App.convert_any2gerber --> No object selected")
  4084. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4085. return
  4086. for obj in self.collection.get_selected():
  4087. obj_name = obj.options["name"]
  4088. try:
  4089. if isinstance(obj, FlatCAMExcellon):
  4090. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4091. elif isinstance(obj, FlatCAMGeometry):
  4092. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4093. else:
  4094. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4095. except Exception as e:
  4096. return "Operation failed: %s" % str(e)
  4097. def on_set_zero_click(self, event):
  4098. #this function will be available only for mouse left click
  4099. pos =[]
  4100. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4101. if event.button == 1:
  4102. if self.grid_status() == True:
  4103. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4104. else:
  4105. pos = pos_canvas
  4106. x = 0 - pos[0]
  4107. y = 0 - pos[1]
  4108. for obj in self.collection.get_list():
  4109. obj.offset((x,y))
  4110. self.object_changed.emit(obj)
  4111. obj.plot()
  4112. # Update the object bounding box options
  4113. a, b, c, d = obj.bounds()
  4114. obj.options['xmin'] = a
  4115. obj.options['ymin'] = b
  4116. obj.options['xmax'] = c
  4117. obj.options['ymax'] = d
  4118. # self.plot_all(zoom=False)
  4119. self.inform.emit(_('[success] Origin set ...'))
  4120. self.plotcanvas.fit_view()
  4121. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  4122. self.should_we_save = True
  4123. def on_selectall(self):
  4124. self.report_usage("on_selectall()")
  4125. # delete the possible selection box around a possible selected object
  4126. self.delete_selection_shape()
  4127. for name in self.collection.get_names():
  4128. self.collection.set_active(name)
  4129. curr_sel_obj = self.collection.get_by_name(name)
  4130. # create the selection box around the selected object
  4131. if self.defaults['global_selection_shape'] is True:
  4132. self.draw_selection_shape(curr_sel_obj)
  4133. def on_preferences(self):
  4134. # add the tab if it was closed
  4135. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4136. # delete the absolute and relative position and messages in the infobar
  4137. self.ui.position_label.setText("")
  4138. self.ui.rel_position_label.setText("")
  4139. # Switch plot_area to preferences page
  4140. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4141. self.ui.show()
  4142. def on_flipy(self):
  4143. self.report_usage("on_flipy()")
  4144. obj_list = self.collection.get_selected()
  4145. xminlist = []
  4146. yminlist = []
  4147. xmaxlist = []
  4148. ymaxlist = []
  4149. if not obj_list:
  4150. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  4151. else:
  4152. try:
  4153. # first get a bounding box to fit all
  4154. for obj in obj_list:
  4155. xmin, ymin, xmax, ymax = obj.bounds()
  4156. xminlist.append(xmin)
  4157. yminlist.append(ymin)
  4158. xmaxlist.append(xmax)
  4159. ymaxlist.append(ymax)
  4160. # get the minimum x,y and maximum x,y for all objects selected
  4161. xminimal = min(xminlist)
  4162. yminimal = min(yminlist)
  4163. xmaximal = max(xmaxlist)
  4164. ymaximal = max(ymaxlist)
  4165. px = 0.5 * (xminimal + xmaximal)
  4166. py = 0.5 * (yminimal + ymaximal)
  4167. # execute mirroring
  4168. for obj in obj_list:
  4169. obj.mirror('X', [px, py])
  4170. obj.plot()
  4171. self.object_changed.emit(obj)
  4172. self.inform.emit(_("[success] Flip on Y axis done."))
  4173. except Exception as e:
  4174. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4175. return
  4176. def on_flipx(self):
  4177. self.report_usage("on_flipx()")
  4178. obj_list = self.collection.get_selected()
  4179. xminlist = []
  4180. yminlist = []
  4181. xmaxlist = []
  4182. ymaxlist = []
  4183. if not obj_list:
  4184. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  4185. else:
  4186. try:
  4187. # first get a bounding box to fit all
  4188. for obj in obj_list:
  4189. xmin, ymin, xmax, ymax = obj.bounds()
  4190. xminlist.append(xmin)
  4191. yminlist.append(ymin)
  4192. xmaxlist.append(xmax)
  4193. ymaxlist.append(ymax)
  4194. # get the minimum x,y and maximum x,y for all objects selected
  4195. xminimal = min(xminlist)
  4196. yminimal = min(yminlist)
  4197. xmaximal = max(xmaxlist)
  4198. ymaximal = max(ymaxlist)
  4199. px = 0.5 * (xminimal + xmaximal)
  4200. py = 0.5 * (yminimal + ymaximal)
  4201. # execute mirroring
  4202. for obj in obj_list:
  4203. obj.mirror('Y', [px, py])
  4204. obj.plot()
  4205. self.object_changed.emit(obj)
  4206. self.inform.emit(_("[success] Flip on X axis done."))
  4207. except Exception as e:
  4208. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4209. return
  4210. def on_rotate(self, silent=False, preset=None):
  4211. self.report_usage("on_rotate()")
  4212. obj_list = self.collection.get_selected()
  4213. xminlist = []
  4214. yminlist = []
  4215. xmaxlist = []
  4216. ymaxlist = []
  4217. if not obj_list:
  4218. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  4219. else:
  4220. if silent is False:
  4221. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4222. min=-360, max=360, decimals=4,
  4223. init_val=float(self.defaults['tools_transform_rotate']))
  4224. num, ok = rotatebox.get_value()
  4225. else:
  4226. num = preset
  4227. ok = True
  4228. if ok:
  4229. try:
  4230. # first get a bounding box to fit all
  4231. for obj in obj_list:
  4232. xmin, ymin, xmax, ymax = obj.bounds()
  4233. xminlist.append(xmin)
  4234. yminlist.append(ymin)
  4235. xmaxlist.append(xmax)
  4236. ymaxlist.append(ymax)
  4237. # get the minimum x,y and maximum x,y for all objects selected
  4238. xminimal = min(xminlist)
  4239. yminimal = min(yminlist)
  4240. xmaximal = max(xmaxlist)
  4241. ymaximal = max(ymaxlist)
  4242. px = 0.5 * (xminimal + xmaximal)
  4243. py = 0.5 * (yminimal + ymaximal)
  4244. for sel_obj in obj_list:
  4245. sel_obj.rotate(-float(num), point=(px, py))
  4246. sel_obj.plot()
  4247. self.object_changed.emit(sel_obj)
  4248. self.inform.emit(_("[success] Rotation done."))
  4249. except Exception as e:
  4250. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  4251. return
  4252. def on_skewx(self):
  4253. self.report_usage("on_skewx()")
  4254. obj_list = self.collection.get_selected()
  4255. xminlist = []
  4256. yminlist = []
  4257. if not obj_list:
  4258. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  4259. else:
  4260. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4261. min=-360, max=360, decimals=4,
  4262. init_val=float(self.defaults['tools_transform_skew_x']))
  4263. num, ok = skewxbox.get_value()
  4264. if ok:
  4265. # first get a bounding box to fit all
  4266. for obj in obj_list:
  4267. xmin, ymin, xmax, ymax = obj.bounds()
  4268. xminlist.append(xmin)
  4269. yminlist.append(ymin)
  4270. # get the minimum x,y and maximum x,y for all objects selected
  4271. xminimal = min(xminlist)
  4272. yminimal = min(yminlist)
  4273. for obj in obj_list:
  4274. obj.skew(num, 0, point=(xminimal, yminimal))
  4275. obj.plot()
  4276. self.object_changed.emit(obj)
  4277. self.inform.emit(_("[success] Skew on X axis done."))
  4278. def on_skewy(self):
  4279. self.report_usage("on_skewy()")
  4280. obj_list = self.collection.get_selected()
  4281. xminlist = []
  4282. yminlist = []
  4283. if not obj_list:
  4284. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  4285. else:
  4286. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4287. min=-360, max=360, decimals=4,
  4288. init_val=float(self.defaults['tools_transform_skew_y']))
  4289. num, ok = skewybox.get_value()
  4290. if ok:
  4291. # first get a bounding box to fit all
  4292. for obj in obj_list:
  4293. xmin, ymin, xmax, ymax = obj.bounds()
  4294. xminlist.append(xmin)
  4295. yminlist.append(ymin)
  4296. # get the minimum x,y and maximum x,y for all objects selected
  4297. xminimal = min(xminlist)
  4298. yminimal = min(yminlist)
  4299. for obj in obj_list:
  4300. obj.skew(0, num, point=(xminimal, yminimal))
  4301. obj.plot()
  4302. self.object_changed.emit(obj)
  4303. self.inform.emit(_("[success] Skew on Y axis done."))
  4304. def delete_first_selected(self):
  4305. # Keep this for later
  4306. try:
  4307. name = self.collection.get_active().options["name"]
  4308. except AttributeError:
  4309. self.log.debug("Nothing selected for deletion")
  4310. return
  4311. # Remove plot
  4312. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4313. # self.plotcanvas.auto_adjust_axes()
  4314. # Clear form
  4315. self.setup_component_editor()
  4316. # Remove from dictionary
  4317. self.collection.delete_active()
  4318. self.inform.emit("Object deleted: %s" % name)
  4319. def on_plots_updated(self):
  4320. """
  4321. Callback used to report when the plots have changed.
  4322. Adjust axes and zooms to fit.
  4323. :return: None
  4324. """
  4325. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  4326. self.on_zoom_fit(None)
  4327. self.collection.update_view()
  4328. # TODO: Rework toolbar 'clear', 'replot' functions
  4329. def on_toolbar_replot(self):
  4330. """
  4331. Callback for toolbar button. Re-plots all objects.
  4332. :return: None
  4333. """
  4334. self.report_usage("on_toolbar_replot")
  4335. self.log.debug("on_toolbar_replot()")
  4336. try:
  4337. self.collection.get_active().read_form()
  4338. except AttributeError:
  4339. self.log.debug("on_toolbar_replot(): AttributeError")
  4340. pass
  4341. self.plot_all()
  4342. def on_row_activated(self, index):
  4343. if index.isValid():
  4344. if index.internalPointer().parent_item != self.collection.root_item:
  4345. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4346. def grid_status(self):
  4347. if self.ui.grid_snap_btn.isChecked():
  4348. return 1
  4349. else:
  4350. return 0
  4351. def populate_cmenu_grids(self):
  4352. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4353. self.ui.cmenu_gridmenu.clear()
  4354. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4355. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  4356. grid_toggle.setCheckable(True)
  4357. if self.grid_status():
  4358. grid_toggle.setChecked(True)
  4359. else:
  4360. grid_toggle.setChecked(False)
  4361. self.ui.cmenu_gridmenu.addSeparator()
  4362. for grid in sorted_list:
  4363. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  4364. action.triggered.connect(self.set_grid)
  4365. self.ui.cmenu_gridmenu.addSeparator()
  4366. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  4367. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  4368. grid_add.triggered.connect(self.on_grid_add)
  4369. grid_delete.triggered.connect(self.on_grid_delete)
  4370. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4371. def set_grid(self):
  4372. self.ui.grid_gap_x_entry.setText(self.sender().text())
  4373. self.ui.grid_gap_y_entry.setText(self.sender().text())
  4374. def on_grid_add(self):
  4375. # ## Current application units in lower Case
  4376. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4377. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4378. text=_('Enter a Grid Value:'),
  4379. min=0.0000, max=99.9999, decimals=4)
  4380. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  4381. val, ok = grid_add_popup.get_value()
  4382. if ok:
  4383. if float(val) == 0:
  4384. self.inform.emit(
  4385. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4386. return
  4387. else:
  4388. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4389. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4390. self.inform.emit(
  4391. _("[success] New Grid added ..."))
  4392. else:
  4393. self.inform.emit(
  4394. _("[WARNING_NOTCL] Grid already exists ..."))
  4395. else:
  4396. self.inform.emit(
  4397. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  4398. def on_grid_delete(self):
  4399. # ## Current application units in lower Case
  4400. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4401. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4402. text='Enter a Grid Value:',
  4403. min=0.0000, max=99.9999, decimals=4)
  4404. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  4405. val, ok = grid_del_popup.get_value()
  4406. if ok:
  4407. if float(val) == 0:
  4408. self.inform.emit(
  4409. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4410. return
  4411. else:
  4412. try:
  4413. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4414. except ValueError:
  4415. self.inform.emit(
  4416. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  4417. return
  4418. self.inform.emit(
  4419. _("[success] Grid Value deleted ..."))
  4420. else:
  4421. self.inform.emit(
  4422. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  4423. def on_shortcut_list(self):
  4424. self.report_usage("on_shortcut_list()")
  4425. # add the tab if it was closed
  4426. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  4427. # delete the absolute and relative position and messages in the infobar
  4428. self.ui.position_label.setText("")
  4429. self.ui.rel_position_label.setText("")
  4430. # Switch plot_area to preferences page
  4431. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4432. self.ui.show()
  4433. def on_select_tab(self, name):
  4434. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4435. if self.ui.splitter.sizes()[0] == 0:
  4436. self.ui.splitter.setSizes([1, 1])
  4437. else:
  4438. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4439. self.ui.splitter.setSizes([0, 1])
  4440. if name == 'project':
  4441. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4442. elif name == 'selected':
  4443. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4444. elif name == 'tool':
  4445. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4446. def on_copy_name(self):
  4447. self.report_usage("on_copy_name()")
  4448. obj = self.collection.get_active()
  4449. try:
  4450. name = obj.options["name"]
  4451. except AttributeError:
  4452. log.debug("on_copy_name() --> No object selected to copy it's name")
  4453. self.inform.emit(_("[WARNING_NOTCL] No object selected to copy it's name"))
  4454. return
  4455. self.clipboard.setText(name)
  4456. self.inform.emit(_("Name copied on clipboard ..."))
  4457. def on_mouse_click_over_plot(self, event):
  4458. """
  4459. Default actions are:
  4460. :param event: Contains information about the event, like which button
  4461. was clicked, the pixel coordinates and the axes coordinates.
  4462. :return: None
  4463. """
  4464. self.pos = []
  4465. # So it can receive key presses
  4466. self.plotcanvas.vispy_canvas.native.setFocus()
  4467. # Set the mouse button for panning
  4468. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  4469. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4470. if self.grid_status() == True:
  4471. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4472. self.app_cursor.enabled = True
  4473. else:
  4474. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4475. self.app_cursor.enabled = False
  4476. try:
  4477. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4478. if event.button == 1:
  4479. # Reset here the relative coordinates so there is a new reference on the click position
  4480. if self.rel_point1 is None:
  4481. self.rel_point1 = self.pos
  4482. else:
  4483. self.rel_point2 = copy(self.rel_point1)
  4484. self.rel_point1 = self.pos
  4485. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4486. if modifiers == QtCore.Qt.ShiftModifier:
  4487. # do not auto open the Project Tab
  4488. self.click_noproject = True
  4489. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  4490. return
  4491. self.on_mouse_move_over_plot(event, origin_click=True)
  4492. except Exception as e:
  4493. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4494. def on_double_click_over_plot(self, event):
  4495. self.doubleclick = True
  4496. def on_mouse_move_over_plot(self, event, origin_click=None):
  4497. """
  4498. Callback for the mouse motion event over the plot.
  4499. :param event: Contains information about the event.
  4500. :param origin_click
  4501. :return: None
  4502. """
  4503. # So it can receive key presses
  4504. self.plotcanvas.vispy_canvas.native.setFocus()
  4505. self.pos_jump = event.pos
  4506. self.ui.popMenu.mouse_is_panning = False
  4507. if origin_click != True:
  4508. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4509. if event.button == 2 and event.is_dragging == 1:
  4510. self.ui.popMenu.mouse_is_panning = True
  4511. return
  4512. if self.rel_point1 is not None:
  4513. try: # May fail in case mouse not within axes
  4514. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4515. if self.grid_status():
  4516. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4517. self.app_cursor.enabled = True
  4518. # Update cursor
  4519. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  4520. else:
  4521. pos = (pos_canvas[0], pos_canvas[1])
  4522. self.app_cursor.enabled = False
  4523. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4524. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  4525. dx = pos[0] - self.rel_point1[0]
  4526. dy = pos[1] - self.rel_point1[1]
  4527. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4528. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4529. self.mouse = [pos[0], pos[1]]
  4530. # if the mouse is moved and the LMB is clicked then the action is a selection
  4531. if event.is_dragging == 1 and event.button == 1:
  4532. self.delete_selection_shape()
  4533. if dx < 0:
  4534. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4535. face_color=self.defaults['global_alt_sel_fill'])
  4536. self.selection_type = False
  4537. else:
  4538. self.draw_moving_selection_shape(self.pos, pos)
  4539. self.selection_type = True
  4540. # hover effect - enabled in Preferences -> General -> GUI Settings
  4541. if self.defaults['global_hover']:
  4542. for obj in self.collection.get_list():
  4543. try:
  4544. # select the object(s) only if it is enabled (plotted)
  4545. if obj.options['plot']:
  4546. if obj not in self.collection.get_selected():
  4547. poly_obj = Polygon(
  4548. [(obj.options['xmin'], obj.options['ymin']),
  4549. (obj.options['xmax'], obj.options['ymin']),
  4550. (obj.options['xmax'], obj.options['ymax']),
  4551. (obj.options['xmin'], obj.options['ymax'])]
  4552. )
  4553. if Point(pos).within(poly_obj):
  4554. if obj.isHovering is False:
  4555. obj.isHovering = True
  4556. obj.notHovering = True
  4557. # create the selection box around the selected object
  4558. self.draw_hover_shape(obj, color='#d1e0e0')
  4559. else:
  4560. if obj.notHovering is True:
  4561. obj.notHovering = False
  4562. obj.isHovering = False
  4563. self.delete_hover_shape()
  4564. except:
  4565. # the Exception here will happen if we try to select on screen and we have an
  4566. # newly (and empty) just created Geometry or Excellon object that do not have the
  4567. # xmin, xmax, ymin, ymax options.
  4568. # In this case poly_obj creation (see above) will fail
  4569. pass
  4570. except:
  4571. self.ui.position_label.setText("")
  4572. self.ui.rel_position_label.setText("")
  4573. self.mouse = None
  4574. def on_mouse_click_release_over_plot(self, event):
  4575. """
  4576. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4577. and has been registered in ''self.__init__()''.
  4578. :param event: contains information about the event.
  4579. :return:
  4580. """
  4581. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4582. if self.grid_status():
  4583. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4584. else:
  4585. pos = (pos_canvas[0], pos_canvas[1])
  4586. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4587. # canvas menu
  4588. try:
  4589. if event.button == 2: # right click
  4590. if self.ui.popMenu.mouse_is_panning is False:
  4591. self.cursor = QtGui.QCursor()
  4592. self.populate_cmenu_grids()
  4593. self.ui.popMenu.popup(self.cursor.pos())
  4594. except Exception as e:
  4595. log.warning("Error: %s" % str(e))
  4596. return
  4597. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4598. # selection and then select a type of selection ("enclosing" or "touching")
  4599. try:
  4600. if event.button == 1: # left click
  4601. if self.doubleclick is True:
  4602. self.doubleclick = False
  4603. if self.collection.get_selected():
  4604. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4605. if self.ui.splitter.sizes()[0] == 0:
  4606. self.ui.splitter.setSizes([1, 1])
  4607. # delete the selection shape(S) as it may be in the way
  4608. self.delete_selection_shape()
  4609. self.delete_hover_shape()
  4610. else:
  4611. if self.selection_type is not None:
  4612. self.selection_area_handler(self.pos, pos, self.selection_type)
  4613. self.selection_type = None
  4614. else:
  4615. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4616. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  4617. # deselect, and if it's not selected then it will be selected
  4618. if modifiers == QtCore.Qt.ControlModifier:
  4619. # If there is no active command (self.command_active is None) then we check if we clicked
  4620. # on a object by checking the bounding limits against mouse click position
  4621. if self.command_active is None:
  4622. self.select_objects(key='CTRL')
  4623. self.delete_hover_shape()
  4624. else:
  4625. # If there is no active command (self.command_active is None) then we check if we clicked
  4626. # on a object by checking the bounding limits against mouse click position
  4627. if self.command_active is None:
  4628. self.select_objects()
  4629. self.delete_hover_shape()
  4630. except Exception as e:
  4631. log.warning("Error: %s" % str(e))
  4632. return
  4633. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4634. """
  4635. :param start_pos: mouse position when the selection LMB click was done
  4636. :param end_pos: mouse position when the left mouse button is released
  4637. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4638. :return:
  4639. """
  4640. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4641. self.delete_selection_shape()
  4642. for obj in self.collection.get_list():
  4643. try:
  4644. # select the object(s) only if it is enabled (plotted)
  4645. if obj.options['plot']:
  4646. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4647. (obj.options['xmax'], obj.options['ymin']),
  4648. (obj.options['xmax'], obj.options['ymax']),
  4649. (obj.options['xmin'], obj.options['ymax'])])
  4650. if sel_type is True:
  4651. if poly_obj.within(poly_selection):
  4652. # create the selection box around the selected object
  4653. if self.defaults['global_selection_shape'] is True:
  4654. self.draw_selection_shape(obj)
  4655. self.collection.set_active(obj.options['name'])
  4656. else:
  4657. if poly_selection.intersects(poly_obj):
  4658. # create the selection box around the selected object
  4659. if self.defaults['global_selection_shape'] is True:
  4660. self.draw_selection_shape(obj)
  4661. self.collection.set_active(obj.options['name'])
  4662. except Exception as e:
  4663. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4664. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4665. # In this case poly_obj creation (see above) will fail
  4666. log.debug("App.selection_area_handler() --> %s" % str(e))
  4667. def select_objects(self, key=None):
  4668. # list where we store the overlapped objects under our mouse left click position
  4669. objects_under_the_click_list = []
  4670. # Populate the list with the overlapped objects on the click position
  4671. curr_x, curr_y = self.pos
  4672. for obj in self.all_objects_list:
  4673. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4674. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4675. if obj.options['name'] not in objects_under_the_click_list:
  4676. if obj.options['plot']:
  4677. # add objects to the objects_under_the_click list only if the object is plotted
  4678. # (active and not disabled)
  4679. objects_under_the_click_list.append(obj.options['name'])
  4680. try:
  4681. # If there is no element in the overlapped objects list then make everyone inactive
  4682. # because we selected "nothing"
  4683. if not objects_under_the_click_list:
  4684. self.collection.set_all_inactive()
  4685. # delete the possible selection box around a possible selected object
  4686. self.delete_selection_shape()
  4687. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  4688. # only when working on App
  4689. if self.call_source == 'app':
  4690. if self.click_noproject is False:
  4691. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4692. else:
  4693. # restore auto open the Project Tab
  4694. self.click_noproject = False
  4695. # delete any text in the status bar, implicitly the last object name that was selected
  4696. self.inform.emit("")
  4697. else:
  4698. self.call_source = 'app'
  4699. else:
  4700. # case when there is only an object under the click and we toggle it
  4701. if len(objects_under_the_click_list) == 1:
  4702. if self.collection.get_active() is None :
  4703. self.collection.set_active(objects_under_the_click_list[0])
  4704. # create the selection box around the selected object
  4705. curr_sel_obj = self.collection.get_active()
  4706. if self.defaults['global_selection_shape'] is True:
  4707. self.draw_selection_shape(curr_sel_obj)
  4708. # self.inform.emit('[selected] %s: %s selected' %
  4709. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4710. if curr_sel_obj.kind == 'gerber':
  4711. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4712. color='green', name=str(curr_sel_obj.options['name'])))
  4713. elif curr_sel_obj.kind == 'excellon':
  4714. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4715. color='brown', name=str(curr_sel_obj.options['name'])))
  4716. elif curr_sel_obj.kind == 'cncjob':
  4717. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4718. color='blue', name=str(curr_sel_obj.options['name'])))
  4719. elif curr_sel_obj.kind == 'geometry':
  4720. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4721. color='red', name=str(curr_sel_obj.options['name'])))
  4722. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  4723. self.collection.set_all_inactive()
  4724. self.delete_selection_shape()
  4725. self.collection.set_active(objects_under_the_click_list[0])
  4726. # create the selection box around the selected object
  4727. curr_sel_obj = self.collection.get_active()
  4728. if self.defaults['global_selection_shape'] is True:
  4729. self.draw_selection_shape(curr_sel_obj)
  4730. # self.inform.emit('[selected] %s: %s selected' %
  4731. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4732. if curr_sel_obj.kind == 'gerber':
  4733. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4734. color='green', name=str(curr_sel_obj.options['name'])))
  4735. elif curr_sel_obj.kind == 'excellon':
  4736. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4737. color='brown', name=str(curr_sel_obj.options['name'])))
  4738. elif curr_sel_obj.kind == 'cncjob':
  4739. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4740. color='blue', name=str(curr_sel_obj.options['name'])))
  4741. elif curr_sel_obj.kind == 'geometry':
  4742. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4743. color='red', name=str(curr_sel_obj.options['name'])))
  4744. else:
  4745. self.collection.set_all_inactive()
  4746. self.delete_selection_shape()
  4747. if self.call_source == 'app':
  4748. # delete any text in the status bar, implicitly the last object name that was selected
  4749. self.inform.emit("")
  4750. else:
  4751. self.call_source = 'app'
  4752. else:
  4753. # If there is no selected object
  4754. # make active the first element of the overlapped objects list
  4755. if self.collection.get_active() is None:
  4756. self.collection.set_active(objects_under_the_click_list[0])
  4757. name_sel_obj = self.collection.get_active().options['name']
  4758. # In case that there is a selected object but it is not in the overlapped object list
  4759. # make that object inactive and activate the first element in the overlapped object list
  4760. if name_sel_obj not in objects_under_the_click_list:
  4761. self.collection.set_inactive(name_sel_obj)
  4762. name_sel_obj = objects_under_the_click_list[0]
  4763. self.collection.set_active(name_sel_obj)
  4764. else:
  4765. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  4766. self.collection.set_all_inactive()
  4767. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  4768. len(objects_under_the_click_list)])
  4769. curr_sel_obj = self.collection.get_active()
  4770. # delete the possible selection box around a possible selected object
  4771. self.delete_selection_shape()
  4772. # create the selection box around the selected object
  4773. if self.defaults['global_selection_shape'] is True:
  4774. self.draw_selection_shape(curr_sel_obj)
  4775. # self.inform.emit('[selected] %s: %s selected' %
  4776. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4777. if curr_sel_obj.kind == 'gerber':
  4778. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4779. color='green', name=str(curr_sel_obj.options['name'])))
  4780. elif curr_sel_obj.kind == 'excellon':
  4781. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4782. color='brown', name=str(curr_sel_obj.options['name'])))
  4783. elif curr_sel_obj.kind == 'cncjob':
  4784. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4785. color='blue', name=str(curr_sel_obj.options['name'])))
  4786. elif curr_sel_obj.kind == 'geometry':
  4787. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4788. color='red', name=str(curr_sel_obj.options['name'])))
  4789. # for obj in self.collection.get_list():
  4790. # obj.plot()
  4791. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  4792. # TODO: on selected objects change the object colors and do not draw the selection box
  4793. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  4794. except Exception as e:
  4795. log.error("[ERROR] Something went bad. %s" % str(e))
  4796. return
  4797. def delete_hover_shape(self):
  4798. self.hover_shapes.clear()
  4799. self.hover_shapes.redraw()
  4800. def draw_hover_shape(self, sel_obj, color=None):
  4801. """
  4802. :param sel_obj: the object for which the hover shape must be drawn
  4803. :return:
  4804. """
  4805. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4806. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4807. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4808. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4809. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  4810. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4811. hover_rect = hover_rect.buffer(-0.1)
  4812. hover_rect = hover_rect.buffer(0.2)
  4813. else:
  4814. hover_rect = hover_rect.buffer(-0.00393)
  4815. hover_rect = hover_rect.buffer(0.00787)
  4816. if color:
  4817. face = Color(color)
  4818. face.alpha = 0.2
  4819. outline = Color(color, alpha=0.8)
  4820. else:
  4821. face = Color(self.defaults['global_sel_fill'])
  4822. face.alpha = 0.2
  4823. outline = self.defaults['global_sel_line']
  4824. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  4825. def delete_selection_shape(self):
  4826. self.move_tool.sel_shapes.clear()
  4827. self.move_tool.sel_shapes.redraw()
  4828. def draw_selection_shape(self, sel_obj, color=None):
  4829. """
  4830. :param sel_obj: the object for which the selection shape must be drawn
  4831. :return:
  4832. """
  4833. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4834. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4835. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4836. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4837. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4838. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4839. sel_rect = sel_rect.buffer(-0.1)
  4840. sel_rect = sel_rect.buffer(0.2)
  4841. else:
  4842. sel_rect = sel_rect.buffer(-0.00393)
  4843. sel_rect = sel_rect.buffer(0.00787)
  4844. if color:
  4845. face = Color(color, alpha=0.2)
  4846. outline = Color(color, alpha=0.8)
  4847. else:
  4848. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  4849. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  4850. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=outline,
  4851. face_color=face, update=True, layer=0, tolerance=None))
  4852. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  4853. """
  4854. :param old_coords: old coordinates
  4855. :param coords: new coordinates
  4856. :return:
  4857. """
  4858. if 'color' in kwargs:
  4859. color = kwargs['color']
  4860. else:
  4861. color = self.defaults['global_sel_line']
  4862. if 'face_color' in kwargs:
  4863. face_color = kwargs['face_color']
  4864. else:
  4865. face_color = self.defaults['global_sel_fill']
  4866. x0, y0 = old_coords
  4867. x1, y1 = coords
  4868. pt1 = (x0, y0)
  4869. pt2 = (x1, y0)
  4870. pt3 = (x1, y1)
  4871. pt4 = (x0, y1)
  4872. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4873. color_t = Color(face_color)
  4874. color_t.alpha = 0.3
  4875. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  4876. layer=0, tolerance=None)
  4877. def on_file_new_click(self):
  4878. if self.collection.get_list() and self.should_we_save:
  4879. msgbox = QtWidgets.QMessageBox()
  4880. # msgbox.setText("<B>Save changes ...</B>")
  4881. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  4882. "Creating a New project will delete them.\n"
  4883. "Do you want to Save the project?"))
  4884. msgbox.setWindowTitle(_("Save changes"))
  4885. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4886. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4887. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4888. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4889. msgbox.setDefaultButton(bt_yes)
  4890. msgbox.exec_()
  4891. response = msgbox.clickedButton()
  4892. if response == bt_yes:
  4893. self.on_file_saveprojectas()
  4894. elif response == bt_cancel:
  4895. return
  4896. elif response == bt_no:
  4897. self.on_file_new()
  4898. else:
  4899. self.on_file_new()
  4900. self.inform.emit(_("[success] New Project created..."))
  4901. def on_file_new(self):
  4902. """
  4903. Callback for menu item File->New. Returns the application to its
  4904. startup state. This method is thread-safe.
  4905. :return: None
  4906. """
  4907. self.report_usage("on_file_new")
  4908. # Remove everything from memory
  4909. App.log.debug("on_file_new()")
  4910. if self.call_source != 'app':
  4911. self.editor2object(cleanup=True)
  4912. # ## EDITOR section
  4913. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  4914. self.exc_editor = FlatCAMExcEditor(self)
  4915. self.grb_editor = FlatCAMGrbEditor(self)
  4916. # Clear pool
  4917. self.clear_pool()
  4918. for obj in self.collection.get_list():
  4919. # delete shapes left drawn from mark shape_collections, if any
  4920. if isinstance(obj, FlatCAMGerber):
  4921. try:
  4922. obj.mark_shapes.enabled = False
  4923. obj.mark_shapes.clear(update=True)
  4924. except AttributeError:
  4925. pass
  4926. # also delete annotation shapes, if any
  4927. elif isinstance(obj, FlatCAMCNCjob):
  4928. try:
  4929. obj.annotation.enabled = False
  4930. obj.annotation.clear(update=True)
  4931. except AttributeError:
  4932. pass
  4933. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  4934. self.init_tcl()
  4935. self.delete_selection_shape()
  4936. self.collection.delete_all()
  4937. self.setup_component_editor()
  4938. # Clear project filename
  4939. self.project_filename = None
  4940. # Load the application defaults
  4941. self.load_defaults(filename='current_defaults')
  4942. # Re-fresh project options
  4943. self.on_options_app2project()
  4944. # Init Tools
  4945. self.init_tools()
  4946. # Close any Tabs opened in the Plot Tab Area section
  4947. for index in range(self.ui.plot_tab_area.count()):
  4948. self.ui.plot_tab_area.closeTab(index)
  4949. # for whatever reason previous command does not close the last tab so I do it manually
  4950. self.ui.plot_tab_area.closeTab(0)
  4951. # # And then add again the Plot Area
  4952. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4953. self.ui.plot_tab_area.protectTab(0)
  4954. # take the focus of the Notebook on Project Tab.
  4955. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4956. def obj_properties(self):
  4957. self.report_usage("obj_properties()")
  4958. self.properties_tool.run(toggle=False)
  4959. def on_project_context_save(self):
  4960. obj = self.collection.get_active()
  4961. if type(obj) == FlatCAMGeometry:
  4962. self.on_file_exportdxf()
  4963. elif type(obj) == FlatCAMExcellon:
  4964. self.on_file_saveexcellon()
  4965. elif type(obj) == FlatCAMCNCjob:
  4966. obj.on_exportgcode_button_click()
  4967. elif type(obj) == FlatCAMGerber:
  4968. self.on_file_savegerber()
  4969. def obj_move(self):
  4970. self.report_usage("obj_move()")
  4971. self.move_tool.run(toggle=False)
  4972. def on_fileopengerber(self):
  4973. """
  4974. File menu callback for opening a Gerber.
  4975. :return: None
  4976. """
  4977. self.report_usage("on_fileopengerber")
  4978. App.log.debug("on_fileopengerber()")
  4979. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4980. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4981. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  4982. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4983. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4984. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4985. "Allegro Files (*.art);;" \
  4986. "Mentor Files (*.pho *.gdo);;" \
  4987. "All Files (*.*)"
  4988. try:
  4989. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  4990. directory=self.get_last_folder(), filter=_filter_)
  4991. except TypeError:
  4992. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  4993. filenames = [str(filename) for filename in filenames]
  4994. if len(filenames) == 0:
  4995. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  4996. else:
  4997. for filename in filenames:
  4998. if filename != '':
  4999. self.worker_task.emit({'fcn': self.open_gerber,
  5000. 'params': [filename]})
  5001. def on_fileopenexcellon(self):
  5002. """
  5003. File menu callback for opening an Excellon file.
  5004. :return: None
  5005. """
  5006. self.report_usage("on_fileopenexcellon")
  5007. App.log.debug("on_fileopenexcellon()")
  5008. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5009. "All Files (*.*)"
  5010. try:
  5011. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5012. directory=self.get_last_folder(), filter=_filter_)
  5013. except TypeError:
  5014. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5015. filenames = [str(filename) for filename in filenames]
  5016. if len(filenames) == 0:
  5017. self.inform.emit(_("[WARNING_NOTCL] Open Excellon cancelled."))
  5018. else:
  5019. for filename in filenames:
  5020. if filename != '':
  5021. self.worker_task.emit({'fcn': self.open_excellon,
  5022. 'params': [filename]})
  5023. def on_fileopengcode(self):
  5024. """
  5025. File menu call back for opening gcode.
  5026. :return: None
  5027. """
  5028. self.report_usage("on_fileopengcode")
  5029. App.log.debug("on_fileopengcode()")
  5030. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5031. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5032. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  5033. "All Files (*.*)"
  5034. try:
  5035. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5036. directory=self.get_last_folder(), filter=_filter_)
  5037. except TypeError:
  5038. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5039. filenames = [str(filename) for filename in filenames]
  5040. if len(filenames) == 0:
  5041. self.inform.emit(_("[WARNING_NOTCL] Open G-Code cancelled."))
  5042. else:
  5043. for filename in filenames:
  5044. if filename != '':
  5045. self.worker_task.emit({'fcn': self.open_gcode,
  5046. 'params': [filename]})
  5047. def on_file_openproject(self):
  5048. """
  5049. File menu callback for opening a project.
  5050. :return: None
  5051. """
  5052. self.report_usage("on_file_openproject")
  5053. App.log.debug("on_file_openproject()")
  5054. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5055. try:
  5056. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5057. directory=self.get_last_folder(), filter=_filter_)
  5058. except TypeError:
  5059. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter = _filter_)
  5060. # The Qt methods above will return a QString which can cause problems later.
  5061. # So far json.dump() will fail to serialize it.
  5062. # TODO: Improve the serialization methods and remove this fix.
  5063. filename = str(filename)
  5064. if filename == "":
  5065. self.inform.emit(_("[WARNING_NOTCL] Open Project cancelled."))
  5066. else:
  5067. # self.worker_task.emit({'fcn': self.open_project,
  5068. # 'params': [filename]})
  5069. # The above was failing because open_project() is not
  5070. # thread safe. The new_project()
  5071. self.open_project(filename)
  5072. def on_file_openconfig(self):
  5073. """
  5074. File menu callback for opening a config file.
  5075. :return: None
  5076. """
  5077. self.report_usage("on_file_openconfig")
  5078. App.log.debug("on_file_openconfig()")
  5079. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5080. try:
  5081. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5082. directory=self.data_path, filter=_filter_)
  5083. except TypeError:
  5084. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5085. filter = _filter_)
  5086. if filename == "":
  5087. self.inform.emit(_("[WARNING_NOTCL] Open Config cancelled."))
  5088. else:
  5089. self.open_config_file(filename)
  5090. def on_file_exportsvg(self):
  5091. """
  5092. Callback for menu item File->Export SVG.
  5093. :return: None
  5094. """
  5095. self.report_usage("on_file_exportsvg")
  5096. App.log.debug("on_file_exportsvg()")
  5097. obj = self.collection.get_active()
  5098. if obj is None:
  5099. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5100. msg = _("Please Select a Geometry object to export")
  5101. msgbox = QtWidgets.QMessageBox()
  5102. msgbox.setInformativeText(msg)
  5103. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5104. msgbox.setDefaultButton(bt_ok)
  5105. msgbox.exec_()
  5106. return
  5107. # Check for more compatible types and add as required
  5108. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  5109. and not isinstance(obj, FlatCAMExcellon)):
  5110. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  5111. msgbox = QtWidgets.QMessageBox()
  5112. msgbox.setInformativeText(msg)
  5113. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5114. msgbox.setDefaultButton(bt_ok)
  5115. msgbox.exec_()
  5116. return
  5117. name = self.collection.get_active().options["name"]
  5118. filter = "SVG File (*.svg);;All Files (*.*)"
  5119. try:
  5120. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5121. caption=_("Export SVG"),
  5122. directory=self.get_last_save_folder() + '/' + str(name),
  5123. filter=filter)
  5124. except TypeError:
  5125. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=filter)
  5126. filename = str(filename)
  5127. if filename == "":
  5128. self.inform.emit(_("[WARNING_NOTCL] Export SVG cancelled."))
  5129. return
  5130. else:
  5131. self.export_svg(name, filename)
  5132. if self.defaults["global_open_style"] is False:
  5133. self.file_opened.emit("SVG", filename)
  5134. self.file_saved.emit("SVG", filename)
  5135. def on_file_exportpng(self):
  5136. self.report_usage("on_file_exportpng")
  5137. App.log.debug("on_file_exportpng()")
  5138. self.date = str(datetime.today()).rpartition('.')[0]
  5139. self.date = ''.join(c for c in self.date if c not in ':-')
  5140. self.date = self.date.replace(' ', '_')
  5141. image = _screenshot()
  5142. data = np.asarray(image)
  5143. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5144. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  5145. return
  5146. filter_ = "PNG File (*.png);;All Files (*.*)"
  5147. try:
  5148. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5149. caption=_("Export PNG Image"),
  5150. directory=self.get_last_save_folder() + '/png_' + self.date,
  5151. filter=filter_)
  5152. except TypeError:
  5153. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  5154. filename = str(filename)
  5155. if filename == "":
  5156. self.inform.emit(_("Export PNG cancelled."))
  5157. return
  5158. else:
  5159. write_png(filename, data)
  5160. if self.defaults["global_open_style"] is False:
  5161. self.file_opened.emit("png", filename)
  5162. self.file_saved.emit("png", filename)
  5163. def on_file_savegerber(self):
  5164. """
  5165. Callback for menu item File->Export Gerber.
  5166. :return: None
  5167. """
  5168. self.report_usage("on_file_savegerber")
  5169. App.log.debug("on_file_savegerber()")
  5170. obj = self.collection.get_active()
  5171. if obj is None:
  5172. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  5173. return
  5174. # Check for more compatible types and add as required
  5175. if not isinstance(obj, FlatCAMGerber):
  5176. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5177. return
  5178. name = self.collection.get_active().options["name"]
  5179. filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5180. try:
  5181. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5182. caption="Save Gerber source file",
  5183. directory=self.get_last_save_folder() + '/' + name,
  5184. filter=filter)
  5185. except TypeError:
  5186. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=filter)
  5187. filename = str(filename)
  5188. if filename == "":
  5189. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  5190. return
  5191. else:
  5192. self.save_source_file(name, filename)
  5193. if self.defaults["global_open_style"] is False:
  5194. self.file_opened.emit("Gerber", filename)
  5195. self.file_saved.emit("Gerber", filename)
  5196. def on_file_saveexcellon(self):
  5197. """
  5198. Callback for menu item File->Export Gerber.
  5199. :return: None
  5200. """
  5201. self.report_usage("on_file_saveexcellon")
  5202. App.log.debug("on_file_saveexcellon()")
  5203. obj = self.collection.get_active()
  5204. if obj is None:
  5205. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  5206. return
  5207. # Check for more compatible types and add as required
  5208. if not isinstance(obj, FlatCAMExcellon):
  5209. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5210. return
  5211. name = self.collection.get_active().options["name"]
  5212. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5213. try:
  5214. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5215. caption=_("Save Excellon source file"),
  5216. directory=self.get_last_save_folder() + '/' + name,
  5217. filter=filter)
  5218. except TypeError:
  5219. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=filter)
  5220. filename = str(filename)
  5221. if filename == "":
  5222. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  5223. return
  5224. else:
  5225. self.save_source_file(name, filename)
  5226. if self.defaults["global_open_style"] is False:
  5227. self.file_opened.emit("Excellon", filename)
  5228. self.file_saved.emit("Excellon", filename)
  5229. def on_file_exportexcellon(self):
  5230. """
  5231. Callback for menu item File->Export->Excellon.
  5232. :return: None
  5233. """
  5234. self.report_usage("on_file_exportexcellon")
  5235. App.log.debug("on_file_exportexcellon()")
  5236. obj = self.collection.get_active()
  5237. if obj is None:
  5238. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  5239. return
  5240. # Check for more compatible types and add as required
  5241. if not isinstance(obj, FlatCAMExcellon):
  5242. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5243. return
  5244. name = self.collection.get_active().options["name"]
  5245. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5246. try:
  5247. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5248. caption=_("Export Excellon"),
  5249. directory=self.get_last_save_folder() + '/' + name,
  5250. filter=filter)
  5251. except TypeError:
  5252. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=filter)
  5253. filename = str(filename)
  5254. if filename == "":
  5255. self.inform.emit(_("[WARNING_NOTCL] Export Excellon cancelled."))
  5256. return
  5257. else:
  5258. self.export_excellon(name, filename)
  5259. if self.defaults["global_open_style"] is False:
  5260. self.file_opened.emit("Excellon", filename)
  5261. self.file_saved.emit("Excellon", filename)
  5262. def on_file_exportgerber(self):
  5263. """
  5264. Callback for menu item File->Export->Gerber.
  5265. :return: None
  5266. """
  5267. self.report_usage("on_file_exportgerber")
  5268. App.log.debug("on_file_exportgerber()")
  5269. obj = self.collection.get_active()
  5270. if obj is None:
  5271. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Gerber object to export."))
  5272. return
  5273. # Check for more compatible types and add as required
  5274. if not isinstance(obj, FlatCAMGerber):
  5275. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5276. return
  5277. name = self.collection.get_active().options["name"]
  5278. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  5279. try:
  5280. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5281. caption=_("Export Gerber"),
  5282. directory=self.get_last_save_folder() + '/' + name,
  5283. filter=_filter_)
  5284. except TypeError:
  5285. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  5286. filename = str(filename)
  5287. if filename == "":
  5288. self.inform.emit(_("[WARNING_NOTCL] Export Gerber cancelled."))
  5289. return
  5290. else:
  5291. self.export_gerber(name, filename)
  5292. if self.defaults["global_open_style"] is False:
  5293. self.file_opened.emit("Gerber", filename)
  5294. self.file_saved.emit("Gerber", filename)
  5295. def on_file_exportdxf(self):
  5296. """
  5297. Callback for menu item File->Export DXF.
  5298. :return: None
  5299. """
  5300. self.report_usage("on_file_exportdxf")
  5301. App.log.debug("on_file_exportdxf()")
  5302. obj = self.collection.get_active()
  5303. if obj is None:
  5304. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5305. msg = _("Please Select a Geometry object to export")
  5306. msgbox = QtWidgets.QMessageBox()
  5307. msgbox.setInformativeText(msg)
  5308. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5309. msgbox.setDefaultButton(bt_ok)
  5310. msgbox.exec_()
  5311. return
  5312. # Check for more compatible types and add as required
  5313. if not isinstance(obj, FlatCAMGeometry):
  5314. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  5315. msgbox = QtWidgets.QMessageBox()
  5316. msgbox.setInformativeText(msg)
  5317. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5318. msgbox.setDefaultButton(bt_ok)
  5319. msgbox.exec_()
  5320. return
  5321. name = self.collection.get_active().options["name"]
  5322. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  5323. try:
  5324. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5325. caption=_("Export DXF"),
  5326. directory=self.get_last_save_folder() + '/' + name,
  5327. filter=_filter_)
  5328. except TypeError:
  5329. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  5330. filter=_filter_)
  5331. filename = str(filename)
  5332. if filename == "":
  5333. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  5334. return
  5335. else:
  5336. self.export_dxf(name, filename)
  5337. if self.defaults["global_open_style"] is False:
  5338. self.file_opened.emit("DXF", filename)
  5339. self.file_saved.emit("DXF", filename)
  5340. def on_file_importsvg(self, type_of_obj):
  5341. """
  5342. Callback for menu item File->Import SVG.
  5343. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5344. :type type_of_obj: str
  5345. :return: None
  5346. """
  5347. self.report_usage("on_file_importsvg")
  5348. App.log.debug("on_file_importsvg()")
  5349. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  5350. try:
  5351. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5352. directory=self.get_last_folder(), filter=_filter_)
  5353. except TypeError:
  5354. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5355. filter=_filter_)
  5356. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5357. type_of_obj = "geometry"
  5358. filenames = [str(filename) for filename in filenames]
  5359. if len(filenames) == 0:
  5360. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  5361. else:
  5362. for filename in filenames:
  5363. if filename != '':
  5364. self.worker_task.emit({'fcn': self.import_svg,
  5365. 'params': [filename, type_of_obj]})
  5366. def on_file_importdxf(self, type_of_obj):
  5367. """
  5368. Callback for menu item File->Import DXF.
  5369. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5370. :type type_of_obj: str
  5371. :return: None
  5372. """
  5373. self.report_usage("on_file_importdxf")
  5374. App.log.debug("on_file_importdxf()")
  5375. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  5376. try:
  5377. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5378. directory=self.get_last_folder(),
  5379. filter=_filter_)
  5380. except TypeError:
  5381. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5382. filter=_filter_)
  5383. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5384. type_of_obj = "geometry"
  5385. filenames = [str(filename) for filename in filenames]
  5386. if len(filenames) == 0:
  5387. self.inform.emit(_("[WARNING_NOTCL] Open DXF cancelled."))
  5388. else:
  5389. for filename in filenames:
  5390. if filename != '':
  5391. self.worker_task.emit({'fcn': self.import_dxf,
  5392. 'params': [filename, type_of_obj]})
  5393. # ################################################################################################################ ##
  5394. # # ## The following section has the functions that are displayed and call the Editor tab CNCJob Tab ############### ##
  5395. # ################################################################################################################ ##
  5396. def init_code_editor(self, name):
  5397. # Signals section
  5398. # Disconnect the old signals
  5399. self.ui.buttonOpen.clicked.disconnect()
  5400. self.ui.buttonSave.clicked.disconnect()
  5401. # add the tab if it was closed
  5402. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  5403. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  5404. # delete the absolute and relative position and messages in the infobar
  5405. self.ui.position_label.setText("")
  5406. self.ui.rel_position_label.setText("")
  5407. # first clear previous text in text editor (if any)
  5408. self.ui.code_editor.clear()
  5409. self.ui.code_editor.setReadOnly(False)
  5410. self.toggle_codeeditor = True
  5411. self.ui.code_editor.completer_enable = False
  5412. # Switch plot_area to CNCJob tab
  5413. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5414. def on_view_source(self):
  5415. try:
  5416. obj = self.collection.get_active()
  5417. except:
  5418. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  5419. return 'fail'
  5420. # then append the text from GCode to the text editor
  5421. try:
  5422. file = StringIO(obj.source_file)
  5423. except AttributeError:
  5424. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  5425. return 'fail'
  5426. if obj.kind == 'gerber':
  5427. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  5428. elif obj.kind == 'excellon':
  5429. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  5430. self.init_code_editor(name=_("Source Editor"))
  5431. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5432. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5433. try:
  5434. for line in file:
  5435. proc_line = str(line).strip('\n')
  5436. self.ui.code_editor.append(proc_line)
  5437. except Exception as e:
  5438. log.debug('App.on_view_source() -->%s' % str(e))
  5439. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  5440. return
  5441. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5442. self.handleTextChanged()
  5443. self.ui.show()
  5444. def on_toggle_code_editor(self):
  5445. self.report_usage("on_toggle_code_editor()")
  5446. if self.toggle_codeeditor is False:
  5447. self.init_code_editor(name=_("Code Editor"))
  5448. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  5449. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  5450. else:
  5451. for idx in range(self.ui.plot_tab_area.count()):
  5452. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  5453. self.ui.plot_tab_area.closeTab(idx)
  5454. break
  5455. self.toggle_codeeditor = False
  5456. def on_filenewscript(self):
  5457. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5458. self.init_code_editor(name=_("Script Editor"))
  5459. self.ui.code_editor.completer_enable = True
  5460. self.ui.code_editor.append(_(
  5461. "#\n"
  5462. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  5463. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  5464. "#\n\n"
  5465. "# FlatCAM commands list:\n"
  5466. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  5467. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  5468. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  5469. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  5470. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  5471. "# WriteGCode\n"
  5472. "#\n\n"
  5473. ))
  5474. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5475. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5476. self.handleTextChanged()
  5477. self.ui.code_editor.show()
  5478. def on_fileopenscript(self):
  5479. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5480. try:
  5481. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  5482. directory=self.get_last_folder(), filter=_filter_)
  5483. except TypeError:
  5484. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  5485. # The Qt methods above will return a QString which can cause problems later.
  5486. # So far json.dump() will fail to serialize it.
  5487. # TODO: Improve the serialization methods and remove this fix.
  5488. filename = str(filename)
  5489. if filename == "":
  5490. self.inform.emit(_("[WARNING_NOTCL] Open TCL script cancelled."))
  5491. else:
  5492. self.on_filenewscript()
  5493. try:
  5494. with open(filename, "r") as opened_script:
  5495. try:
  5496. for line in opened_script:
  5497. proc_line = str(line).strip('\n')
  5498. self.ui.code_editor.append(proc_line)
  5499. except Exception as e:
  5500. log.debug('App.on_fileopenscript() -->%s' % str(e))
  5501. self.inform.emit(_('[ERROR]App.on_fileopenscript() -->%s') % str(e))
  5502. return
  5503. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5504. self.handleTextChanged()
  5505. self.ui.show()
  5506. except Exception as e:
  5507. log.debug("App.on_fileopenscript() -> %s" % str(e))
  5508. def on_filerunscript(self, name=None):
  5509. """
  5510. File menu callback for loading and running a TCL script.
  5511. :return: None
  5512. """
  5513. self.report_usage("on_filerunscript")
  5514. App.log.debug("on_file_runscript()")
  5515. if name:
  5516. filename = name
  5517. else:
  5518. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5519. try:
  5520. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  5521. directory=self.get_last_folder(), filter=_filter_)
  5522. except TypeError:
  5523. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  5524. # The Qt methods above will return a QString which can cause problems later.
  5525. # So far json.dump() will fail to serialize it.
  5526. # TODO: Improve the serialization methods and remove this fix.
  5527. filename = str(filename)
  5528. if filename == "":
  5529. self.inform.emit(_("[WARNING_NOTCL] Run TCL script cancelled."))
  5530. else:
  5531. try:
  5532. with open(filename, "r") as tcl_script:
  5533. cmd_line_shellfile_content = tcl_script.read()
  5534. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  5535. except Exception as e:
  5536. log.debug("App.on_filerunscript() -> %s" % str(e))
  5537. sys.exit(2)
  5538. def on_file_saveproject(self):
  5539. """
  5540. Callback for menu item File->Save Project. Saves the project to
  5541. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  5542. if set to None. The project is saved by calling ``self.save_project()``.
  5543. :return: None
  5544. """
  5545. self.report_usage("on_file_saveproject")
  5546. if self.project_filename is None:
  5547. self.on_file_saveprojectas()
  5548. else:
  5549. self.worker_task.emit({'fcn': self.save_project,
  5550. 'params': [self.project_filename]})
  5551. if self.defaults["global_open_style"] is False:
  5552. self.file_opened.emit("project", self.project_filename)
  5553. self.file_saved.emit("project", self.project_filename)
  5554. self.should_we_save = False
  5555. def on_file_saveprojectas(self, make_copy=False, thread=True, quit=False):
  5556. """
  5557. Callback for menu item File->Save Project As... Opens a file
  5558. chooser and saves the project to the given file via
  5559. ``self.save_project()``.
  5560. :return: None
  5561. """
  5562. self.report_usage("on_file_saveprojectas")
  5563. self.date = str(datetime.today()).rpartition('.')[0]
  5564. self.date = ''.join(c for c in self.date if c not in ':-')
  5565. self.date = self.date.replace(' ', '_')
  5566. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  5567. try:
  5568. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5569. caption=_("Save Project As ..."),
  5570. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  5571. filter=filter_)
  5572. except TypeError:
  5573. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  5574. filename = str(filename)
  5575. if filename == '':
  5576. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  5577. return
  5578. try:
  5579. f = open(filename, 'r')
  5580. f.close()
  5581. except IOError:
  5582. pass
  5583. if thread is True:
  5584. self.worker_task.emit({'fcn': self.save_project,
  5585. 'params': [filename, quit]})
  5586. else:
  5587. self.save_project(filename, quit)
  5588. # self.save_project(filename)
  5589. if self.defaults["global_open_style"] is False:
  5590. self.file_opened.emit("project", filename)
  5591. self.file_saved.emit("project", filename)
  5592. if not make_copy:
  5593. self.project_filename = filename
  5594. self.should_we_save = False
  5595. def export_svg(self, obj_name, filename, scale_factor=0.00):
  5596. """
  5597. Exports a Geometry Object to an SVG file.
  5598. :param filename: Path to the SVG file to save to.
  5599. :return:
  5600. """
  5601. self.report_usage("export_svg()")
  5602. if filename is None:
  5603. filename = self.defaults["global_last_save_folder"]
  5604. self.log.debug("export_svg()")
  5605. try:
  5606. obj = self.collection.get_by_name(str(obj_name))
  5607. except:
  5608. # TODO: The return behavior has not been established... should raise exception?
  5609. return "Could not retrieve object: %s" % obj_name
  5610. with self.proc_container.new(_("Exporting SVG")) as proc:
  5611. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5612. # Determine bounding area for svg export
  5613. bounds = obj.bounds()
  5614. size = obj.size()
  5615. # Convert everything to strings for use in the xml doc
  5616. svgwidth = str(size[0])
  5617. svgheight = str(size[1])
  5618. minx = str(bounds[0])
  5619. miny = str(bounds[1] - size[1])
  5620. uom = obj.units.lower()
  5621. # Add a SVG Header and footer to the svg output from shapely
  5622. # The transform flips the Y Axis so that everything renders
  5623. # properly within svg apps such as inkscape
  5624. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5625. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5626. svg_header += 'width="' + svgwidth + uom + '" '
  5627. svg_header += 'height="' + svgheight + uom + '" '
  5628. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  5629. svg_header += '<g transform="scale(1,-1)">'
  5630. svg_footer = '</g> </svg>'
  5631. svg_elem = svg_header + exported_svg + svg_footer
  5632. # Parse the xml through a xml parser just to add line feeds
  5633. # and to make it look more pretty for the output
  5634. svgcode = parse_xml_string(svg_elem)
  5635. with open(filename, 'w') as fp:
  5636. fp.write(svgcode.toprettyxml())
  5637. if self.defaults["global_open_style"] is False:
  5638. self.file_opened.emit("SVG", filename)
  5639. self.file_saved.emit("SVG", filename)
  5640. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5641. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  5642. """
  5643. Exports a Geometry Object to an SVG file in negative.
  5644. :param filename: Path to the SVG file to save to.
  5645. :param: use_thread: If True use threads
  5646. :type: Bool
  5647. :return:
  5648. """
  5649. self.report_usage("export_negative()")
  5650. if filename is None:
  5651. filename = self.defaults["global_last_save_folder"]
  5652. self.log.debug("export_svg() negative")
  5653. try:
  5654. obj = self.collection.get_by_name(str(obj_name))
  5655. except:
  5656. # TODO: The return behavior has not been established... should raise exception?
  5657. return "Could not retrieve object: %s" % obj_name
  5658. try:
  5659. box = self.collection.get_by_name(str(box_name))
  5660. except:
  5661. # TODO: The return behavior has not been established... should raise exception?
  5662. return "Could not retrieve object: %s" % box_name
  5663. if box is None:
  5664. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5665. box = obj
  5666. def make_negative_film():
  5667. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5668. self.progress.emit(40)
  5669. # Determine bounding area for svg export
  5670. bounds = box.bounds()
  5671. size = box.size()
  5672. uom = obj.units.lower()
  5673. # Convert everything to strings for use in the xml doc
  5674. svgwidth = str(size[0] + (2 * boundary))
  5675. svgheight = str(size[1] + (2 * boundary))
  5676. minx = str(bounds[0] - boundary)
  5677. miny = str(bounds[1] + boundary + size[1])
  5678. miny_rect = str(bounds[1] - boundary)
  5679. # Add a SVG Header and footer to the svg output from shapely
  5680. # The transform flips the Y Axis so that everything renders
  5681. # properly within svg apps such as inkscape
  5682. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5683. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5684. svg_header += 'width="' + svgwidth + uom + '" '
  5685. svg_header += 'height="' + svgheight + uom + '" '
  5686. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5687. svg_header += '>'
  5688. svg_header += '<g transform="scale(1,-1)">'
  5689. svg_footer = '</g> </svg>'
  5690. self.progress.emit(60)
  5691. # Change the attributes of the exported SVG
  5692. # We don't need stroke-width - wrong, we do when we have lines with certain width
  5693. # We set opacity to maximum
  5694. # We set the color to WHITE
  5695. root = ET.fromstring(exported_svg)
  5696. for child in root:
  5697. child.set('fill', '#FFFFFF')
  5698. child.set('opacity', '1.0')
  5699. child.set('stroke', '#FFFFFF')
  5700. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  5701. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  5702. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  5703. first_svg_elem_tag = 'rect'
  5704. first_svg_elem_attribs = {
  5705. 'x': minx,
  5706. 'y': miny_rect,
  5707. 'width': svgwidth,
  5708. 'height': svgheight,
  5709. 'id': 'neg_rect',
  5710. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  5711. }
  5712. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  5713. exported_svg = ET.tostring(root)
  5714. svg_elem = svg_header + str(exported_svg) + svg_footer
  5715. self.progress.emit(80)
  5716. # Parse the xml through a xml parser just to add line feeds
  5717. # and to make it look more pretty for the output
  5718. doc = parse_xml_string(svg_elem)
  5719. with open(filename, 'w') as fp:
  5720. fp.write(doc.toprettyxml())
  5721. self.progress.emit(100)
  5722. if self.defaults["global_open_style"] is False:
  5723. self.file_opened.emit("SVG", filename)
  5724. self.file_saved.emit("SVG", filename)
  5725. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5726. if use_thread is True:
  5727. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5728. def job_thread_film(app_obj):
  5729. try:
  5730. make_negative_film()
  5731. except Exception as e:
  5732. proc.done()
  5733. return
  5734. proc.done()
  5735. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5736. else:
  5737. make_negative_film()
  5738. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  5739. """
  5740. Exports a Geometry Object to an SVG file in negative.
  5741. :param filename: Path to the SVG file to save to.
  5742. :param: use_thread: If True use threads
  5743. :type: Bool
  5744. :return:
  5745. """
  5746. self.report_usage("export_svg_black()")
  5747. if filename is None:
  5748. filename = self.defaults["global_last_save_folder"]
  5749. self.log.debug("export_svg() black")
  5750. try:
  5751. obj = self.collection.get_by_name(str(obj_name))
  5752. except:
  5753. # TODO: The return behavior has not been established... should raise exception?
  5754. return "Could not retrieve object: %s" % obj_name
  5755. try:
  5756. box = self.collection.get_by_name(str(box_name))
  5757. except:
  5758. # TODO: The return behavior has not been established... should raise exception?
  5759. return "Could not retrieve object: %s" % box_name
  5760. if box is None:
  5761. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5762. box = obj
  5763. def make_black_film():
  5764. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5765. self.progress.emit(40)
  5766. # Change the attributes of the exported SVG
  5767. # We don't need stroke-width
  5768. # We set opacity to maximum
  5769. # We set the colour to WHITE
  5770. root = ET.fromstring(exported_svg)
  5771. for child in root:
  5772. child.set('fill', '#000000')
  5773. child.set('opacity', '1.0')
  5774. child.set('stroke', '#000000')
  5775. exported_svg = ET.tostring(root)
  5776. # Determine bounding area for svg export
  5777. bounds = box.bounds()
  5778. size = box.size()
  5779. # This contain the measure units
  5780. uom = obj.units.lower()
  5781. # Define a boundary around SVG of about 1.0mm (~39mils)
  5782. if uom in "mm":
  5783. boundary = 1.0
  5784. else:
  5785. boundary = 0.0393701
  5786. self.progress.emit(80)
  5787. # Convert everything to strings for use in the xml doc
  5788. svgwidth = str(size[0] + (2 * boundary))
  5789. svgheight = str(size[1] + (2 * boundary))
  5790. minx = str(bounds[0] - boundary)
  5791. miny = str(bounds[1] + boundary + size[1])
  5792. self.log.debug(minx)
  5793. self.log.debug(miny)
  5794. # Add a SVG Header and footer to the svg output from shapely
  5795. # The transform flips the Y Axis so that everything renders
  5796. # properly within svg apps such as inkscape
  5797. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5798. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5799. svg_header += 'width="' + svgwidth + uom + '" '
  5800. svg_header += 'height="' + svgheight + uom + '" '
  5801. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5802. svg_header += '>'
  5803. svg_header += '<g transform="scale(1,-1)">'
  5804. svg_footer = '</g> </svg>'
  5805. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  5806. self.progress.emit(90)
  5807. # Parse the xml through a xml parser just to add line feeds
  5808. # and to make it look more pretty for the output
  5809. doc = parse_xml_string(svg_elem)
  5810. with open(filename, 'w') as fp:
  5811. fp.write(doc.toprettyxml())
  5812. self.progress.emit(100)
  5813. if self.defaults["global_open_style"] is False:
  5814. self.file_opened.emit("SVG", filename)
  5815. self.file_saved.emit("SVG", filename)
  5816. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5817. if use_thread is True:
  5818. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5819. def job_thread_film(app_obj):
  5820. try:
  5821. make_black_film()
  5822. except Exception as e:
  5823. proc.done()
  5824. return
  5825. proc.done()
  5826. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5827. else:
  5828. make_black_film()
  5829. def save_source_file(self, obj_name, filename, use_thread=True):
  5830. """
  5831. Exports a Gerber Object to an Gerber file.
  5832. :param filename: Path to the Gerber file to save to.
  5833. :return:
  5834. """
  5835. self.report_usage("save source file()")
  5836. if filename is None:
  5837. filename = self.defaults["global_last_save_folder"]
  5838. self.log.debug("save source file()")
  5839. obj = self.collection.get_by_name(obj_name)
  5840. file_string = StringIO(obj.source_file)
  5841. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5842. with open(filename, 'w') as file:
  5843. file.writelines('G04*\n')
  5844. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  5845. (obj.kind.upper(), str(self.version), str(self.version_date)))
  5846. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  5847. file.writelines('G04 Created on : %s*\n' % time_string)
  5848. for line in file_string:
  5849. file.writelines(line)
  5850. def export_excellon(self, obj_name, filename, use_thread=True):
  5851. """
  5852. Exports a Excellon Object to an Excellon file.
  5853. :param filename: Path to the Excellon file to save to.
  5854. :return:
  5855. """
  5856. self.report_usage("export_excellon()")
  5857. if filename is None:
  5858. filename = self.defaults["global_last_save_folder"]
  5859. self.log.debug("export_excellon()")
  5860. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  5861. self.defaults["excellon_exp_decimals"]
  5862. )
  5863. units = ''
  5864. try:
  5865. obj = self.collection.get_by_name(str(obj_name))
  5866. except:
  5867. # TODO: The return behavior has not been established... should raise exception?
  5868. return "Could not retrieve object: %s" % obj_name
  5869. # updated units
  5870. eunits = self.defaults["excellon_exp_units"]
  5871. ewhole = self.defaults["excellon_exp_integer"]
  5872. efract = self.defaults["excellon_exp_decimals"]
  5873. ezeros = self.defaults["excellon_exp_zeros"]
  5874. eformat = self.defaults[ "excellon_exp_format"]
  5875. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5876. if fc_units == 'MM':
  5877. factor = 1 if eunits == 'METRIC' else 0.03937
  5878. else:
  5879. factor = 25.4 if eunits == 'METRIC' else 1
  5880. def make_excellon():
  5881. try:
  5882. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5883. header = 'M48\n'
  5884. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5885. (str(self.version), str(self.version_date))
  5886. header += ';Filename: %s' % str(obj_name) + '\n'
  5887. header += ';Created on : %s' % time_str + '\n'
  5888. if eformat == 'dec':
  5889. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  5890. header += eunits + '\n'
  5891. for tool in obj.tools:
  5892. if eunits == 'METRIC':
  5893. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5894. tool=str(tool),
  5895. dec=2)
  5896. else:
  5897. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5898. tool=str(tool),
  5899. dec=4)
  5900. else:
  5901. if ezeros == 'LZ':
  5902. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5903. form='ndec', e_zeros='LZ', factor=factor)
  5904. header += '%s,%s\n' % (eunits, 'LZ')
  5905. header += format_exc
  5906. for tool in obj.tools:
  5907. if eunits == 'METRIC':
  5908. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5909. tool=str(tool),
  5910. dec=2)
  5911. else:
  5912. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5913. tool=str(tool),
  5914. dec=4)
  5915. else:
  5916. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5917. form='ndec', e_zeros='TZ', factor=factor)
  5918. header += '%s,%s\n' % (eunits, 'TZ')
  5919. header += format_exc
  5920. for tool in obj.tools:
  5921. if eunits == 'METRIC':
  5922. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5923. tool=str(tool),
  5924. dec=2)
  5925. else:
  5926. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5927. tool=str(tool),
  5928. dec=4)
  5929. header += '%\n'
  5930. footer = 'M30\n'
  5931. exported_excellon = header
  5932. exported_excellon += excellon_code
  5933. exported_excellon += footer
  5934. with open(filename, 'w') as fp:
  5935. fp.write(exported_excellon)
  5936. if self.defaults["global_open_style"] is False:
  5937. self.file_opened.emit("Excellon", filename)
  5938. self.file_saved.emit("Excellon", filename)
  5939. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  5940. except Exception as e:
  5941. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  5942. return 'fail'
  5943. if use_thread is True:
  5944. with self.proc_container.new(_("Exporting Excellon")) as proc:
  5945. def job_thread_exc(app_obj):
  5946. ret = make_excellon()
  5947. if ret == 'fail':
  5948. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5949. return
  5950. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5951. else:
  5952. ret = make_excellon()
  5953. if ret == 'fail':
  5954. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5955. return
  5956. def export_gerber(self, obj_name, filename, use_thread=True):
  5957. """
  5958. Exports a Gerber Object to an Gerber file.
  5959. :param filename: Path to the Gerber file to save to.
  5960. :return:
  5961. """
  5962. self.report_usage("export_gerber()")
  5963. if filename is None:
  5964. filename = self.defaults["global_last_save_folder"]
  5965. self.log.debug("export_gerber()")
  5966. try:
  5967. obj = self.collection.get_by_name(str(obj_name))
  5968. except:
  5969. # TODO: The return behavior has not been established... should raise exception?
  5970. return "Could not retrieve object: %s" % obj_name
  5971. # updated units
  5972. gunits = self.defaults["gerber_exp_units"]
  5973. gwhole = self.defaults["gerber_exp_integer"]
  5974. gfract = self.defaults["gerber_exp_decimals"]
  5975. gzeros = self.defaults["gerber_exp_zeros"]
  5976. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5977. if fc_units == 'MM':
  5978. factor = 1 if gunits == 'MM' else 0.03937
  5979. else:
  5980. factor = 25.4 if gunits == 'MM' else 1
  5981. def make_gerber():
  5982. try:
  5983. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5984. header = 'G04*\n'
  5985. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  5986. (str(self.version), str(self.version_date))
  5987. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  5988. header += 'G04 Created on : %s*' % time_str + '\n'
  5989. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  5990. header += "%MO{units}*%\n".format(units=gunits)
  5991. for apid in obj.apertures:
  5992. if obj.apertures[apid]['type'] == 'C':
  5993. header += "%ADD{apid}{type},{size}*%\n".format(
  5994. apid=str(apid),
  5995. type='C',
  5996. size=(factor * obj.apertures[apid]['size'])
  5997. )
  5998. elif obj.apertures[apid]['type'] == 'R':
  5999. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6000. apid=str(apid),
  6001. type='R',
  6002. width=(factor * obj.apertures[apid]['width']),
  6003. height=(factor * obj.apertures[apid]['height'])
  6004. )
  6005. elif obj.apertures[apid]['type'] == 'O':
  6006. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6007. apid=str(apid),
  6008. type='O',
  6009. width=(factor * obj.apertures[apid]['width']),
  6010. height=(factor * obj.apertures[apid]['height'])
  6011. )
  6012. header += '\n'
  6013. # obsolete units but some software may need it
  6014. if gunits == 'IN':
  6015. header += 'G70*\n'
  6016. else:
  6017. header += 'G71*\n'
  6018. # Absolute Mode
  6019. header += 'G90*\n'
  6020. header += 'G01*\n'
  6021. # positive polarity
  6022. header += '%LPD*%\n'
  6023. footer = 'M02*\n'
  6024. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6025. exported_gerber = header
  6026. exported_gerber += gerber_code
  6027. exported_gerber += footer
  6028. with open(filename, 'w') as fp:
  6029. fp.write(exported_gerber)
  6030. if self.defaults["global_open_style"] is False:
  6031. self.file_opened.emit("Gerber", filename)
  6032. self.file_saved.emit("Gerber", filename)
  6033. self.inform.emit(_("[success] Gerber file exported to %s") % filename)
  6034. except Exception as e:
  6035. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6036. return 'fail'
  6037. if use_thread is True:
  6038. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6039. def job_thread_exc(app_obj):
  6040. ret = make_gerber()
  6041. if ret == 'fail':
  6042. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  6043. return
  6044. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6045. else:
  6046. ret = make_gerber()
  6047. if ret == 'fail':
  6048. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  6049. return
  6050. def export_dxf(self, obj_name, filename, use_thread=True):
  6051. """
  6052. Exports a Geometry Object to an DXF file.
  6053. :param filename: Path to the DXF file to save to.
  6054. :return:
  6055. """
  6056. self.report_usage("export_dxf()")
  6057. if filename is None:
  6058. filename = self.defaults["global_last_save_folder"]
  6059. self.log.debug("export_dxf()")
  6060. format_exc = ''
  6061. units = ''
  6062. try:
  6063. obj = self.collection.get_by_name(str(obj_name))
  6064. except:
  6065. # TODO: The return behavior has not been established... should raise exception?
  6066. return "Could not retrieve object: %s" % obj_name
  6067. # updated units
  6068. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6069. if units == 'IN' or units == 'INCH':
  6070. units = 'INCH'
  6071. elif units == 'MM' or units == 'METIRC':
  6072. units ='METRIC'
  6073. def make_dxf():
  6074. try:
  6075. dxf_code = obj.export_dxf()
  6076. dxf_code.saveas(filename)
  6077. if self.defaults["global_open_style"] is False:
  6078. self.file_opened.emit("DXF", filename)
  6079. self.file_saved.emit("DXF", filename)
  6080. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  6081. except:
  6082. return 'fail'
  6083. if use_thread is True:
  6084. with self.proc_container.new(_("Exporting DXF")) as proc:
  6085. def job_thread_exc(app_obj):
  6086. ret = make_dxf()
  6087. if ret == 'fail':
  6088. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  6089. return
  6090. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6091. else:
  6092. ret = make_dxf()
  6093. if ret == 'fail':
  6094. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  6095. return
  6096. def import_svg(self, filename, geo_type='geometry', outname=None):
  6097. """
  6098. Adds a new Geometry Object to the projects and populates
  6099. it with shapes extracted from the SVG file.
  6100. :param filename: Path to the SVG file.
  6101. :param outname:
  6102. :return:
  6103. """
  6104. self.report_usage("import_svg()")
  6105. obj_type = ""
  6106. if geo_type is None or geo_type == "geometry":
  6107. obj_type = "geometry"
  6108. elif geo_type == "gerber":
  6109. obj_type = geo_type
  6110. else:
  6111. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6112. "Only Geometry and Gerber are supported"))
  6113. return
  6114. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6115. def obj_init(geo_obj, app_obj):
  6116. geo_obj.import_svg(filename, obj_type, units=units)
  6117. geo_obj.multigeo = False
  6118. with self.proc_container.new(_("Importing SVG")) as proc:
  6119. # Object name
  6120. name = outname or filename.split('/')[-1].split('\\')[-1]
  6121. self.new_object(obj_type, name, obj_init, autoselected=False)
  6122. self.progress.emit(20)
  6123. # Register recent file
  6124. self.file_opened.emit("svg", filename)
  6125. # GUI feedback
  6126. self.inform.emit(_("[success] Opened: %s") % filename)
  6127. self.progress.emit(100)
  6128. def import_dxf(self, filename, geo_type='geometry', outname=None):
  6129. """
  6130. Adds a new Geometry Object to the projects and populates
  6131. it with shapes extracted from the DXF file.
  6132. :param filename: Path to the DXF file.
  6133. :param outname:
  6134. :type putname: str
  6135. :return:
  6136. """
  6137. self.report_usage("import_dxf()")
  6138. obj_type = ""
  6139. if geo_type is None or geo_type == "geometry":
  6140. obj_type = "geometry"
  6141. elif geo_type == "gerber":
  6142. obj_type = geo_type
  6143. else:
  6144. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6145. "Only Geometry and Gerber are supported"))
  6146. return
  6147. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6148. def obj_init(geo_obj, app_obj):
  6149. geo_obj.import_dxf(filename, obj_type, units=units)
  6150. geo_obj.multigeo = False
  6151. with self.proc_container.new(_("Importing DXF")) as proc:
  6152. # Object name
  6153. name = outname or filename.split('/')[-1].split('\\')[-1]
  6154. self.new_object(obj_type, name, obj_init, autoselected=False)
  6155. self.progress.emit(20)
  6156. # Register recent file
  6157. self.file_opened.emit("dxf", filename)
  6158. # GUI feedback
  6159. self.inform.emit(_("[success] Opened: %s") % filename)
  6160. self.progress.emit(100)
  6161. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  6162. """
  6163. Adds a new Geometry Object to the projects and populates
  6164. it with shapes extracted from the SVG file.
  6165. :param filename: Path to the SVG file.
  6166. :param o_type: type of FlatCAM objeect
  6167. :param dpi: dot per inch
  6168. :param mode: black or color
  6169. :param mask: dictate the level of detail
  6170. :param outname: name for the resulting file
  6171. :return:
  6172. """
  6173. self.report_usage("import_image()")
  6174. if o_type is None or o_type == "geometry":
  6175. obj_type = "geometry"
  6176. elif o_type == "gerber":
  6177. obj_type = o_type
  6178. else:
  6179. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6180. "Only Geometry and Gerber are supported"))
  6181. return
  6182. def obj_init(geo_obj, app_obj):
  6183. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  6184. geo_obj.multigeo = False
  6185. with self.proc_container.new(_("Importing Image")) as proc:
  6186. # Object name
  6187. name = outname or filename.split('/')[-1].split('\\')[-1]
  6188. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  6189. self.new_object(obj_type, name, obj_init)
  6190. self.progress.emit(20)
  6191. # Register recent file
  6192. self.file_opened.emit("image", filename)
  6193. # GUI feedback
  6194. self.inform.emit(_("[success] Opened: %s") % filename)
  6195. self.progress.emit(100)
  6196. def open_gerber(self, filename, outname=None):
  6197. """
  6198. Opens a Gerber file, parses it and creates a new object for
  6199. it in the program. Thread-safe.
  6200. :param outname: Name of the resulting object. None causes the
  6201. name to be that of the file.
  6202. :param filename: Gerber file filename
  6203. :type filename: str
  6204. :param follow: If true, the parser will not create polygons, just lines
  6205. following the gerber path.
  6206. :type follow: bool
  6207. :return: None
  6208. """
  6209. # How the object should be initialized
  6210. def obj_init(gerber_obj, app_obj):
  6211. assert isinstance(gerber_obj, FlatCAMGerber), \
  6212. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  6213. # Opening the file happens here
  6214. self.progress.emit(30)
  6215. try:
  6216. gerber_obj.parse_file(filename)
  6217. except IOError:
  6218. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  6219. app_obj.progress.emit(0)
  6220. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  6221. return "fail"
  6222. except ParseError as err:
  6223. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: {name}. {error}").format(name=filename,
  6224. error=str(err)))
  6225. app_obj.progress.emit(0)
  6226. self.log.error(str(err))
  6227. return "fail"
  6228. except:
  6229. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  6230. msg += traceback.format_exc()
  6231. app_obj.inform.emit(msg)
  6232. return "fail"
  6233. if gerber_obj.is_empty():
  6234. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  6235. # self.collection.set_active(gerber_obj.options["name"])
  6236. # self.collection.delete_active()
  6237. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  6238. return "fail"
  6239. # Further parsing
  6240. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  6241. App.log.debug("open_gerber()")
  6242. with self.proc_container.new(_("Opening Gerber")) as proc:
  6243. self.progress.emit(10)
  6244. # Object name
  6245. name = outname or filename.split('/')[-1].split('\\')[-1]
  6246. # # ## Object creation # ##
  6247. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  6248. if ret == 'fail':
  6249. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  6250. return
  6251. # Register recent file
  6252. self.file_opened.emit("gerber", filename)
  6253. self.progress.emit(100)
  6254. # GUI feedback
  6255. self.inform.emit(_("[success] Opened: %s") % filename)
  6256. def open_excellon(self, filename, outname=None):
  6257. """
  6258. Opens an Excellon file, parses it and creates a new object for
  6259. it in the program. Thread-safe.
  6260. :param outname: Name of the resulting object. None causes the
  6261. name to be that of the file.
  6262. :param filename: Excellon file filename
  6263. :type filename: str
  6264. :return: None
  6265. """
  6266. App.log.debug("open_excellon()")
  6267. # How the object should be initialized
  6268. def obj_init(excellon_obj, app_obj):
  6269. # self.progress.emit(20)
  6270. try:
  6271. ret = excellon_obj.parse_file(filename=filename)
  6272. if ret == "fail":
  6273. log.debug("Excellon parsing failed.")
  6274. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  6275. return "fail"
  6276. except IOError:
  6277. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  6278. log.debug("Could not open Excellon object.")
  6279. self.progress.emit(0) # TODO: self and app_bjj mixed
  6280. return "fail"
  6281. except:
  6282. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  6283. msg += traceback.format_exc()
  6284. app_obj.inform.emit(msg)
  6285. return "fail"
  6286. ret = excellon_obj.create_geometry()
  6287. if ret == 'fail':
  6288. log.debug("Could not create geometry for Excellon object.")
  6289. return "fail"
  6290. for tool in excellon_obj.tools:
  6291. if excellon_obj.tools[tool]['solid_geometry']:
  6292. return
  6293. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  6294. return "fail"
  6295. with self.proc_container.new(_("Opening Excellon.")):
  6296. # Object name
  6297. name = outname or filename.split('/')[-1].split('\\')[-1]
  6298. ret_val = self.new_object("excellon", name, obj_init, autoselected=False)
  6299. if ret_val == 'fail':
  6300. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  6301. return
  6302. # Register recent file
  6303. self.file_opened.emit("excellon", filename)
  6304. # GUI feedback
  6305. self.inform.emit(_("[success] Opened: %s") % filename)
  6306. def open_gcode(self, filename, outname=None):
  6307. """
  6308. Opens a G-gcode file, parses it and creates a new object for
  6309. it in the program. Thread-safe.
  6310. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6311. :param filename: G-code file filename
  6312. :type filename: str
  6313. :return: None
  6314. """
  6315. App.log.debug("open_gcode()")
  6316. # How the object should be initialized
  6317. def obj_init(job_obj, app_obj_):
  6318. """
  6319. :param job_obj: the resulting object
  6320. :type app_obj_: App
  6321. """
  6322. assert isinstance(app_obj_, App), \
  6323. "Initializer expected App, got %s" % type(app_obj_)
  6324. self.progress.emit(10)
  6325. try:
  6326. f = open(filename)
  6327. gcode = f.read()
  6328. f.close()
  6329. except IOError:
  6330. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  6331. self.progress.emit(0)
  6332. return "fail"
  6333. job_obj.gcode = gcode
  6334. self.progress.emit(20)
  6335. ret = job_obj.gcode_parse()
  6336. if ret == "fail":
  6337. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  6338. return "fail"
  6339. self.progress.emit(60)
  6340. job_obj.create_geometry()
  6341. with self.proc_container.new(_("Opening G-Code.")):
  6342. # Object name
  6343. name = outname or filename.split('/')[-1].split('\\')[-1]
  6344. # New object creation and file processing
  6345. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  6346. if ret == 'fail':
  6347. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  6348. "Attempting to create a FlatCAM CNCJob Object from "
  6349. "G-Code file failed during processing"))
  6350. return "fail"
  6351. # Register recent file
  6352. self.file_opened.emit("cncjob", filename)
  6353. # GUI feedback
  6354. self.inform.emit(_("[success] Opened: %s") % filename)
  6355. self.progress.emit(100)
  6356. def open_config_file(self, filename, run_from_arg=None):
  6357. """
  6358. Loads a config file from the specified file.
  6359. :param filename: Name of the file from which to load.
  6360. :type filename: str
  6361. :return: None
  6362. """
  6363. App.log.debug("Opening config file: " + filename)
  6364. # add the tab if it was closed
  6365. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  6366. # first clear previous text in text editor (if any)
  6367. self.ui.code_editor.clear()
  6368. # Switch plot_area to CNCJob tab
  6369. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6370. try:
  6371. if filename:
  6372. f = QtCore.QFile(filename)
  6373. if f.open(QtCore.QIODevice.ReadOnly):
  6374. stream = QtCore.QTextStream(f)
  6375. gcode_edited = stream.readAll()
  6376. self.ui.code_editor.setPlainText(gcode_edited)
  6377. f.close()
  6378. except IOError:
  6379. App.log.error("Failed to open config file: %s" % filename)
  6380. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  6381. return
  6382. def open_project(self, filename, run_from_arg=None):
  6383. """
  6384. Loads a project from the specified file.
  6385. 1) Loads and parses file
  6386. 2) Registers the file as recently opened.
  6387. 3) Calls on_file_new()
  6388. 4) Updates options
  6389. 5) Calls new_object() with the object's from_dict() as init method.
  6390. 6) Calls plot_all()
  6391. :param filename: Name of the file from which to load.
  6392. :type filename: str
  6393. :param run_from_arg: True if run for arguments
  6394. :return: None
  6395. """
  6396. App.log.debug("Opening project: " + filename)
  6397. # Open and parse an uncompressed Project file
  6398. try:
  6399. f = open(filename, 'r')
  6400. except IOError:
  6401. App.log.error("Failed to open project file: %s" % filename)
  6402. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  6403. return
  6404. try:
  6405. d = json.load(f, object_hook=dict2obj)
  6406. except Exception as e:
  6407. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  6408. (filename, str(e)))
  6409. f.close()
  6410. # Open and parse a compressed Project file
  6411. try:
  6412. with lzma.open(filename) as f:
  6413. file_content = f.read().decode('utf-8')
  6414. d = json.loads(file_content, object_hook=dict2obj)
  6415. except IOError:
  6416. App.log.error("Failed to open project file: %s" % filename)
  6417. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  6418. return
  6419. # Clear the current project
  6420. # # NOT THREAD SAFE # ##
  6421. if run_from_arg is True:
  6422. pass
  6423. else:
  6424. self.on_file_new()
  6425. # Project options
  6426. self.options.update(d['options'])
  6427. self.project_filename = filename
  6428. self.set_screen_units(self.options["units"])
  6429. # Re create objects
  6430. App.log.debug("Re-creating objects...")
  6431. for obj in d['objs']:
  6432. def obj_init(obj_inst, app_inst):
  6433. obj_inst.from_dict(obj)
  6434. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  6435. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  6436. self.plot_all()
  6437. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  6438. self.should_we_save = False
  6439. self.file_opened.emit("project", filename)
  6440. App.log.debug("Project loaded")
  6441. def propagate_defaults(self, silent=False):
  6442. """
  6443. This method is used to set default values in classes. It's
  6444. an alternative to project options but allows the use
  6445. of values invisible to the user.
  6446. :return: None
  6447. """
  6448. if silent is False:
  6449. self.log.debug("propagate_defaults()")
  6450. # Which objects to update the given parameters.
  6451. routes = {
  6452. "global_zdownrate": CNCjob,
  6453. "excellon_zeros": Excellon,
  6454. "excellon_format_upper_in": Excellon,
  6455. "excellon_format_lower_in": Excellon,
  6456. "excellon_format_upper_mm": Excellon,
  6457. "excellon_format_lower_mm": Excellon,
  6458. "excellon_units": Excellon,
  6459. "gerber_use_buffer_for_union": Gerber,
  6460. "geometry_multidepth": Geometry
  6461. }
  6462. for param in routes:
  6463. if param in routes[param].defaults:
  6464. try:
  6465. routes[param].defaults[param] = self.defaults[param]
  6466. if silent is False:
  6467. self.log.debug(" " + param + " OK")
  6468. except KeyError:
  6469. if silent is False:
  6470. self.log.debug(" ERROR: " + param + " not in defaults.")
  6471. else:
  6472. # Try extracting the name:
  6473. # classname_param here is param in the object
  6474. if param.find(routes[param].__name__.lower() + "_") == 0:
  6475. p = param[len(routes[param].__name__) + 1:]
  6476. if p in routes[param].defaults:
  6477. routes[param].defaults[p] = self.defaults[param]
  6478. if silent is False:
  6479. self.log.debug(" " + param + " OK!")
  6480. def restore_main_win_geom(self):
  6481. try:
  6482. self.ui.setGeometry(self.defaults["global_def_win_x"],
  6483. self.defaults["global_def_win_y"],
  6484. self.defaults["global_def_win_w"],
  6485. self.defaults["global_def_win_h"])
  6486. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  6487. settings = QSettings("Open Source", "FlatCAM")
  6488. if settings.contains("maximized_gui"):
  6489. maximized_ui = settings.value('maximized_gui', type=bool)
  6490. if maximized_ui is True:
  6491. self.ui.showMaximized()
  6492. except KeyError as e:
  6493. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  6494. def plot_all(self, zoom=True):
  6495. """
  6496. Re-generates all plots from all objects.
  6497. :return: None
  6498. """
  6499. self.log.debug("Plot_all()")
  6500. for obj in self.collection.get_list():
  6501. def worker_task(obj):
  6502. with self.proc_container.new("Plotting"):
  6503. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  6504. if zoom:
  6505. self.object_plotted.emit(obj)
  6506. # Send to worker
  6507. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  6508. def register_folder(self, filename):
  6509. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  6510. def register_save_folder(self, filename):
  6511. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  6512. def set_progress_bar(self, percentage, text=""):
  6513. self.ui.progress_bar.setValue(int(percentage))
  6514. def setup_shell(self):
  6515. """
  6516. Creates shell functions. Runs once at startup.
  6517. :return: None
  6518. """
  6519. self.log.debug("setup_shell()")
  6520. def shelp(p=None):
  6521. if not p:
  6522. return _("Available commands:\n") + \
  6523. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  6524. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  6525. if p not in commands:
  6526. return "Unknown command: %s" % p
  6527. return commands[p]["help"]
  6528. # --- Migrated to new architecture ---
  6529. # def options(name):
  6530. # ops = self.collection.get_by_name(str(name)).options
  6531. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  6532. def h(*args):
  6533. """
  6534. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  6535. and standalone parameters into list.
  6536. """
  6537. kwa = {}
  6538. a = []
  6539. n = len(args)
  6540. name = None
  6541. for i in range(n):
  6542. match = re.search(r'^-([a-zA-Z].*)', args[i])
  6543. if match:
  6544. assert name is None
  6545. name = match.group(1)
  6546. continue
  6547. if name is None:
  6548. a.append(args[i])
  6549. else:
  6550. kwa[name] = args[i]
  6551. name = None
  6552. return a, kwa
  6553. @contextmanager
  6554. def wait_signal(signal, timeout=10000):
  6555. """
  6556. Block loop until signal emitted, timeout (ms) elapses
  6557. or unhandled exception happens in a thread.
  6558. :param timeout: time after which the loop is exited
  6559. :param signal: Signal to wait for.
  6560. """
  6561. loop = QtCore.QEventLoop()
  6562. # Normal termination
  6563. signal.connect(loop.quit)
  6564. # Termination by exception in thread
  6565. self.thread_exception.connect(loop.quit)
  6566. status = {'timed_out': False}
  6567. def report_quit():
  6568. status['timed_out'] = True
  6569. loop.quit()
  6570. yield
  6571. # Temporarily change how exceptions are managed.
  6572. oeh = sys.excepthook
  6573. ex = []
  6574. def except_hook(type_, value, traceback_):
  6575. ex.append(value)
  6576. oeh(type_, value, traceback_)
  6577. sys.excepthook = except_hook
  6578. # Terminate on timeout
  6579. if timeout is not None:
  6580. QtCore.QTimer.singleShot(timeout, report_quit)
  6581. # # ## Block ## ##
  6582. loop.exec_()
  6583. # Restore exception management
  6584. sys.excepthook = oeh
  6585. if ex:
  6586. self.raiseTclError(str(ex[0]))
  6587. if status['timed_out']:
  6588. raise Exception('Timed out!')
  6589. def make_docs():
  6590. output = ''
  6591. import collections
  6592. od = collections.OrderedDict(sorted(commands.items()))
  6593. for cmd_, val in od.items():
  6594. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  6595. t = val['help']
  6596. usage_i = t.find('>')
  6597. if usage_i < 0:
  6598. expl = t
  6599. output += expl + '\n\n'
  6600. continue
  6601. expl = t[:usage_i - 1]
  6602. output += expl + '\n\n'
  6603. end_usage_i = t[usage_i:].find('\n')
  6604. if end_usage_i < 0:
  6605. end_usage_i = len(t[usage_i:])
  6606. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  6607. else:
  6608. extras = t[usage_i+end_usage_i+1:]
  6609. parts = [s.strip() for s in extras.split('\n')]
  6610. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  6611. for p in parts:
  6612. output += ' ' + p + '\n\n'
  6613. return output
  6614. '''
  6615. Howto implement TCL shell commands:
  6616. All parameters passed to command should be possible to set as None and test it afterwards.
  6617. This is because we need to see error caused in tcl,
  6618. if None value as default parameter is not allowed TCL will return empty error.
  6619. Use:
  6620. def mycommand(name=None,...):
  6621. Test it like this:
  6622. if name is None:
  6623. self.raise_tcl_error('Argument name is missing.')
  6624. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  6625. otherwise we will miss it and processing will silently continue.
  6626. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  6627. which is catched in exec_command and displayed in TCL shell console with red background.
  6628. Error in console is displayed with TCL trace.
  6629. This behavior works only within main thread,
  6630. errors with promissed tasks can be catched and detected only with log.
  6631. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  6632. TCL shell.
  6633. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  6634. '''
  6635. commands = {
  6636. 'help': {
  6637. 'fcn': shelp,
  6638. 'help': _("Shows list of commands.")
  6639. },
  6640. }
  6641. # Import/overwrite tcl commands as objects of TclCommand descendants
  6642. # This modifies the variable 'commands'.
  6643. tclCommands.register_all_commands(self, commands)
  6644. # Add commands to the tcl interpreter
  6645. for cmd in commands:
  6646. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  6647. # Make the tcl puts function return instead of print to stdout
  6648. self.tcl.eval('''
  6649. rename puts original_puts
  6650. proc puts {args} {
  6651. if {[llength $args] == 1} {
  6652. return "[lindex $args 0]"
  6653. } else {
  6654. eval original_puts $args
  6655. }
  6656. }
  6657. ''')
  6658. def setup_recent_items(self):
  6659. # TODO: Move this to constructor
  6660. icons = {
  6661. "gerber": "share/flatcam_icon16.png",
  6662. "excellon": "share/drill16.png",
  6663. 'geometry': "share/geometry16.png",
  6664. "cncjob": "share/cnc16.png",
  6665. "project": "share/project16.png",
  6666. "svg": "share/geometry16.png",
  6667. "dxf": "share/dxf16.png",
  6668. "pdf": "share/pdf32.png",
  6669. "image": "share/image16.png"
  6670. }
  6671. openers = {
  6672. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  6673. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  6674. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  6675. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  6676. 'project': self.open_project,
  6677. 'svg': self.import_svg,
  6678. 'dxf': self.import_dxf,
  6679. 'image': self.import_image,
  6680. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  6681. }
  6682. # Open file
  6683. try:
  6684. f = open(self.data_path + '/recent.json')
  6685. except IOError:
  6686. App.log.error("Failed to load recent item list.")
  6687. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  6688. return
  6689. try:
  6690. self.recent = json.load(f)
  6691. except json.scanner.JSONDecodeError:
  6692. App.log.error("Failed to parse recent item list.")
  6693. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  6694. f.close()
  6695. return
  6696. f.close()
  6697. # Closure needed to create callbacks in a loop.
  6698. # Otherwise late binding occurs.
  6699. def make_callback(func, fname):
  6700. def opener():
  6701. func(fname)
  6702. return opener
  6703. def reset_recent():
  6704. # Reset menu
  6705. self.ui.recent.clear()
  6706. self.recent = []
  6707. try:
  6708. f = open(self.data_path + '/recent.json', 'w')
  6709. except IOError:
  6710. App.log.error("Failed to open recent items file for writing.")
  6711. return
  6712. json.dump(self.recent, f)
  6713. # Reset menu
  6714. self.ui.recent.clear()
  6715. # Create menu items
  6716. for recent in self.recent:
  6717. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  6718. try:
  6719. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  6720. # Attach callback
  6721. o = make_callback(openers[recent["kind"]], recent['filename'])
  6722. action.triggered.connect(o)
  6723. self.ui.recent.addAction(action)
  6724. except KeyError:
  6725. App.log.error("Unsupported file type: %s" % recent["kind"])
  6726. # Last action in Recent Files menu is one that Clear the content
  6727. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  6728. clear_action.triggered.connect(reset_recent)
  6729. self.ui.recent.addSeparator()
  6730. self.ui.recent.addAction(clear_action)
  6731. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  6732. # self.ui.menufilerecent.set_submenu(recent_menu)
  6733. # recent_menu.show_all()
  6734. # self.ui.recent.show()
  6735. self.log.debug("Recent items list has been populated.")
  6736. def setup_component_editor(self):
  6737. # label = QtWidgets.QLabel("Choose an item from Project")
  6738. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  6739. sel_title = QtWidgets.QTextEdit(
  6740. _('<b>Shortcut Key List</b>'))
  6741. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6742. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6743. # font = self.sel_title.font()
  6744. # font.setPointSize(12)
  6745. # self.sel_title.setFont(font)
  6746. selected_text = _('''
  6747. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  6748. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6749. The normal flow when working in FlatCAM is the following:</span></p>
  6750. <ol>
  6751. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  6752. <br />
  6753. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  6754. &nbsp;</li>
  6755. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  6756. <br />
  6757. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  6758. <br />
  6759. You can change the parameters in this screen and the flow direction is like this:<br />
  6760. <br />
  6761. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  6762. </ol>
  6763. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  6764. ''')
  6765. sel_title.setText(selected_text)
  6766. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6767. self.ui.selected_scroll_area.setWidget(sel_title)
  6768. # tool_title = QtWidgets.QTextEdit(
  6769. # '<b>Shortcut Key List</b>')
  6770. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6771. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6772. # # font = self.sel_title.font()
  6773. # # font.setPointSize(12)
  6774. # # self.sel_title.setFont(font)
  6775. #
  6776. # tool_text = '''
  6777. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  6778. #
  6779. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6780. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  6781. #
  6782. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  6783. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  6784. #
  6785. # <ol>
  6786. # </ol>
  6787. #
  6788. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  6789. #
  6790. # '''
  6791. #
  6792. # tool_title.setText(tool_text)
  6793. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6794. #
  6795. # self.ui.tool_scroll_area.setWidget(tool_title)
  6796. def setup_obj_classes(self):
  6797. """
  6798. Sets up application specifics on the FlatCAMObj class.
  6799. :return: None
  6800. """
  6801. FlatCAMObj.app = self
  6802. ObjectCollection.app = self
  6803. FCProcess.app = self
  6804. FCProcessContainer.app = self
  6805. def version_check(self):
  6806. """
  6807. Checks for the latest version of the program. Alerts the
  6808. user if theirs is outdated. This method is meant to be run
  6809. in a separate thread.
  6810. :return: None
  6811. """
  6812. self.log.debug("version_check()")
  6813. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6814. full_url = App.version_url + \
  6815. "?s=" + str(self.defaults['global_serial']) + \
  6816. "&v=" + str(self.version) + \
  6817. "&os=" + str(self.os) + \
  6818. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  6819. else:
  6820. # no_stats dict; just so it won't break things on website
  6821. no_ststs_dict = {}
  6822. no_ststs_dict["global_ststs"] = {}
  6823. full_url = App.version_url + \
  6824. "?s=" + str(self.defaults['global_serial']) + \
  6825. "&v=" + str(self.version) + \
  6826. "&os=" + str(self.os) + \
  6827. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6828. App.log.debug("Checking for updates @ %s" % full_url)
  6829. # ## Get the data
  6830. try:
  6831. f = urllib.request.urlopen(full_url)
  6832. except:
  6833. # App.log.warning("Failed checking for latest version. Could not connect.")
  6834. self.log.warning("Failed checking for latest version. Could not connect.")
  6835. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  6836. return
  6837. try:
  6838. data = json.load(f)
  6839. except Exception as e:
  6840. App.log.error("Could not parse information about latest version.")
  6841. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  6842. App.log.debug("json.load(): %s" % str(e))
  6843. f.close()
  6844. return
  6845. f.close()
  6846. # ## Latest version?
  6847. if self.version >= data["version"]:
  6848. App.log.debug("FlatCAM is up to date!")
  6849. self.inform.emit(_("[success] FlatCAM is up to date!"))
  6850. return
  6851. App.log.debug("Newer version available.")
  6852. self.message.emit(
  6853. _("Newer Version Available"),
  6854. _("There is a newer version of FlatCAM available for download:\n\n") +
  6855. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  6856. _("info")
  6857. )
  6858. def on_zoom_fit(self, event):
  6859. """
  6860. Callback for zoom-out request. This can be either from the corresponding
  6861. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6862. with axes limits from the geometry bounds of all objects.
  6863. :param event: Ignored.
  6864. :return: None
  6865. """
  6866. self.plotcanvas.fit_view()
  6867. def disable_all_plots(self):
  6868. self.report_usage("disable_all_plots()")
  6869. self.disable_plots(self.collection.get_list())
  6870. self.inform.emit(_("[success] All plots disabled."))
  6871. def disable_other_plots(self):
  6872. self.report_usage("disable_other_plots()")
  6873. self.disable_plots(self.collection.get_non_selected())
  6874. self.inform.emit(_("[success] All non selected plots disabled."))
  6875. def enable_all_plots(self):
  6876. self.report_usage("enable_all_plots()")
  6877. self.enable_plots(self.collection.get_list())
  6878. self.inform.emit(_("[success] All plots enabled."))
  6879. def on_enable_sel_plots(self):
  6880. log.debug("App.on_enable_sel_plot()")
  6881. object_list = self.collection.get_selected()
  6882. self.enable_plots(objects=object_list)
  6883. self.inform.emit(_("[success] Selected plots enabled..."))
  6884. def on_disable_sel_plots(self):
  6885. log.debug("App.on_disable_sel_plot()")
  6886. # self.inform.emit(_("Disabling plots ..."))
  6887. object_list = self.collection.get_selected()
  6888. self.disable_plots(objects=object_list)
  6889. self.inform.emit(_("[success] Selected plots disabled..."))
  6890. def enable_plots(self, objects):
  6891. """
  6892. Disables plots
  6893. :param objects: list of Objects to be enabled
  6894. :return:
  6895. """
  6896. log.debug("Enabling plots ...")
  6897. self.inform.emit(_("Working ..."))
  6898. for obj in objects:
  6899. obj.options['plot'] = True
  6900. self.plots_updated.emit()
  6901. def disable_plots(self, objects):
  6902. """
  6903. Disables plots
  6904. :param objects: list of Objects to be disabled
  6905. :return:
  6906. """
  6907. log.debug("Disabling plots ...")
  6908. self.inform.emit(_("Working ..."))
  6909. for obj in objects:
  6910. obj.options['plot'] = False
  6911. self.plots_updated.emit()
  6912. def clear_plots(self):
  6913. objects = self.collection.get_list()
  6914. for obj in objects:
  6915. obj.clear(obj == objects[-1])
  6916. # Clear pool to free memory
  6917. self.clear_pool()
  6918. def generate_cnc_job(self, objects):
  6919. self.report_usage("generate_cnc_job()")
  6920. # for obj in objects:
  6921. # obj.generatecncjob()
  6922. for obj in objects:
  6923. obj.on_generatecnc_button_click()
  6924. def save_project(self, filename, quit=False):
  6925. """
  6926. Saves the current project to the specified file.
  6927. :param filename: Name of the file in which to save.
  6928. :type filename: str
  6929. :return: None
  6930. """
  6931. self.log.debug("save_project()")
  6932. self.save_in_progress = True
  6933. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  6934. # Capture the latest changes
  6935. # Current object
  6936. try:
  6937. self.collection.get_active().read_form()
  6938. except:
  6939. self.log.debug("There was no active object")
  6940. pass
  6941. # Project options
  6942. self.options_read_form()
  6943. # Serialize the whole project
  6944. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  6945. "options": self.options,
  6946. "version": self.version}
  6947. if self.defaults["global_save_compressed"] is True:
  6948. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  6949. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  6950. # # Write
  6951. f.write(g)
  6952. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6953. else:
  6954. # Open file
  6955. try:
  6956. f = open(filename, 'w')
  6957. except IOError:
  6958. App.log.error("Failed to open file for saving: %s", filename)
  6959. return
  6960. # Write
  6961. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  6962. f.close()
  6963. # verification of the saved project
  6964. # Open and parse
  6965. try:
  6966. saved_f = open(filename, 'r')
  6967. except IOError:
  6968. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  6969. return
  6970. try:
  6971. saved_d = json.load(saved_f, object_hook=dict2obj)
  6972. except:
  6973. self.inform.emit(
  6974. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  6975. f.close()
  6976. return
  6977. saved_f.close()
  6978. if 'version' in saved_d:
  6979. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6980. else:
  6981. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  6982. # if quit:
  6983. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  6984. # t.start()
  6985. self.start_delayed_quit(delay=500, filename=filename, quit=quit)
  6986. def start_delayed_quit(self, delay, filename, quit=None):
  6987. """
  6988. :param delay: period of checking if project file size is more than zero; in seconds
  6989. :param filename: the name of the project file to be checked periodically for size more than zero
  6990. :return:
  6991. """
  6992. to_quit = quit
  6993. self.save_timer = QtCore.QTimer()
  6994. self.save_timer.setInterval(delay)
  6995. self.save_timer.timeout.connect(lambda : self.check_project_file_size(filename=filename, quit=to_quit))
  6996. self.save_timer.start()
  6997. def check_project_file_size(self, filename, quit=None):
  6998. """
  6999. :param filename: the name of the project file to be checked periodically for size more than zero
  7000. :return:
  7001. """
  7002. try:
  7003. if os.stat(filename).st_size > 0:
  7004. self.save_in_progress = False
  7005. self.save_timer.stop()
  7006. if quit:
  7007. self.app_quit.emit()
  7008. except Exception:
  7009. traceback.print_exc()
  7010. def on_options_app2project(self):
  7011. """
  7012. Callback for Options->Transfer Options->App=>Project. Copies options
  7013. from application defaults to project defaults.
  7014. :return: None
  7015. """
  7016. self.report_usage("on_options_app2project")
  7017. self.defaults_read_form()
  7018. self.options.update(self.defaults)
  7019. self.options_write_form()
  7020. def on_options_project2app(self):
  7021. """
  7022. Callback for Options->Transfer Options->Project=>App. Copies options
  7023. from project defaults to application defaults.
  7024. :return: None
  7025. """
  7026. self.report_usage("on_options_project2app")
  7027. self.options_read_form()
  7028. self.defaults.update(self.options)
  7029. self.defaults_write_form()
  7030. def on_options_project2object(self):
  7031. """
  7032. Callback for Options->Transfer Options->Project=>Object. Copies options
  7033. from project defaults to the currently selected object.
  7034. :return: None
  7035. """
  7036. self.report_usage("on_options_project2object")
  7037. self.options_read_form()
  7038. obj = self.collection.get_active()
  7039. if obj is None:
  7040. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7041. return
  7042. for option in self.options:
  7043. if option.find(obj.kind + "_") == 0:
  7044. oname = option[len(obj.kind) + 1:]
  7045. obj.options[oname] = self.options[option]
  7046. obj.to_form() # Update UI
  7047. def on_options_object2project(self):
  7048. """
  7049. Callback for Options->Transfer Options->Object=>Project. Copies options
  7050. from the currently selected object to project defaults.
  7051. :return: None
  7052. """
  7053. self.report_usage("on_options_object2project")
  7054. obj = self.collection.get_active()
  7055. if obj is None:
  7056. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7057. return
  7058. obj.read_form()
  7059. for option in obj.options:
  7060. if option in ['name']: # TODO: Handle this better...
  7061. continue
  7062. self.options[obj.kind + "_" + option] = obj.options[option]
  7063. self.options_write_form()
  7064. def on_options_object2app(self):
  7065. """
  7066. Callback for Options->Transfer Options->Object=>App. Copies options
  7067. from the currently selected object to application defaults.
  7068. :return: None
  7069. """
  7070. self.report_usage("on_options_object2app")
  7071. obj = self.collection.get_active()
  7072. if obj is None:
  7073. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7074. return
  7075. obj.read_form()
  7076. for option in obj.options:
  7077. if option in ['name']: # TODO: Handle this better...
  7078. continue
  7079. self.defaults[obj.kind + "_" + option] = obj.options[option]
  7080. self.defaults_write_form()
  7081. def on_options_app2object(self):
  7082. """
  7083. Callback for Options->Transfer Options->App=>Object. Copies options
  7084. from application defaults to the currently selected object.
  7085. :return: None
  7086. """
  7087. self.report_usage("on_options_app2object")
  7088. self.defaults_read_form()
  7089. obj = self.collection.get_active()
  7090. if obj is None:
  7091. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7092. return
  7093. for option in self.defaults:
  7094. if option.find(obj.kind + "_") == 0:
  7095. oname = option[len(obj.kind) + 1:]
  7096. obj.options[oname] = self.defaults[option]
  7097. obj.to_form() # Update UI
  7098. # end of file