FlatCAMApp.py 533 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871
  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
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import tkinter as tk
  21. from PyQt5 import QtPrintSupport
  22. from contextlib import contextmanager
  23. import gc
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from multiprocessing.connection import Listener, Client
  26. from multiprocessing import Pool, cpu_count
  27. import socket
  28. from array import array
  29. # #######################################
  30. # # Imports part of FlatCAM ##
  31. # #######################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from flatcamGUI.PlotCanvas import *
  35. from flatcamGUI.PlotCanvasLegacy import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from flatcamEditors.FlatCAMTextEditor import TextEditor
  43. from FlatCAMProcess import *
  44. from FlatCAMWorkerStack import WorkerStack
  45. from flatcamGUI.VisPyVisuals import Color
  46. from vispy.gloo.util import _screenshot
  47. from vispy.io import write_png
  48. from flatcamTools import *
  49. import tclCommands
  50. import gettext
  51. import FlatCAMTranslation as fcTranslate
  52. import builtins
  53. if sys.platform == 'win32':
  54. import winreg
  55. fcTranslate.apply_language('strings')
  56. if '_' not in builtins.__dict__:
  57. _ = gettext.gettext
  58. # ########################################
  59. # # App ###
  60. # ########################################
  61. class App(QtCore.QObject):
  62. """
  63. The main application class. The constructor starts the GUI.
  64. """
  65. # Get Cmd Line Options
  66. cmd_line_shellfile = ''
  67. cmd_line_shellvar = ''
  68. cmd_line_headless = None
  69. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  70. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  71. "FlatCam.py --headless=1"
  72. try:
  73. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  74. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  75. "shellvar=",
  76. "headless=",
  77. "multiprocessing-fork="])
  78. except getopt.GetoptError:
  79. print(cmd_line_help)
  80. sys.exit(2)
  81. for opt, arg in cmd_line_options:
  82. if opt == '-h':
  83. print(cmd_line_help)
  84. sys.exit()
  85. elif opt == '--shellfile':
  86. cmd_line_shellfile = arg
  87. elif opt == '--shellvar':
  88. cmd_line_shellvar = arg
  89. elif opt == '--headless':
  90. try:
  91. cmd_line_headless = eval(arg)
  92. except NameError:
  93. pass
  94. # ## Logging ###
  95. log = logging.getLogger('base')
  96. log.setLevel(logging.DEBUG)
  97. # log.setLevel(logging.WARNING)
  98. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  99. handler = logging.StreamHandler()
  100. handler.setFormatter(formatter)
  101. log.addHandler(handler)
  102. # ##########################################################################
  103. # ################## Version and VERSION DATE ##############################
  104. # ##########################################################################
  105. version = 8.98
  106. version_date = "2019/10/7"
  107. beta = True
  108. engine = '3D'
  109. # current date now
  110. date = str(datetime.today()).rpartition('.')[0]
  111. date = ''.join(c for c in date if c not in ':-')
  112. date = date.replace(' ', '_')
  113. # URL for update checks and statistics
  114. version_url = "http://flatcam.org/version"
  115. # App URL
  116. app_url = "http://flatcam.org"
  117. # Manual URL
  118. manual_url = "http://flatcam.org/manual/index.html"
  119. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  120. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  121. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  122. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  123. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  124. # this variable will hold the project status
  125. # if True it will mean that the project was modified and not saved
  126. should_we_save = False
  127. # flag is True if saving action has been triggered
  128. save_in_progress = False
  129. # ###########################################################################
  130. # ############################# Signals ################################
  131. # ###########################################################################
  132. # Inform the user
  133. # Handled by:
  134. # * App.info() --> Print on the status bar
  135. inform = QtCore.pyqtSignal(str)
  136. app_quit = QtCore.pyqtSignal()
  137. # General purpose background task
  138. worker_task = QtCore.pyqtSignal(dict)
  139. # File opened
  140. # Handled by:
  141. # * register_folder()
  142. # * register_recent()
  143. # Note: Setting the parameters to unicode does not seem
  144. # to have an effect. Then are received as Qstring
  145. # anyway.
  146. # File type and filename
  147. file_opened = QtCore.pyqtSignal(str, str)
  148. # File type and filename
  149. file_saved = QtCore.pyqtSignal(str, str)
  150. # Percentage of progress
  151. progress = QtCore.pyqtSignal(int)
  152. plots_updated = QtCore.pyqtSignal()
  153. # Emitted by new_object() and passes the new object as argument, plot flag.
  154. # on_object_created() adds the object to the collection, plots on appropriate flag
  155. # and emits new_object_available.
  156. object_created = QtCore.pyqtSignal(object, bool, bool)
  157. # Emitted when a object has been changed (like scaled, mirrored)
  158. object_changed = QtCore.pyqtSignal(object)
  159. # Emitted after object has been plotted.
  160. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  161. object_plotted = QtCore.pyqtSignal(object)
  162. # Emitted when a new object has been added or deleted from/to the collection
  163. object_status_changed = QtCore.pyqtSignal(object, str, str)
  164. message = QtCore.pyqtSignal(str, str, str)
  165. # Emmited when shell command is finished(one command only)
  166. shell_command_finished = QtCore.pyqtSignal(object)
  167. # Emitted when multiprocess pool has been recreated
  168. pool_recreated = QtCore.pyqtSignal(object)
  169. # Emitted when an unhandled exception happens
  170. # in the worker task.
  171. thread_exception = QtCore.pyqtSignal(object)
  172. # used to signal that there are arguments for the app
  173. args_at_startup = QtCore.pyqtSignal(list)
  174. # a reusable signal to replot a list of objects
  175. # should be disconnected after use so it can be reused
  176. replot_signal = pyqtSignal(list)
  177. def __init__(self, user_defaults=True, post_gui=None):
  178. """
  179. Starts the application.
  180. :return: app
  181. :rtype: App
  182. """
  183. App.log.info("FlatCAM Starting...")
  184. self.main_thread = QtWidgets.QApplication.instance().thread()
  185. # ############################################################################
  186. # # ################# OS-specific ############################################
  187. # ############################################################################
  188. portable = False
  189. # Folder for user settings.
  190. if sys.platform == 'win32':
  191. # #########################################################################
  192. # Setup the listening thread for another instance launching with args #####
  193. # #########################################################################
  194. # make sure the thread is stored by using a self. otherwise it's garbage collected
  195. self.th = QtCore.QThread()
  196. self.th.start(priority=QtCore.QThread.LowestPriority)
  197. self.new_launch = ArgsThread()
  198. self.new_launch.open_signal[list].connect(self.on_startup_args)
  199. self.new_launch.moveToThread(self.th)
  200. self.new_launch.start.emit()
  201. from win32com.shell import shell, shellcon
  202. if platform.architecture()[0] == '32bit':
  203. App.log.debug("Win32!")
  204. else:
  205. App.log.debug("Win64!")
  206. # #########################################################################
  207. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  208. # #########################################################################
  209. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  210. try:
  211. with open(config_file, 'r'):
  212. pass
  213. except FileNotFoundError:
  214. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  215. try:
  216. with open(config_file, 'r') as f:
  217. try:
  218. for line in f:
  219. param = str(line).replace('\n', '').rpartition('=')
  220. if param[0] == 'portable':
  221. try:
  222. portable = eval(param[2])
  223. except NameError:
  224. portable = False
  225. if param[0] == 'headless':
  226. if param[2].lower() == 'true':
  227. self.cmd_line_headless = 1
  228. else:
  229. self.cmd_line_headless = None
  230. except Exception as e:
  231. log.debug('App.__init__() -->%s' % str(e))
  232. return
  233. except FileNotFoundError as e:
  234. log.debug(str(e))
  235. pass
  236. if portable is False:
  237. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  238. else:
  239. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  240. self.os = 'windows'
  241. else: # Linux/Unix/MacOS
  242. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  243. self.os = 'unix'
  244. # ##########################################################################
  245. # ################## Setup folders and files ###############################
  246. # ##########################################################################
  247. if not os.path.exists(self.data_path):
  248. os.makedirs(self.data_path)
  249. App.log.debug('Created data folder: ' + self.data_path)
  250. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  251. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  252. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  253. if not os.path.exists(self.postprocessorpaths):
  254. os.makedirs(self.postprocessorpaths)
  255. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  256. # create current_defaults.FlatConfig file if there is none
  257. try:
  258. f = open(self.data_path + '/current_defaults.FlatConfig')
  259. f.close()
  260. except IOError:
  261. App.log.debug('Creating empty current_defaults.FlatConfig')
  262. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  263. json.dump({}, f)
  264. f.close()
  265. # create factory_defaults.FlatConfig file if there is none
  266. try:
  267. f = open(self.data_path + '/factory_defaults.FlatConfig')
  268. f.close()
  269. except IOError:
  270. App.log.debug('Creating empty factory_defaults.FlatConfig')
  271. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  272. json.dump({}, f)
  273. f.close()
  274. # create a recent files json file if there is none
  275. try:
  276. f = open(self.data_path + '/recent.json')
  277. f.close()
  278. except IOError:
  279. App.log.debug('Creating empty recent.json')
  280. f = open(self.data_path + '/recent.json', 'w')
  281. json.dump([], f)
  282. f.close()
  283. # create a recent projects json file if there is none
  284. try:
  285. fp = open(self.data_path + '/recent_projects.json')
  286. fp.close()
  287. except IOError:
  288. App.log.debug('Creating empty recent_projects.json')
  289. fp = open(self.data_path + '/recent_projects.json', 'w')
  290. json.dump([], fp)
  291. fp.close()
  292. # Application directory. CHDIR to it. Otherwise, trying to load
  293. # GUI icons will fail as their path is relative.
  294. # This will fail under cx_freeze ...
  295. self.app_home = os.path.dirname(os.path.realpath(__file__))
  296. App.log.debug("Application path is " + self.app_home)
  297. App.log.debug("Started in " + os.getcwd())
  298. # cx_freeze workaround
  299. if os.path.isfile(self.app_home):
  300. self.app_home = os.path.dirname(self.app_home)
  301. os.chdir(self.app_home)
  302. # #############################################################################
  303. # ##################### CREATE MULTIPROCESSING POOL ###########################
  304. # #############################################################################
  305. self.pool = Pool(processes=cpu_count())
  306. # ##########################################################################
  307. # ################## Setting the Splash Screen #############################
  308. # ##########################################################################
  309. settings = QSettings("Open Source", "FlatCAM")
  310. if settings.contains("splash_screen"):
  311. show_splash = settings.value("splash_screen")
  312. else:
  313. settings.setValue('splash_screen', 1)
  314. # This will write the setting to the platform specific storage.
  315. del settings
  316. show_splash = 1
  317. if show_splash and self.cmd_line_headless != 1:
  318. splash_pix = QtGui.QPixmap('share/splash.png')
  319. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  320. # self.splash.setMask(splash_pix.mask())
  321. # move splashscreen to the current monitor
  322. desktop = QtWidgets.QApplication.desktop()
  323. screen = desktop.screenNumber(QtGui.QCursor.pos())
  324. current_screen_center = desktop.availableGeometry(screen).center()
  325. self.splash.move(current_screen_center - self.splash.rect().center())
  326. self.splash.show()
  327. self.splash.showMessage(_("FlatCAM is initializing ..."),
  328. alignment=Qt.AlignBottom | Qt.AlignLeft,
  329. color=QtGui.QColor("gray"))
  330. else:
  331. show_splash = 0
  332. # #############################################################################
  333. # ##################### Initialize GUI ########################################
  334. # #############################################################################
  335. # FlatCAM colors used in plotting
  336. self.FC_light_green = '#BBF268BF'
  337. self.FC_dark_green = '#006E20BF'
  338. self.FC_light_blue = '#a5a5ffbf'
  339. self.FC_dark_blue = '#0000ffbf'
  340. QtCore.QObject.__init__(self)
  341. self.ui = FlatCAMGUI(self.version, self.beta, self)
  342. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  343. self.ui.final_save.connect(self.final_save)
  344. # #############################################################################
  345. # ############################## Data #########################################
  346. # #############################################################################
  347. self.recent = []
  348. self.recent_projects = []
  349. self.clipboard = QtWidgets.QApplication.clipboard()
  350. self.project_filename = None
  351. self.toggle_units_ignore = False
  352. # self.defaults_form = PreferencesUI()
  353. # when adding entries here read the comments in the method found bellow named:
  354. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  355. self.defaults_form_fields = {
  356. # General App
  357. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  358. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  359. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  360. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  361. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  362. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  363. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  364. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  365. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  366. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  367. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  368. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  369. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  370. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  371. # General GUI Preferences
  372. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  373. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  374. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  375. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  376. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  377. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  378. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  379. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  380. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  381. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  382. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  383. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  384. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  385. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  386. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  387. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  388. # General GUI Settings
  389. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  390. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  391. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  392. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  393. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  394. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  395. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  396. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  397. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  398. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  399. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  400. # Gerber General
  401. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  402. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  403. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  404. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  405. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  406. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  407. # Gerber Options
  408. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  409. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  410. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  411. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  412. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  413. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  414. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  415. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  416. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  417. # Gerber Advanced Options
  418. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  419. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  420. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  421. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  422. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  423. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  424. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  425. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  426. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  427. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  428. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  429. # Gerber Export
  430. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  431. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  432. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  433. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  434. # Gerber Editor
  435. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  436. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  437. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  438. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  439. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  440. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  441. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  442. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  443. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  444. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  445. "gerber_editor_circ_angle":
  446. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  447. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  448. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  449. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  450. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  451. # Excellon General
  452. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  453. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  454. "excellon_format_upper_in":
  455. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  456. "excellon_format_lower_in":
  457. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  458. "excellon_format_upper_mm":
  459. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  460. "excellon_format_lower_mm":
  461. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  462. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  463. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  464. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  465. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  466. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  467. # Excellon Options
  468. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  469. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  470. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  471. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  472. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  473. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  474. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  475. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  476. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  477. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  478. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  479. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  480. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  481. # Excellon Advanced Options
  482. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  483. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  484. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  485. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  486. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  487. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  488. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  489. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  490. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  491. # Excellon Export
  492. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  493. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  494. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  495. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  496. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  497. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  498. # Excellon Editor
  499. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  500. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  501. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  502. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  503. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  504. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  505. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  506. "excellon_editor_circ_angle":
  507. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  508. # Excellon Slots
  509. "excellon_editor_slot_direction":
  510. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  511. "excellon_editor_slot_angle":
  512. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  513. "excellon_editor_slot_length":
  514. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  515. # Excellon Slots
  516. "excellon_editor_slot_array_size":
  517. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  518. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  519. "excellon_editor_slot_lin_pitch":
  520. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  521. "excellon_editor_slot_lin_angle":
  522. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  523. "excellon_editor_slot_circ_dir":
  524. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  525. "excellon_editor_slot_circ_angle":
  526. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  527. # Geometry General
  528. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  529. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  530. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  531. # Geometry Options
  532. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  533. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  534. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  535. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  536. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  537. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  538. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  539. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  540. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  541. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  542. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  543. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  544. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  545. # Geometry Advanced Options
  546. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  547. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  548. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  549. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  550. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  551. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  552. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  553. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  554. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  555. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  556. # Geometry Editor
  557. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  558. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  559. # CNCJob General
  560. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  561. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  562. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  563. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  564. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  565. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  566. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  567. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  568. # CNC Job Options
  569. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  570. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  571. # CNC Job Advanced Options
  572. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  573. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  574. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  575. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  576. # NCC Tool
  577. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  578. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  579. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  580. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  581. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  582. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  583. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  584. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  585. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  586. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  587. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  588. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  589. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  590. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  591. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  592. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  593. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  594. # CutOut Tool
  595. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  596. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  597. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  598. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  599. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  600. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  601. # Paint Area Tool
  602. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  603. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  604. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  605. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  606. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  607. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  608. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  609. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  610. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  611. # 2-sided Tool
  612. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  613. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  614. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  615. # Film Tool
  616. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  617. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  618. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  619. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  620. # Panelize Tool
  621. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  622. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  623. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  624. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  625. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  626. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  627. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  628. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  629. # Calculators Tool
  630. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  631. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  632. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  633. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  634. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  635. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  636. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  637. # Transformations Tool
  638. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  639. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  640. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  641. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  642. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  643. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  644. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  645. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  646. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  647. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  648. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  649. # SolderPaste Dispensing Tool
  650. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  651. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  652. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  653. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  654. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  655. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  656. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  657. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  658. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  659. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  660. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  661. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  662. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  663. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  664. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  665. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  666. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  667. # Utilities
  668. # File associations
  669. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  670. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  671. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  672. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  673. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  674. }
  675. # ############################
  676. # ### LOAD POSTPROCESSORS ####
  677. # ############################
  678. self.postprocessors = load_postprocessors(self)
  679. for name in list(self.postprocessors.keys()):
  680. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  681. if name.partition('_')[0] == 'Paste':
  682. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  683. continue
  684. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  685. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  686. if name == 'hpgl':
  687. continue
  688. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  689. # ############################
  690. # ### LOAD LANGUAGES ####
  691. # ############################
  692. self.languages = fcTranslate.load_languages()
  693. for name in sorted(self.languages.values()):
  694. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  695. # #################################################################################
  696. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  697. # #################################################################################
  698. self.defaults = LoudDict()
  699. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  700. self.defaults.update({
  701. # Global APP Preferences
  702. "first_run": True,
  703. "units": "IN",
  704. "global_serial": 0,
  705. "global_stats": {},
  706. "global_tabs_detachable": True,
  707. "global_graphic_engine": '3D',
  708. "global_app_level": 'b',
  709. "global_portable": False,
  710. "global_language": 'English',
  711. "global_version_check": True,
  712. "global_send_stats": True,
  713. "global_pan_button": '2',
  714. "global_mselect_key": 'Control',
  715. "global_project_at_startup": False,
  716. "global_systray_icon": True,
  717. "global_project_autohide": True,
  718. "global_toggle_tooltips": True,
  719. "global_worker_number": 2,
  720. "global_tolerance": 0.005,
  721. "global_open_style": True,
  722. "global_delete_confirmation": True,
  723. "global_compression_level": 3,
  724. "global_save_compressed": True,
  725. # Global GUI Preferences
  726. "global_gridx": 0.0393701,
  727. "global_gridy": 0.0393701,
  728. "global_snap_max": 0.001968504,
  729. "global_workspace": False,
  730. "global_workspaceT": "A4P",
  731. "global_grid_context_menu": {
  732. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  733. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  734. },
  735. "global_plot_fill": '#BBF268BF',
  736. "global_plot_line": '#006E20BF',
  737. "global_sel_fill": '#a5a5ffbf',
  738. "global_sel_line": '#0000ffbf',
  739. "global_alt_sel_fill": '#BBF268BF',
  740. "global_alt_sel_line": '#006E20BF',
  741. "global_draw_color": '#FF0000',
  742. "global_sel_draw_color": '#0000FF',
  743. "global_proj_item_color": '#000000',
  744. "global_proj_item_dis_color": '#b7b7cb',
  745. "global_activity_icon": 'Ball green',
  746. "global_toolbar_view": 511,
  747. "global_background_timeout": 300000, # Default value is 5 minutes
  748. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  749. # (python trace only for unknown errors),
  750. # 1 = show trace(show trace always),
  751. # 2 = (For the future).
  752. # Persistence
  753. "global_last_folder": None,
  754. "global_last_save_folder": None,
  755. # Default window geometry
  756. "global_def_win_x": 100,
  757. "global_def_win_y": 100,
  758. "global_def_win_w": 1024,
  759. "global_def_win_h": 650,
  760. "global_def_notebook_width": 1,
  761. # Constants...
  762. "global_defaults_save_period_ms": 20000, # Time between default saves.
  763. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  764. "global_shell_at_startup": False, # Show the shell at startup.
  765. "global_recent_limit": 10, # Max. items in recent list.
  766. "fit_key": 'V',
  767. "zoom_out_key": '-',
  768. "zoom_in_key": '=',
  769. "grid_toggle_key": 'G',
  770. "global_zoom_ratio": 1.5,
  771. "global_point_clipboard_format": "(%.4f, %.4f)",
  772. "global_zdownrate": None,
  773. # General GUI Settings
  774. "global_hover": False,
  775. "global_selection_shape": True,
  776. "global_layout": "compact",
  777. "global_cursor_type": "small",
  778. "global_cursor_size": 20,
  779. # Gerber General
  780. "gerber_plot": True,
  781. "gerber_solid": True,
  782. "gerber_multicolored": False,
  783. "gerber_circle_steps": 128,
  784. "gerber_use_buffer_for_union": True,
  785. "gerber_def_units": 'IN',
  786. "gerber_def_zeros": 'L',
  787. # Gerber Options
  788. "gerber_isotooldia": 0.00787402,
  789. "gerber_isopasses": 1,
  790. "gerber_isooverlap": 0.00393701,
  791. "gerber_milling_type": "cl",
  792. "gerber_combine_passes": False,
  793. "gerber_noncoppermargin": 0.00393701,
  794. "gerber_noncopperrounded": False,
  795. "gerber_bboxmargin": 0.00393701,
  796. "gerber_bboxrounded": False,
  797. # Gerber Advanced Options
  798. "gerber_aperture_display": False,
  799. "gerber_aperture_scale_factor": 1.0,
  800. "gerber_aperture_buffer_factor": 0.0,
  801. "gerber_follow": False,
  802. "gerber_tool_type": 'circular',
  803. "gerber_vtipdia": 0.1,
  804. "gerber_vtipangle": 30,
  805. "gerber_vcutz": -0.05,
  806. "gerber_buffering": "full",
  807. "gerber_simplification": False,
  808. "gerber_simp_tolerance": 0.0005,
  809. # Gerber Export
  810. "gerber_exp_units": 'IN',
  811. "gerber_exp_integer": 2,
  812. "gerber_exp_decimals": 4,
  813. "gerber_exp_zeros": 'L',
  814. # Gerber Editor
  815. "gerber_editor_sel_limit": 30,
  816. "gerber_editor_newcode": 10,
  817. "gerber_editor_newsize": 0.8,
  818. "gerber_editor_newtype": 'C',
  819. "gerber_editor_newdim": "0.5, 0.5",
  820. "gerber_editor_array_size": 5,
  821. "gerber_editor_lin_axis": 'X',
  822. "gerber_editor_lin_pitch": 1,
  823. "gerber_editor_lin_angle": 0.0,
  824. "gerber_editor_circ_dir": 'CW',
  825. "gerber_editor_circ_angle": 0.0,
  826. "gerber_editor_scale_f": 1.0,
  827. "gerber_editor_buff_f": 0.1,
  828. "gerber_editor_ma_low": 0.0,
  829. "gerber_editor_ma_high": 1.0,
  830. # Excellon General
  831. "excellon_plot": True,
  832. "excellon_solid": True,
  833. "excellon_format_upper_in": 2,
  834. "excellon_format_lower_in": 4,
  835. "excellon_format_upper_mm": 3,
  836. "excellon_format_lower_mm": 3,
  837. "excellon_zeros": "L",
  838. "excellon_units": "INCH",
  839. "excellon_update": True,
  840. "excellon_optimization_type": 'B',
  841. "excellon_search_time": 3,
  842. # Excellon Options
  843. "excellon_drillz": -0.0590551,
  844. "excellon_travelz": 0.0787402,
  845. "excellon_endz": 0.5,
  846. "excellon_feedrate": 3.14961,
  847. "excellon_spindlespeed": None,
  848. "excellon_dwell": False,
  849. "excellon_dwelltime": 1,
  850. "excellon_toolchange": False,
  851. "excellon_toolchangez": 0.5,
  852. "excellon_ppname_e": 'default',
  853. "excellon_tooldia": 0.0314961,
  854. "excellon_slot_tooldia": 0.0708661,
  855. "excellon_gcode_type": "drills",
  856. # Excellon Advanced Options
  857. "excellon_offset": 0.0,
  858. "excellon_toolchangexy": "0.0, 0.0",
  859. "excellon_startz": None,
  860. "excellon_feedrate_rapid": 31.4961,
  861. "excellon_z_pdepth": -0.02,
  862. "excellon_feedrate_probe": 3.14961,
  863. "excellon_spindledir": 'CW',
  864. "excellon_f_plunge": False,
  865. "excellon_f_retract": False,
  866. # Excellon Export
  867. "excellon_exp_units": 'INCH',
  868. "excellon_exp_format": 'ndec',
  869. "excellon_exp_integer": 2,
  870. "excellon_exp_decimals": 4,
  871. "excellon_exp_zeros": 'LZ',
  872. "excellon_exp_slot_type": 'routing',
  873. # Excellon Editor
  874. "excellon_editor_sel_limit": 30,
  875. "excellon_editor_newdia": 0.039,
  876. "excellon_editor_array_size": 5,
  877. "excellon_editor_lin_dir": 'X',
  878. "excellon_editor_lin_pitch": 0.1,
  879. "excellon_editor_lin_angle": 0.0,
  880. "excellon_editor_circ_dir": 'CW',
  881. "excellon_editor_circ_angle": 12,
  882. # Excellon Slots
  883. "excellon_editor_slot_direction": 'X',
  884. "excellon_editor_slot_angle": 0.0,
  885. "excellon_editor_slot_length": 5.0,
  886. # Excellon Slot Array
  887. "excellon_editor_slot_array_size": 5,
  888. "excellon_editor_slot_lin_dir": 'X',
  889. "excellon_editor_slot_lin_pitch": 0.1,
  890. "excellon_editor_slot_lin_angle": 0.0,
  891. "excellon_editor_slot_circ_dir": 'CW',
  892. "excellon_editor_slot_circ_angle": 0.0,
  893. # Geometry General
  894. "geometry_plot": True,
  895. "geometry_circle_steps": 128,
  896. "geometry_cnctooldia": "0.0944882",
  897. # Geometry Options
  898. "geometry_cutz": -0.0944882,
  899. "geometry_vtipdia": 0.1,
  900. "geometry_vtipangle": 30,
  901. "geometry_multidepth": False,
  902. "geometry_depthperpass": 0.0314961,
  903. "geometry_travelz": 0.0787402,
  904. "geometry_toolchange": False,
  905. "geometry_toolchangez": 0.5,
  906. "geometry_endz": 0.5,
  907. "geometry_feedrate": 3.14961,
  908. "geometry_feedrate_z": 3.14961,
  909. "geometry_spindlespeed": None,
  910. "geometry_dwell": False,
  911. "geometry_dwelltime": 1,
  912. "geometry_ppname_g": 'default',
  913. # Geometry Advanced Options
  914. "geometry_toolchangexy": "0.0, 0.0",
  915. "geometry_startz": None,
  916. "geometry_feedrate_rapid": 3.14961,
  917. "geometry_extracut": False,
  918. "geometry_z_pdepth": -0.02,
  919. "geometry_f_plunge": False,
  920. "geometry_spindledir": 'CW',
  921. "geometry_feedrate_probe": 3.14961,
  922. "geometry_segx": 0.0,
  923. "geometry_segy": 0.0,
  924. # Geometry Editor
  925. "geometry_editor_sel_limit": 30,
  926. "geometry_editor_milling_type": "cl",
  927. # CNC Job General
  928. "cncjob_plot": True,
  929. "cncjob_plot_kind": 'all',
  930. "cncjob_annotation": True,
  931. "cncjob_tooldia": 0.0393701,
  932. "cncjob_coords_type": "G90",
  933. "cncjob_coords_decimals": 4,
  934. "cncjob_fr_decimals": 2,
  935. "cncjob_steps_per_circle": 128,
  936. # CNC Job Options
  937. "cncjob_prepend": "",
  938. "cncjob_append": "",
  939. # CNC Job Advanced Options
  940. "cncjob_toolchange_macro": "",
  941. "cncjob_toolchange_macro_enable": False,
  942. "cncjob_annotation_fontsize": 9,
  943. "cncjob_annotation_fontcolor": '#990000',
  944. # NCC Tool
  945. "tools_ncctools": "0.0393701, 0.019685",
  946. "tools_nccorder": 'rev',
  947. "tools_nccoverlap": 0.015748,
  948. "tools_nccmargin": 0.0393701,
  949. "tools_nccmethod": "seed",
  950. "tools_nccconnect": True,
  951. "tools_ncccontour": True,
  952. "tools_nccrest": False,
  953. "tools_ncc_offset_choice": False,
  954. "tools_ncc_offset_value": 0.0000,
  955. "tools_nccref": 'itself',
  956. "tools_ncc_plotting": 'normal',
  957. "tools_nccmilling_type": 'cl',
  958. "tools_ncctool_type": 'V',
  959. "tools_ncccutz": -0.001968504,
  960. "tools_ncctipdia": 0.00393701,
  961. "tools_ncctipangle": 30,
  962. # Cutout Tool
  963. "tools_cutouttooldia": 0.0944882,
  964. "tools_cutoutkind": "single",
  965. "tools_cutoutmargin": 0.00393701,
  966. "tools_cutoutgapsize": 0.15748,
  967. "tools_gaps_ff": "4",
  968. "tools_cutout_convexshape": False,
  969. # Paint Tool
  970. "tools_painttooldia": 0.023622,
  971. "tools_paintorder": 'rev',
  972. "tools_paintoverlap": 0.015748,
  973. "tools_paintmargin": 0.0,
  974. "tools_paintmethod": "seed",
  975. "tools_selectmethod": "all",
  976. "tools_pathconnect": True,
  977. "tools_paintcontour": True,
  978. "tools_paint_plotting": 'normal',
  979. # 2-Sided Tool
  980. "tools_2sided_mirror_axis": "X",
  981. "tools_2sided_axis_loc": "point",
  982. "tools_2sided_drilldia": 0.11811,
  983. # Film Tool
  984. "tools_film_type": 'neg',
  985. "tools_film_boundary": 0.0393701,
  986. "tools_film_scale": 0,
  987. "tools_film_color": '#000000',
  988. # Panel Tool
  989. "tools_panelize_spacing_columns": 0,
  990. "tools_panelize_spacing_rows": 0,
  991. "tools_panelize_columns": 1,
  992. "tools_panelize_rows": 1,
  993. "tools_panelize_constrain": False,
  994. "tools_panelize_constrainx": 0.0,
  995. "tools_panelize_constrainy": 0.0,
  996. "tools_panelize_panel_type": 'gerber',
  997. # Calculators Tool
  998. "tools_calc_vshape_tip_dia": 0.007874,
  999. "tools_calc_vshape_tip_angle": 30,
  1000. "tools_calc_vshape_cut_z": 0.000787,
  1001. "tools_calc_electro_length": 10.0,
  1002. "tools_calc_electro_width": 10.0,
  1003. "tools_calc_electro_cdensity": 13.0,
  1004. "tools_calc_electro_growth": 10.0,
  1005. # Transform Tool
  1006. "tools_transform_rotate": 90,
  1007. "tools_transform_skew_x": 0.0,
  1008. "tools_transform_skew_y": 0.0,
  1009. "tools_transform_scale_x": 1.0,
  1010. "tools_transform_scale_y": 1.0,
  1011. "tools_transform_scale_link": True,
  1012. "tools_transform_scale_reference": True,
  1013. "tools_transform_offset_x": 0.0,
  1014. "tools_transform_offset_y": 0.0,
  1015. "tools_transform_mirror_reference": False,
  1016. "tools_transform_mirror_point": (0, 0),
  1017. # SolderPaste Tool
  1018. "tools_solderpaste_tools": "0.0393701, 0.011811",
  1019. "tools_solderpaste_new": 0.011811,
  1020. "tools_solderpaste_z_start": 0.00019685039,
  1021. "tools_solderpaste_z_dispense": 0.00393701,
  1022. "tools_solderpaste_z_stop": 0.00019685039,
  1023. "tools_solderpaste_z_travel": 0.00393701,
  1024. "tools_solderpaste_z_toolchange": 0.0393701,
  1025. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  1026. "tools_solderpaste_frxy": 3.0,
  1027. "tools_solderpaste_frz": 3.0,
  1028. "tools_solderpaste_frz_dispense": 0.0393701,
  1029. "tools_solderpaste_speedfwd": 20,
  1030. "tools_solderpaste_dwellfwd": 1,
  1031. "tools_solderpaste_speedrev": 10,
  1032. "tools_solderpaste_dwellrev": 1,
  1033. "tools_solderpaste_pp": 'Paste_1',
  1034. # Subtract Tool
  1035. "tools_sub_close_paths": True,
  1036. # Utilities
  1037. # file associations
  1038. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  1039. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  1040. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  1041. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  1042. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  1043. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  1044. # Keyword list
  1045. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  1046. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  1047. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  1048. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  1049. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1050. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1051. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1052. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1053. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1054. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1055. 'toolchange_xy, use_threads, value, x, x0, x1, y, y0, y1, z_cut, z_move',
  1056. "script_autocompleter": True,
  1057. "script_text": "",
  1058. "script_plot": True,
  1059. "script_source_file": "",
  1060. "document_autocompleter": False,
  1061. "document_text": "",
  1062. "document_plot": True,
  1063. "document_source_file": "",
  1064. "document_font_color": '#000000',
  1065. "document_sel_color": '#0055ff',
  1066. "document_font_size": 6,
  1067. "document_tab_size": 80,
  1068. })
  1069. # ############################################################
  1070. # ############### Load defaults from file ####################
  1071. # ############################################################
  1072. if user_defaults:
  1073. self.load_defaults(filename='current_defaults')
  1074. # #############################################################
  1075. # ############## APPLY APP LANGUAGE ###########################
  1076. # #############################################################
  1077. ret_val = fcTranslate.apply_language('strings')
  1078. if ret_val == "no language":
  1079. self.inform.emit('[ERROR] %s' %
  1080. _("Could not find the Language files. The App strings are missing."))
  1081. log.debug("Could not find the Language files. The App strings are missing.")
  1082. else:
  1083. # make the current language the current selection on the language combobox
  1084. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1085. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1086. # ##############################################################
  1087. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1088. # ##############################################################
  1089. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1090. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1091. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  1092. self.save_defaults(silent=True, first_time=True)
  1093. self.propagate_defaults(silent=True)
  1094. self.restore_main_win_geom()
  1095. # def auto_save_defaults():
  1096. # try:
  1097. # self.save_defaults(silent=True)
  1098. # self.propagate_defaults(silent=True)
  1099. # finally:
  1100. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1101. # the following lines activates automatic defaults save
  1102. # if user_defaults:
  1103. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1104. # self.options_form = PreferencesUI()
  1105. self.options_form_fields = {
  1106. "units": self.ui.general_options_form.general_app_group.units_radio,
  1107. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1108. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1109. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1110. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1111. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1112. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1113. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1114. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1115. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1116. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1117. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1118. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1119. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1120. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1121. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1122. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1123. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1124. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1125. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1126. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1127. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1128. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1129. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1130. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1131. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1132. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1133. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1134. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1135. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1136. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1137. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1138. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1139. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1140. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1141. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1142. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1143. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1144. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1145. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1146. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1147. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1148. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1149. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1150. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1151. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1152. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1153. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1154. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1155. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1156. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1157. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1158. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1159. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1160. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1161. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1162. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1163. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1164. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1165. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1166. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1167. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1168. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1169. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1170. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1171. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1172. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1173. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1174. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1175. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1176. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1177. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1178. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1179. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1180. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1181. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1182. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1183. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1184. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1185. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1186. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1187. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1188. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1189. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1190. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1191. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1192. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1193. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1194. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1195. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1196. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1197. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1198. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1199. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1200. }
  1201. for name in list(self.postprocessors.keys()):
  1202. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1203. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1204. self.options = LoudDict()
  1205. self.options.set_change_callback(self.on_options_dict_change)
  1206. self.options.update({
  1207. "units": "IN",
  1208. "global_gridx": 1.0,
  1209. "global_gridy": 1.0,
  1210. "global_snap_max": 0.05,
  1211. "global_background_timeout": 300000, # Default value is 5 minutes
  1212. "global_verbose_error_level": 0, # Shell verbosity:
  1213. # 0 = default(python trace only for unknown errors),
  1214. # 1 = show trace(show trace allways), 2 = (For the future).
  1215. "gerber_plot": True,
  1216. "gerber_solid": True,
  1217. "gerber_multicolored": False,
  1218. "gerber_isotooldia": 0.016,
  1219. "gerber_isopasses": 1,
  1220. "gerber_isooverlap": 0.15,
  1221. "gerber_combine_passes": True,
  1222. "gerber_noncoppermargin": 0.0,
  1223. "gerber_noncopperrounded": False,
  1224. "gerber_bboxmargin": 0.0,
  1225. "gerber_bboxrounded": False,
  1226. "excellon_plot": True,
  1227. "excellon_solid": False,
  1228. "excellon_format_upper_in": 2,
  1229. "excellon_format_lower_in": 4,
  1230. "excellon_format_upper_mm": 3,
  1231. "excellon_format_lower_mm": 3,
  1232. "excellon_units": 'INCH',
  1233. "excellon_optimization_type": 'B',
  1234. "excellon_search_time": 3,
  1235. "excellon_zeros": "L",
  1236. "excellon_drillz": -0.1,
  1237. "excellon_travelz": 0.1,
  1238. "excellon_feedrate": 3.0,
  1239. "excellon_feedrate_rapid": 3.0,
  1240. "excellon_spindlespeed": None,
  1241. "excellon_spindledir": 'CW',
  1242. "excellon_dwell": True,
  1243. "excellon_dwelltime": 1000,
  1244. "excellon_toolchange": False,
  1245. "excellon_toolchangez": 1.0,
  1246. "excellon_toolchangexy": "0.0, 0.0",
  1247. "excellon_tooldia": 0.016,
  1248. "excellon_ppname_e": 'default',
  1249. "excellon_f_plunge": False,
  1250. "excellon_startz": None,
  1251. "excellon_endz": 2.0,
  1252. "geometry_plot": True,
  1253. "geometry_segx": 0.0,
  1254. "geometry_segy": 0.0,
  1255. "geometry_cutz": -0.002,
  1256. "geometry_vtipdia": 0.1,
  1257. "geometry_vtipangle": 30,
  1258. "geometry_travelz": 0.1,
  1259. "geometry_feedrate": 3.0,
  1260. "geometry_feedrate_z": 3.0,
  1261. "geometry_feedrate_rapid": 3.0,
  1262. "geometry_spindlespeed": None,
  1263. "geometry_spindledir": 'CW',
  1264. "geometry_dwell": True,
  1265. "geometry_dwelltime": 1000,
  1266. "geometry_cnctooldia": 0.016,
  1267. "geometry_toolchange": False,
  1268. "geometry_toolchangez": 2.0,
  1269. "geometry_toolchangexy": "0.0, 0.0",
  1270. "geometry_startz": None,
  1271. "geometry_endz": 2.0,
  1272. "geometry_ppname_g": "default",
  1273. "geometry_f_plunge": False,
  1274. "geometry_depthperpass": 0.002,
  1275. "geometry_multidepth": False,
  1276. "geometry_extracut": False,
  1277. "cncjob_plot": True,
  1278. "cncjob_tooldia": 0.016,
  1279. "cncjob_prepend": "",
  1280. "cncjob_append": "",
  1281. "tools_ncctools": "1.0, 0.5",
  1282. "tools_nccoverlap": 0.4,
  1283. "tools_nccmargin": 1,
  1284. "tools_cutouttooldia": 0.07,
  1285. "tools_cutoutmargin": 0.1,
  1286. "tools_cutoutgapsize": 0.15,
  1287. "tools_gaps_ff": "8",
  1288. "tools_painttooldia": 0.07,
  1289. "tools_paintoverlap": 0.15,
  1290. "tools_paintmargin": 0.0,
  1291. "tools_paintmethod": "seed",
  1292. "tools_selectmethod": "single",
  1293. "tools_pathconnect": True,
  1294. "tools_paintcontour": True,
  1295. "tools_2sided_mirror_axis": "X",
  1296. "tools_2sided_axis_loc": 'point',
  1297. "tools_2sided_drilldia": 1,
  1298. "tools_film_type": 'neg',
  1299. "tools_film_boundary": 1,
  1300. "tools_film_scale": 0,
  1301. "tools_panelize_spacing_columns": 0,
  1302. "tools_panelize_spacing_rows": 0,
  1303. "tools_panelize_columns": 1,
  1304. "tools_panelize_rows": 1,
  1305. "tools_panelize_constrain": False,
  1306. "tools_panelize_constrainx": 0.0,
  1307. "tools_panelize_constrainy": 0.0,
  1308. "script_text": "",
  1309. "script_plot": False,
  1310. "script_source_file": "",
  1311. "document_text": "",
  1312. "document_plot": False,
  1313. "document_source_file": "",
  1314. })
  1315. self.options.update(self.defaults) # Copy app defaults to project options
  1316. self.gen_form = None
  1317. self.ger_form = None
  1318. self.exc_form = None
  1319. self.geo_form = None
  1320. self.cnc_form = None
  1321. self.tools_form = None
  1322. self.fa_form = None
  1323. self.on_options_combo_change(0) # Will show the initial form
  1324. # ################################
  1325. # ### Initialize the color box's color in Preferences -> Global -> Color
  1326. # Init Plot Colors
  1327. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1328. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1329. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1330. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1331. int(self.defaults['global_plot_fill'][7:9], 16))
  1332. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1333. int(self.defaults['global_plot_fill'][7:9], 16))
  1334. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1335. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1336. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1337. # Init Left-Right Selection colors
  1338. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1339. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1340. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1341. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1342. int(self.defaults['global_sel_fill'][7:9], 16))
  1343. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1344. int(self.defaults['global_sel_fill'][7:9], 16))
  1345. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1346. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1347. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1348. # Init Right-Left Selection colors
  1349. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1350. self.defaults['global_alt_sel_fill'])
  1351. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1352. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1353. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1354. int(self.defaults['global_sel_fill'][7:9], 16))
  1355. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1356. int(self.defaults['global_sel_fill'][7:9], 16))
  1357. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1358. self.defaults['global_alt_sel_line'])
  1359. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1360. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1361. # Init Draw color and Selection Draw Color
  1362. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1363. self.defaults['global_draw_color'])
  1364. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1365. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1366. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1367. self.defaults['global_sel_draw_color'])
  1368. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1369. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1370. # Init Project Items color
  1371. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1372. self.defaults['global_proj_item_color'])
  1373. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1374. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1375. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1376. self.defaults['global_proj_item_dis_color'])
  1377. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1378. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1379. # Init the Annotation CNC Job color
  1380. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1381. self.defaults['cncjob_annotation_fontcolor'])
  1382. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1383. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1384. # Init the Tool Film color
  1385. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1386. self.defaults['tools_film_color'])
  1387. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1388. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1389. # ### End of Data ####
  1390. # ##############################################
  1391. # ######### SETUP OBJECT COLLECTION ############
  1392. # ##############################################
  1393. self.collection = ObjectCollection(self)
  1394. self.ui.project_tab_layout.addWidget(self.collection.view)
  1395. # ### Adjust tabs width ## ##
  1396. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1397. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1398. self.collection.view.setMinimumWidth(290)
  1399. self.log.debug("Finished creating Object Collection.")
  1400. # ###############################################
  1401. # ############# SETUP Plot Area #################
  1402. # ###############################################
  1403. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1404. if self.defaults["global_graphic_engine"] == '3D':
  1405. self.is_legacy = False
  1406. else:
  1407. self.is_legacy = True
  1408. # Matplotlib axis
  1409. self.axes = None
  1410. if show_splash:
  1411. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1412. "Canvas initialization started."),
  1413. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1414. color=QtGui.QColor("gray"))
  1415. start_plot_time = time.time() # debug
  1416. self.plotcanvas = None
  1417. self.app_cursor = None
  1418. self.hover_shapes = None
  1419. self.on_plotcanvas_setup()
  1420. end_plot_time = time.time()
  1421. self.used_time = end_plot_time - start_plot_time
  1422. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1423. if show_splash:
  1424. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1425. "Canvas initialization started.\n"
  1426. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1427. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1428. color=QtGui.QColor("gray"))
  1429. self.ui.splitter.setStretchFactor(1, 2)
  1430. # #################################################################
  1431. # ####################### SYS TRAY ################################
  1432. # #################################################################
  1433. if self.defaults["global_systray_icon"]:
  1434. self.parent_w = QtWidgets.QWidget()
  1435. if self.cmd_line_headless == 1:
  1436. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1437. headless=True,
  1438. parent=self.parent_w)
  1439. else:
  1440. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1441. parent=self.parent_w)
  1442. # ###############################################
  1443. # ############# Worker SETUP ####################
  1444. # ###############################################
  1445. if self.defaults["global_worker_number"]:
  1446. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1447. else:
  1448. self.workers = WorkerStack(workers_number=2)
  1449. self.worker_task.connect(self.workers.add_task)
  1450. self.log.debug("Finished creating Workers crew.")
  1451. # ################################################
  1452. # ############### Activity Monitor ###############
  1453. # ################################################
  1454. if self.defaults["global_activity_icon"] == "Ball green":
  1455. icon = 'share/active_2_static.png'
  1456. movie = "share/active_2.gif"
  1457. elif self.defaults["global_activity_icon"] == "Ball black":
  1458. icon = 'share/active_static.png'
  1459. movie = "share/active.gif"
  1460. elif self.defaults["global_activity_icon"] == "Arrow green":
  1461. icon = 'share/active_3_static.png'
  1462. movie = "share/active_3.gif"
  1463. elif self.defaults["global_activity_icon"] == "Eclipse green":
  1464. icon = 'share/active_4_static.png'
  1465. movie = "share/active_4.gif"
  1466. else:
  1467. icon = 'share/active_static.png'
  1468. movie = "share/active.gif"
  1469. self.activity_view = FlatCAMActivityView(icon=icon, movie=movie)
  1470. self.ui.infobar.addWidget(self.activity_view)
  1471. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1472. # ################################################
  1473. # ############### Signal handling ################
  1474. # ################################################
  1475. # ############# Custom signals ##################
  1476. # signal for displaying messages in status bar
  1477. self.inform.connect(self.info)
  1478. # signal to be called when the app is quiting
  1479. self.app_quit.connect(self.quit_application)
  1480. self.message.connect(self.message_dialog)
  1481. self.progress.connect(self.set_progress_bar)
  1482. # signals that are emitted when object state changes
  1483. self.object_created.connect(self.on_object_created)
  1484. self.object_changed.connect(self.on_object_changed)
  1485. self.object_plotted.connect(self.on_object_plotted)
  1486. self.plots_updated.connect(self.on_plots_updated)
  1487. # signals emitted when file state change
  1488. self.file_opened.connect(self.register_recent)
  1489. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1490. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1491. # ############# Standard signals ###################
  1492. # ### Menu
  1493. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1494. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1495. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1496. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1497. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1498. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1499. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1500. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1501. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1502. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1503. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1504. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1505. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1506. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1507. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1508. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1509. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1510. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1511. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1512. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1513. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1514. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1515. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1516. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1517. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1518. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1519. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1520. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1521. self.ui.menufile_exit.triggered.connect(self.final_save)
  1522. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1523. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1524. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1525. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1526. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1527. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1528. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1529. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1530. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1531. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1532. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1533. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1534. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1535. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1536. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1537. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1538. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1539. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1540. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1541. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1542. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1543. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1544. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1545. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1546. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1547. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1548. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1549. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1550. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1551. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1552. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1553. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1554. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1555. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1556. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1557. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1558. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1559. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1560. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1561. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1562. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1563. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1564. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1565. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1566. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1567. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1568. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1569. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1570. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1571. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1572. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1573. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1574. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1575. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1576. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1577. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1578. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1579. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1580. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1581. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1582. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1583. # ToolBar signals
  1584. self.connect_toolbar_signals()
  1585. # Notebook signals
  1586. # make the right click on the notebook tab connect to a function
  1587. self.ui.notebook.setupContextMenu()
  1588. self.ui.notebook.addContextMenu(
  1589. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1590. initial_checked=self.defaults["global_tabs_detachable"])
  1591. # activate initial state
  1592. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1593. # Context Menu
  1594. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1595. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1596. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1597. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1598. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1599. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1600. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1601. self.ui.clearplot.triggered.connect(self.clear_plots)
  1602. self.ui.replot.triggered.connect(self.plot_all)
  1603. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1604. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1605. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1606. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1607. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1608. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1609. # Preferences Plot Area TAB
  1610. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1611. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1612. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1613. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1614. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1615. # ##############################
  1616. # ### GUI PREFERENCES SIGNALS ##
  1617. # ##############################
  1618. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1619. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1620. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1621. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1622. )
  1623. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1624. lambda: self.on_toggle_units(no_pref=False))
  1625. # ###############################################################
  1626. # ################### GUI COLORS SIGNALS ########################
  1627. # ###############################################################
  1628. # Setting plot colors signals
  1629. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1630. self.on_pf_color_entry)
  1631. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1632. self.on_pf_color_button)
  1633. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1634. self.on_pf_color_spinner)
  1635. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1636. self.on_pf_color_slider)
  1637. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1638. self.on_pl_color_entry)
  1639. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1640. self.on_pl_color_button)
  1641. # Setting selection (left - right) colors signals
  1642. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1643. self.on_sf_color_entry)
  1644. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1645. self.on_sf_color_button)
  1646. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1647. self.on_sf_color_spinner)
  1648. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1649. self.on_sf_color_slider)
  1650. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1651. self.on_sl_color_entry)
  1652. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1653. self.on_sl_color_button)
  1654. # Setting selection (right - left) colors signals
  1655. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1656. self.on_alt_sf_color_entry)
  1657. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1658. self.on_alt_sf_color_button)
  1659. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1660. self.on_alt_sf_color_spinner)
  1661. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1662. self.on_alt_sf_color_slider)
  1663. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1664. self.on_alt_sl_color_entry)
  1665. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1666. self.on_alt_sl_color_button)
  1667. # Setting Editor Draw colors signals
  1668. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1669. self.on_draw_color_entry)
  1670. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1671. self.on_draw_color_button)
  1672. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1673. self.on_sel_draw_color_entry)
  1674. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1675. self.on_sel_draw_color_button)
  1676. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1677. self.on_proj_color_entry)
  1678. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1679. self.on_proj_color_button)
  1680. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1681. self.on_proj_color_dis_entry)
  1682. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1683. self.on_proj_color_dis_button)
  1684. # ########## workspace setting signals ###########
  1685. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1686. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1687. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1688. # #################################################
  1689. # ############ GUI SETTINGS SIGNALS ###############
  1690. # #################################################
  1691. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1692. # ########## CNC Job related signals #############
  1693. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1694. self.on_cnc_custom_parameters)
  1695. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1696. self.on_annotation_fontcolor_entry)
  1697. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1698. self.on_annotation_fontcolor_button)
  1699. # ########## Tools related signals #############
  1700. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1701. self.on_film_color_entry)
  1702. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1703. self.on_film_color_button)
  1704. # portability changed signal
  1705. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1706. # Object list
  1707. self.collection.view.activated.connect(self.on_row_activated)
  1708. self.object_status_changed.connect(self.on_collection_updated)
  1709. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1710. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1711. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1712. # Export Excellon parameters.
  1713. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1714. self.on_update_exc_export
  1715. )
  1716. # call it once to make sure it is updated at startup
  1717. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1718. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1719. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1720. self.on_excellon_defaults_button)
  1721. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1722. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1723. self.on_excellon_options_button)
  1724. # when there are arguments at application startup this get launched
  1725. self.args_at_startup[list].connect(self.on_startup_args)
  1726. # ##############################################################
  1727. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1728. # ##############################################################
  1729. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1730. lambda: self.restore_extensions(ext_type='excellon'))
  1731. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1732. lambda: self.restore_extensions(ext_type='gcode'))
  1733. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1734. lambda: self.restore_extensions(ext_type='gerber'))
  1735. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1736. lambda: self.delete_all_extensions(ext_type='excellon'))
  1737. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1738. lambda: self.delete_all_extensions(ext_type='gcode'))
  1739. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1740. lambda: self.delete_all_extensions(ext_type='gerber'))
  1741. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1742. lambda: self.add_extension(ext_type='excellon'))
  1743. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1744. lambda: self.add_extension(ext_type='gcode'))
  1745. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1746. lambda: self.add_extension(ext_type='gerber'))
  1747. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1748. lambda: self.del_extension(ext_type='excellon'))
  1749. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1750. lambda: self.del_extension(ext_type='gcode'))
  1751. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1752. lambda: self.del_extension(ext_type='gerber'))
  1753. # connect the 'Apply' buttons from the Preferences/File Associations
  1754. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1755. lambda: self.on_register_files(obj_type='excellon'))
  1756. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1757. lambda: self.on_register_files(obj_type='gcode'))
  1758. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1759. lambda: self.on_register_files(obj_type='gerber'))
  1760. # ##############################################################
  1761. # ###################### KEYWORDS SIGNALS ######################
  1762. # ##############################################################
  1763. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1764. lambda: self.restore_extensions(ext_type='keyword'))
  1765. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1766. lambda: self.delete_all_extensions(ext_type='keyword'))
  1767. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1768. lambda: self.add_extension(ext_type='keyword'))
  1769. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1770. lambda: self.del_extension(ext_type='keyword'))
  1771. # splash screen button signal
  1772. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1773. # connect the abort_all_tasks related slots to the related signals
  1774. self.proc_container.idle_flag.connect(self.app_is_idle)
  1775. # #####################################################################################
  1776. # ########### FINISHED CONNECTING SIGNALS #############################################
  1777. # #####################################################################################
  1778. self.log.debug("Finished connecting Signals.")
  1779. # #####################################################################################
  1780. # ########################## Other setups #############################################
  1781. # #####################################################################################
  1782. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1783. # depending on from where those tools are called different actions can be done
  1784. self.call_source = 'app'
  1785. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1786. self.tool_tab_locked = False
  1787. # decide if to show or hide the Notebook side of the screen at startup
  1788. if self.defaults["global_project_at_startup"] is True:
  1789. self.ui.splitter.setSizes([1, 1])
  1790. else:
  1791. self.ui.splitter.setSizes([0, 1])
  1792. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1793. self.setup_obj_classes()
  1794. self.setup_recent_items()
  1795. self.setup_component_editor()
  1796. # this does not work in Legacy Mode
  1797. if self.is_legacy is True:
  1798. self.ui.general_defaults_form.general_gui_group.workspace_cb.setDisabled(True)
  1799. self.ui.general_defaults_form.general_gui_group.workspace_type_lbl.setDisabled(True)
  1800. self.ui.general_defaults_form.general_gui_group.wk_cb.setDisabled(True)
  1801. # #####################################################################################
  1802. # ######################### Auto-complete KEYWORDS ####################################
  1803. # #####################################################################################
  1804. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1805. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1806. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1807. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1808. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1809. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1810. 'mirror', 'ncc',
  1811. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1812. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1813. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1814. 'save', 'save_project',
  1815. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1816. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1817. 'version', 'write_gcode'
  1818. ]
  1819. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1820. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1821. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis', 'axisoffset',
  1822. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1823. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1824. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1825. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1826. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1827. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1828. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1829. 'spacing_columns',
  1830. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'use_threads', 'value', 'x',
  1831. 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1832. ]
  1833. self.tcl_keywords = [
  1834. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1835. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1836. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1837. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1838. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1839. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1840. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1841. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1842. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1843. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1844. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1845. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1846. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1847. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1848. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1849. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1850. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1851. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1852. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1853. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1854. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1855. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1856. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1857. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1858. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1859. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1860. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1861. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1862. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1863. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1864. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1865. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1866. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1867. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1868. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1869. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1870. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1871. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1872. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1873. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1874. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1875. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1876. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1877. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1878. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1879. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1880. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1881. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1882. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1883. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1884. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1885. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1886. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1887. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1888. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1889. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1890. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1891. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1892. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1893. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1894. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1895. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1896. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1897. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1898. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1899. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1900. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1901. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1902. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1903. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1904. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1905. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1906. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1907. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1908. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1909. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1910. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1911. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1912. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1913. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1914. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1915. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1916. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1917. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1918. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1919. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1920. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1921. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1922. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1923. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1924. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1925. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1926. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1927. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1928. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1929. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1930. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1931. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1932. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1933. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1934. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1935. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1936. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1937. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1938. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1939. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1940. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1941. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1942. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1943. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1944. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1945. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1946. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1947. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1948. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1949. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1950. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1951. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1952. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1953. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1954. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1955. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1956. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1957. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1958. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1959. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1960. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1961. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1962. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1963. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1964. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1965. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1966. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1967. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1968. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1969. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1970. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1971. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1972. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1973. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1974. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1975. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1976. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1977. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1978. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1979. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1980. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1981. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1982. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1983. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1984. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1985. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1986. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1987. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1988. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1989. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1990. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1991. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1992. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1993. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1994. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1995. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1996. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1997. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1998. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1999. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2000. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2001. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2002. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2003. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2004. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2005. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2006. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2007. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2008. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2009. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2010. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2011. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2012. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2013. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2014. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2015. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2016. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2017. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2018. ]
  2019. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2020. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2021. # ####################################################################################
  2022. # ####################### Shell SETUP ################################################
  2023. # ####################################################################################
  2024. self.shell = FCShell(self, version=self.version)
  2025. self.shell._edit.set_model_data(self.myKeywords)
  2026. self.shell.setWindowIcon(self.ui.app_icon)
  2027. self.shell.setWindowTitle("FlatCAM Shell")
  2028. self.shell.resize(*self.defaults["global_shell_shape"])
  2029. self.shell.append_output("FlatCAM %s - " % self.version)
  2030. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  2031. self.init_tcl()
  2032. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2033. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2034. self.ui.shell_dock.setWidget(self.shell)
  2035. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2036. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2037. QtWidgets.QDockWidget.DockWidgetFloatable |
  2038. QtWidgets.QDockWidget.DockWidgetClosable)
  2039. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2040. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2041. if self.defaults["global_shell_at_startup"]:
  2042. self.ui.shell_dock.show()
  2043. else:
  2044. self.ui.shell_dock.hide()
  2045. # ##################################################################################
  2046. # ###################### Tools and Plugins #########################################
  2047. # ##################################################################################
  2048. self.dblsidedtool = None
  2049. self.distance_tool = None
  2050. self.distance_min_tool = None
  2051. self.panelize_tool = None
  2052. self.film_tool = None
  2053. self.paste_tool = None
  2054. self.calculator_tool = None
  2055. self.rules_tool = None
  2056. self.sub_tool = None
  2057. self.move_tool = None
  2058. self.cutout_tool = None
  2059. self.ncclear_tool = None
  2060. self.optimal_tool=None
  2061. self.paint_tool = None
  2062. self.transform_tool = None
  2063. self.properties_tool = None
  2064. self.pdf_tool = None
  2065. self.image_tool = None
  2066. self.pcb_wizard_tool = None
  2067. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2068. self.install_tools()
  2069. # ### System Font Parsing ###
  2070. # self.f_parse = ParseFont(self)
  2071. # self.parse_system_fonts()
  2072. # #####################################################################################
  2073. # ######################## Check for updates ##########################################
  2074. # #####################################################################################
  2075. # Separate thread (Not worker)
  2076. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2077. if (self.beta is False or self.beta is None) and \
  2078. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  2079. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2080. self.thr2 = QtCore.QThread()
  2081. self.worker_task.emit({'fcn': self.version_check,
  2082. 'params': []})
  2083. self.thr2.start(QtCore.QThread.LowPriority)
  2084. # #####################################################################################
  2085. # ######################### Register files with FlatCAM; #############################
  2086. # ######################### It works only for Windows for now ########################
  2087. # #####################################################################################
  2088. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2089. self.on_register_files()
  2090. # #####################################################################################
  2091. # ###################### Variables for global usage ###################################
  2092. # #####################################################################################
  2093. # coordinates for relative position display
  2094. self.rel_point1 = (0, 0)
  2095. self.rel_point2 = (0, 0)
  2096. # variable to store coordinates
  2097. self.pos = (0, 0)
  2098. self.pos_jump = (0, 0)
  2099. # variable to store mouse coordinates
  2100. self.mouse = [0, 0]
  2101. # decide if we have a double click or single click
  2102. self.doubleclick = False
  2103. # variable to store if a command is active (then the var is not None) and which one it is
  2104. self.command_active = None
  2105. # variable to store the status of moving selection action
  2106. # None value means that it's not an selection action
  2107. # True value = a selection from left to right
  2108. # False value = a selection from right to left
  2109. self.selection_type = None
  2110. # List to store the objects that are currently loaded in FlatCAM
  2111. # This list is updated on each object creation or object delete
  2112. self.all_objects_list = list()
  2113. # List to store the objects that are selected
  2114. self.sel_objects_list = list()
  2115. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2116. self.key_modifiers = None
  2117. # Variable to hold the status of the axis
  2118. self.toggle_axis = True
  2119. # Variable to store the status of the fullscreen event
  2120. self.toggle_fscreen = False
  2121. # Variable to store the status of the code editor
  2122. self.toggle_codeeditor = False
  2123. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2124. self.click_noproject = False
  2125. self.cursor = None
  2126. # Variable to store the GCODE that was edited
  2127. self.gcode_edited = ""
  2128. # reference for the self.ui.code_editor
  2129. self.reference_code_editor = None
  2130. self.script_code = ''
  2131. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2132. self.preferences_changed_flag = False
  2133. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2134. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2135. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2136. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2137. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2138. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2139. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2140. 'tap', 'xpi']
  2141. self.svg_list = ['svg']
  2142. self.dxf_list = ['dxf']
  2143. self.pdf_list = ['pdf']
  2144. self.prj_list = ['flatprj']
  2145. self.conf_list = ['flatconfig']
  2146. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2147. # flag for polygons not cleared
  2148. self.poly_not_cleared = False
  2149. # VisPy visuals
  2150. self.isHovering = False
  2151. self.notHovering = True
  2152. # Window geometry
  2153. self.x_pos = None
  2154. self.y_pos = None
  2155. self.width = None
  2156. self.height = None
  2157. # Event signals disconnect id holders
  2158. self.mp = None
  2159. self.mm = None
  2160. self.mr = None
  2161. self.mp_zc = None
  2162. # when True, the app has to return from any thread
  2163. self.abort_flag = False
  2164. # set the value used in the Windows Title
  2165. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2166. # ###############################################################################
  2167. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2168. # ############# It's done only once after install ###############
  2169. # ###############################################################################
  2170. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2171. fac_def_from_file = factory_file.read()
  2172. factory_defaults = json.loads(fac_def_from_file)
  2173. # if the file contain an empty dictionary then save the factory defaults into the file
  2174. if not factory_defaults:
  2175. self.save_factory_defaults(silent=False)
  2176. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2177. initial_lay = 'compact'
  2178. self.on_layout(lay=initial_lay)
  2179. # Set the combobox in Preferences to the current layout
  2180. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2181. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2182. factory_file.close()
  2183. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2184. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2185. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2186. # after the first run, this object should be False
  2187. self.defaults["first_run"] = False
  2188. # ###############################################################################
  2189. # ################# ADDING FlatCAM EDITORS section ##############################
  2190. # ###############################################################################
  2191. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2192. # at the first launch of the App , the editors will not be functional.
  2193. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2194. self.exc_editor = FlatCAMExcEditor(self)
  2195. self.grb_editor = FlatCAMGrbEditor(self)
  2196. self.log.debug("Finished adding FlatCAM Editor's.")
  2197. self.set_ui_title(name=_("New Project - Not saved"))
  2198. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2199. current_platform = platform.architecture()[0]
  2200. if current_platform != '64bit':
  2201. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2202. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2203. # ###############################################################################
  2204. # ####################### Finished the CONSTRUCTOR ##############################
  2205. # ###############################################################################
  2206. App.log.debug("END of constructor. Releasing control.")
  2207. # #####################################################################################
  2208. # ########################## SHOW GUI #################################################
  2209. # #####################################################################################
  2210. # if the app is not started as headless, show it
  2211. if self.cmd_line_headless != 1:
  2212. if show_splash:
  2213. # finish the splash
  2214. self.splash.finish(self.ui)
  2215. settings = QSettings("Open Source", "FlatCAM")
  2216. if settings.contains("maximized_gui"):
  2217. maximized_ui = settings.value('maximized_gui', type=bool)
  2218. if maximized_ui is True:
  2219. self.ui.showMaximized()
  2220. else:
  2221. self.ui.show()
  2222. else:
  2223. self.ui.show()
  2224. if self.defaults["global_systray_icon"]:
  2225. self.trayIcon.show()
  2226. else:
  2227. log.warning("******************* RUNNING HEADLESS *******************")
  2228. # #####################################################################################
  2229. # ########################## START-UP ARGUMENTS #######################################
  2230. # #####################################################################################
  2231. # test if the program was started with a script as parameter
  2232. if self.cmd_line_shellvar:
  2233. try:
  2234. cnt = 0
  2235. command_tcl = 0
  2236. for i in self.cmd_line_shellvar.split(','):
  2237. if i is not None:
  2238. try:
  2239. command_tcl = eval(i)
  2240. except:
  2241. command_tcl = i
  2242. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2243. cnt += 1
  2244. # if there are Windows paths then replace the path separator with a Unix like one
  2245. if sys.platform == 'win32':
  2246. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2247. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2248. except Exception as ext:
  2249. print("ERROR: ", ext)
  2250. sys.exit(2)
  2251. if self.cmd_line_shellfile:
  2252. try:
  2253. if self.ui.shell_dock.isHidden():
  2254. self.ui.shell_dock.show()
  2255. with open(self.cmd_line_shellfile, "r") as myfile:
  2256. if show_splash:
  2257. self.splash.showMessage('%s: %ssec\n%s' % (
  2258. _("Canvas initialization started.\n"
  2259. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2260. _("Executing Tcl Script ...")),
  2261. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2262. color=QtGui.QColor("gray"))
  2263. cmd_line_shellfile_text = myfile.read()
  2264. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2265. except Exception as ext:
  2266. print("ERROR: ", ext)
  2267. sys.exit(2)
  2268. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2269. # the path/file_name must be enclosed in quotes if it contain spaces
  2270. if App.args:
  2271. self.args_at_startup.emit(App.args)
  2272. @staticmethod
  2273. def copy_and_overwrite(from_path, to_path):
  2274. """
  2275. From here:
  2276. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2277. :param from_path: source path
  2278. :param to_path: destination path
  2279. :return: None
  2280. """
  2281. if os.path.exists(to_path):
  2282. shutil.rmtree(to_path)
  2283. try:
  2284. shutil.copytree(from_path, to_path)
  2285. except FileNotFoundError:
  2286. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2287. shutil.copytree(from_new_path, to_path)
  2288. def on_startup_args(self, args, silent=False):
  2289. """
  2290. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2291. :param args: a list containing the application args at startup
  2292. :return: None
  2293. """
  2294. if args is not None:
  2295. args_to_process = args
  2296. else:
  2297. args_to_process = App.args
  2298. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2299. for argument in args_to_process:
  2300. if '.FlatPrj'.lower() in argument.lower():
  2301. try:
  2302. project_name = str(argument)
  2303. if project_name == "":
  2304. if silent is False:
  2305. self.inform.emit(_("Open cancelled."))
  2306. else:
  2307. # self.open_project(project_name)
  2308. run_from_arg = True
  2309. # self.worker_task.emit({'fcn': self.open_project,
  2310. # 'params': [project_name, run_from_arg]})
  2311. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2312. except Exception as e:
  2313. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2314. elif '.FlatConfig'.lower() in argument.lower():
  2315. try:
  2316. file_name = str(argument)
  2317. if file_name == "":
  2318. if silent is False:
  2319. self.inform.emit(_("Open Config file failed."))
  2320. else:
  2321. run_from_arg = True
  2322. # self.worker_task.emit({'fcn': self.open_config_file,
  2323. # 'params': [file_name, run_from_arg]})
  2324. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2325. except Exception as e:
  2326. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2327. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2328. try:
  2329. file_name = str(argument)
  2330. if file_name == "":
  2331. if silent is False:
  2332. self.inform.emit(_("Open Script file failed."))
  2333. else:
  2334. if silent is False:
  2335. self.on_fileopenscript(name=file_name)
  2336. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2337. self.on_filerunscript(name=file_name)
  2338. except Exception as e:
  2339. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2340. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2341. log.debug("App.on_startup_args() --> Quit event.")
  2342. sys.exit()
  2343. elif 'save'.lower() in argument.lower():
  2344. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2345. self.save_defaults()
  2346. else:
  2347. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2348. proc_arg = argument.lower()
  2349. for ext in exc_list:
  2350. proc_ext = ext.replace(' ', '')
  2351. proc_ext = '.%s' % proc_ext
  2352. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2353. file_name = str(argument)
  2354. if file_name == "":
  2355. if silent is False:
  2356. self.inform.emit(_("Open Excellon file failed."))
  2357. else:
  2358. self.on_fileopenexcellon(name=file_name)
  2359. return
  2360. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2361. for ext in gco_list:
  2362. proc_ext = ext.replace(' ', '')
  2363. proc_ext = '.%s' % proc_ext
  2364. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2365. file_name = str(argument)
  2366. if file_name == "":
  2367. if silent is False:
  2368. self.inform.emit(_("Open GCode file failed."))
  2369. else:
  2370. self.on_fileopengcode(name=file_name)
  2371. return
  2372. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2373. for ext in grb_list:
  2374. proc_ext = ext.replace(' ', '')
  2375. proc_ext = '.%s' % proc_ext
  2376. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2377. file_name = str(argument)
  2378. if file_name == "":
  2379. if silent is False:
  2380. self.inform.emit(_("Open Gerber file failed."))
  2381. else:
  2382. self.on_fileopengerber(name=file_name)
  2383. return
  2384. # if it reached here without already returning then the app was registered with a file that it does not
  2385. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2386. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2387. # for arg in args_to_process:
  2388. # if 'FlatCAM.exe' in arg:
  2389. # continue
  2390. # else:
  2391. # sys.exit(2)
  2392. def set_ui_title(self, name):
  2393. """
  2394. Sets the title of the main window.
  2395. :param name: String that store the project path and project name
  2396. :return: None
  2397. """
  2398. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2399. (self.version,
  2400. ('BETA' if self.beta else ''),
  2401. platform.architecture()[0],
  2402. self.engine,
  2403. name)
  2404. )
  2405. def on_app_restart(self):
  2406. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2407. # be left in the SySTray
  2408. try:
  2409. self.trayIcon.hide()
  2410. except Exception as e:
  2411. log.debug("App.on_app_restart() --> %s" % str(e))
  2412. fcTranslate.restart_program(app=self)
  2413. def defaults_read_form(self):
  2414. """
  2415. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2416. :return: None
  2417. """
  2418. for option in self.defaults_form_fields:
  2419. try:
  2420. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2421. except Exception as e:
  2422. log.debug("App.defaults_read_form() --> %s" % str(e))
  2423. def defaults_write_form(self, factor=None, fl_units=None):
  2424. """
  2425. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2426. self.defaults dictionary.
  2427. :param factor: will apply a factor to the values that written in the GUI elements
  2428. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2429. :return: None
  2430. """
  2431. for option in self.defaults:
  2432. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2433. # try:
  2434. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2435. # except KeyError:
  2436. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2437. # # TODO: Rethink this?
  2438. # pass
  2439. def defaults_write_form_field(self, field, factor=None, units=None):
  2440. """
  2441. Basically it is the worker in the self.defaults_write_form()
  2442. :param field: the GUI element in Preferences GUI to be updated
  2443. :param factor: factor to be applied to the field parameter
  2444. :param units: current FLatCAM measuring units
  2445. :return: None, it updates GUI elements
  2446. """
  2447. try:
  2448. if factor is None:
  2449. if units is None:
  2450. self.defaults_form_fields[field].set_value(self.defaults[field])
  2451. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2452. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2453. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2454. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2455. else:
  2456. if units is None:
  2457. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2458. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2459. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2460. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2461. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2462. except KeyError:
  2463. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2464. # TODO: Rethink this?
  2465. pass
  2466. except AttributeError:
  2467. log.debug(field)
  2468. def clear_pool(self):
  2469. """
  2470. Clear the multiprocessing pool and calls garbage collector.
  2471. :return: None
  2472. """
  2473. self.pool.close()
  2474. self.pool = Pool()
  2475. self.pool_recreated.emit(self.pool)
  2476. gc.collect()
  2477. def install_tools(self):
  2478. """
  2479. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2480. Instantiation of the Tools classes.
  2481. The order that the tools are installed is important as they can depend on each other install position.
  2482. :return: None
  2483. """
  2484. self.dblsidedtool = DblSidedTool(self)
  2485. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2486. self.distance_tool = Distance(self)
  2487. self.distance_tool.install(icon=QtGui.QIcon('share/measure16.png'), pos=self.ui.menuedit,
  2488. before=self.ui.menueditorigin,
  2489. separator=False)
  2490. self.distance_min_tool = DistanceMin(self)
  2491. self.distance_min_tool.install(icon=QtGui.QIcon('share/measure16.png'), pos=self.ui.menuedit,
  2492. before=self.ui.menueditorigin,
  2493. separator=True)
  2494. self.panelize_tool = Panelize(self)
  2495. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2496. self.film_tool = Film(self)
  2497. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2498. self.paste_tool = SolderPaste(self)
  2499. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2500. self.calculator_tool = ToolCalculator(self)
  2501. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2502. self.sub_tool = ToolSub(self)
  2503. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2504. self.rules_tool = RulesCheck(self)
  2505. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2506. self.optimal_tool = ToolOptimal(self)
  2507. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2508. self.move_tool = ToolMove(self)
  2509. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2510. before=self.ui.menueditorigin, separator=True)
  2511. self.cutout_tool = CutOut(self)
  2512. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2513. before=self.sub_tool.menuAction)
  2514. self.ncclear_tool = NonCopperClear(self)
  2515. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2516. before=self.sub_tool.menuAction, separator=True)
  2517. self.paint_tool = ToolPaint(self)
  2518. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2519. before=self.sub_tool.menuAction, separator=True)
  2520. self.transform_tool = ToolTransform(self)
  2521. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2522. self.properties_tool = Properties(self)
  2523. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2524. self.pdf_tool = ToolPDF(self)
  2525. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2526. separator=True)
  2527. self.image_tool = ToolImage(self)
  2528. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2529. separator=True)
  2530. self.pcb_wizard_tool = PcbWizard(self)
  2531. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2532. self.log.debug("Tools are installed.")
  2533. def remove_tools(self):
  2534. """
  2535. Will remove all the actions in the Tool menu.
  2536. :return: None
  2537. """
  2538. for act in self.ui.menutool.actions():
  2539. self.ui.menutool.removeAction(act)
  2540. def init_tools(self):
  2541. """
  2542. Initialize the Tool tab in the notebook side of the central widget.
  2543. Remove the actions in the Tools menu.
  2544. Instantiate again the FlatCAM tools (plugins).
  2545. All this is required when changing the layout: standard, compact etc.
  2546. :return: None
  2547. """
  2548. log.debug("init_tools()")
  2549. # delete the data currently in the Tools Tab and the Tab itself
  2550. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2551. if widget is not None:
  2552. widget.deleteLater()
  2553. self.ui.notebook.removeTab(2)
  2554. # rebuild the Tools Tab
  2555. self.ui.tool_tab = QtWidgets.QWidget()
  2556. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2557. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2558. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2559. self.ui.tool_scroll_area = VerticalScrollArea()
  2560. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2561. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2562. # first remove all of them
  2563. self.remove_tools()
  2564. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2565. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2566. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2567. # third install all of them
  2568. self.install_tools()
  2569. self.log.debug("Tools are initialized.")
  2570. # def parse_system_fonts(self):
  2571. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2572. # 'params': []})
  2573. def connect_toolbar_signals(self):
  2574. """
  2575. Reconnect the signals to the actions in the toolbar.
  2576. This has to be done each time after the FlatCAM tools are removed/installed.
  2577. :return: None
  2578. """
  2579. # Toolbar
  2580. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2581. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2582. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2583. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2584. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2585. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2586. self.ui.replot_btn.triggered.connect(self.plot_all)
  2587. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2588. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2589. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2590. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2591. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2592. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2593. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2594. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2595. self.ui.delete_btn.triggered.connect(self.on_delete)
  2596. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2597. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2598. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2599. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2600. # Tools Toolbar Signals
  2601. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2602. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2603. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2604. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2605. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2606. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2607. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2608. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2609. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2610. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2611. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2612. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2613. def object2editor(self):
  2614. """
  2615. Send the current Geometry or Excellon object (if any) into the it's editor.
  2616. :return: None
  2617. """
  2618. self.report_usage("object2editor()")
  2619. edited_object = self.collection.get_active()
  2620. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2621. isinstance(edited_object, FlatCAMExcellon):
  2622. pass
  2623. else:
  2624. self.inform.emit('[WARNING_NOTCL] %s' %
  2625. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2626. return
  2627. if isinstance(edited_object, FlatCAMGeometry):
  2628. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2629. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2630. # we set the notebook to hidden
  2631. self.ui.splitter.setSizes([0, 1])
  2632. if edited_object.multigeo is True:
  2633. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2634. if len(edited_tools) > 1:
  2635. self.inform.emit('[WARNING_NOTCL] %s' %
  2636. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2637. "is not possible.\n"
  2638. "Edit only one geometry at a time."))
  2639. # determine the tool dia of the selected tool
  2640. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2641. # now find the key in the edited_object.tools that has this tooldia
  2642. multi_tool = 1
  2643. for tool in edited_object.tools:
  2644. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2645. multi_tool = tool
  2646. break
  2647. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2648. else:
  2649. self.geo_editor.edit_fcgeometry(edited_object)
  2650. # set call source to the Editor we go into
  2651. self.call_source = 'geo_editor'
  2652. elif isinstance(edited_object, FlatCAMExcellon):
  2653. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2654. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2655. if self.ui.splitter.sizes()[0] == 0:
  2656. self.ui.splitter.setSizes([1, 1])
  2657. self.exc_editor.edit_fcexcellon(edited_object)
  2658. # set call source to the Editor we go into
  2659. self.call_source = 'exc_editor'
  2660. elif isinstance(edited_object, FlatCAMGerber):
  2661. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2662. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2663. if self.ui.splitter.sizes()[0] == 0:
  2664. self.ui.splitter.setSizes([1, 1])
  2665. self.grb_editor.edit_fcgerber(edited_object)
  2666. # set call source to the Editor we go into
  2667. self.call_source = 'grb_editor'
  2668. # make sure that we can't select another object while in Editor Mode:
  2669. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2670. self.ui.project_frame.setDisabled(True)
  2671. # delete any selection shape that might be active as they are not relevant in Editor
  2672. self.delete_selection_shape()
  2673. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2674. self.ui.plot_tab_area.protectTab(0)
  2675. self.inform.emit('[WARNING_NOTCL] %s' %
  2676. _("Editor is activated ..."))
  2677. self.should_we_save = True
  2678. def editor2object(self, cleanup=None):
  2679. """
  2680. Transfers the Geometry or Excellon from it's editor to the current object.
  2681. :return: None
  2682. """
  2683. self.report_usage("editor2object()")
  2684. # do not update a geometry or excellon object unless it comes out of an editor
  2685. if self.call_source != 'app':
  2686. edited_obj = self.collection.get_active()
  2687. if cleanup is None:
  2688. msgbox = QtWidgets.QMessageBox()
  2689. msgbox.setText(_("Do you want to save the edited object?"))
  2690. msgbox.setWindowTitle(_("Close Editor"))
  2691. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2692. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2693. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2694. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2695. msgbox.setDefaultButton(bt_yes)
  2696. msgbox.exec_()
  2697. response = msgbox.clickedButton()
  2698. if response == bt_yes:
  2699. # clean the Tools Tab
  2700. self.ui.tool_scroll_area.takeWidget()
  2701. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2702. self.ui.notebook.setTabText(2, "Tool")
  2703. if isinstance(edited_obj, FlatCAMGeometry):
  2704. obj_type = "Geometry"
  2705. if cleanup is None:
  2706. self.geo_editor.update_fcgeometry(edited_obj)
  2707. self.geo_editor.update_options(edited_obj)
  2708. self.geo_editor.deactivate()
  2709. # update the geo object options so it is including the bounding box values
  2710. try:
  2711. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2712. edited_obj.options['xmin'] = xmin
  2713. edited_obj.options['ymin'] = ymin
  2714. edited_obj.options['xmax'] = xmax
  2715. edited_obj.options['ymax'] = ymax
  2716. except AttributeError as e:
  2717. self.inform.emit('[WARNING] %s' %
  2718. _("Object empty after edit."))
  2719. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2720. elif isinstance(edited_obj, FlatCAMGerber):
  2721. obj_type = "Gerber"
  2722. if cleanup is None:
  2723. self.grb_editor.update_fcgerber()
  2724. self.grb_editor.update_options(edited_obj)
  2725. self.grb_editor.deactivate_grb_editor()
  2726. # delete the old object (the source object) if it was an empty one
  2727. if len(edited_obj.solid_geometry) == 0:
  2728. old_name = edited_obj.options['name']
  2729. self.collection.set_active(old_name)
  2730. self.collection.delete_active()
  2731. # restore GUI to the Selected TAB
  2732. # Remove anything else in the GUI
  2733. self.ui.selected_scroll_area.takeWidget()
  2734. # Switch notebook to Selected page
  2735. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2736. elif isinstance(edited_obj, FlatCAMExcellon):
  2737. obj_type = "Excellon"
  2738. if cleanup is None:
  2739. self.exc_editor.update_fcexcellon(edited_obj)
  2740. self.exc_editor.update_options(edited_obj)
  2741. self.exc_editor.deactivate()
  2742. # delete the old object (the source object) if it was an empty one
  2743. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2744. old_name = edited_obj.options['name']
  2745. self.collection.set_active(old_name)
  2746. self.collection.delete_active()
  2747. # restore GUI to the Selected TAB
  2748. # Remove anything else in the GUI
  2749. self.ui.tool_scroll_area.takeWidget()
  2750. # Switch notebook to Selected page
  2751. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2752. else:
  2753. self.inform.emit('[WARNING_NOTCL] %s' %
  2754. _("Select a Gerber, Geometry or Excellon Object to update."))
  2755. return
  2756. self.inform.emit('[selected] %s %s' %
  2757. (obj_type, _("is updated, returning to App...")))
  2758. elif response == bt_no:
  2759. # clean the Tools Tab
  2760. self.ui.tool_scroll_area.takeWidget()
  2761. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2762. self.ui.notebook.setTabText(2, "Tool")
  2763. if isinstance(edited_obj, FlatCAMGeometry):
  2764. self.geo_editor.deactivate()
  2765. elif isinstance(edited_obj, FlatCAMGerber):
  2766. self.grb_editor.deactivate_grb_editor()
  2767. elif isinstance(edited_obj, FlatCAMExcellon):
  2768. self.exc_editor.deactivate()
  2769. # set focus on the project tab
  2770. else:
  2771. self.inform.emit('[WARNING_NOTCL] %s' %
  2772. _("Select a Gerber, Geometry or Excellon Object to update."))
  2773. return
  2774. edited_obj.set_ui(edited_obj.ui_type())
  2775. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2776. elif response == bt_cancel:
  2777. return
  2778. else:
  2779. if isinstance(edited_obj, FlatCAMGeometry):
  2780. self.geo_editor.deactivate()
  2781. elif isinstance(edited_obj, FlatCAMGerber):
  2782. self.grb_editor.deactivate_grb_editor()
  2783. elif isinstance(edited_obj, FlatCAMExcellon):
  2784. self.exc_editor.deactivate()
  2785. else:
  2786. self.inform.emit('[WARNING_NOTCL] %s' %
  2787. _("Select a Gerber, Geometry or Excellon Object to update."))
  2788. return
  2789. # if notebook is hidden we show it
  2790. if self.ui.splitter.sizes()[0] == 0:
  2791. self.ui.splitter.setSizes([1, 1])
  2792. # restore the call_source to app
  2793. self.call_source = 'app'
  2794. edited_obj.plot()
  2795. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2796. self.ui.plot_tab_area.protectTab(0)
  2797. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2798. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2799. self.ui.project_frame.setDisabled(False)
  2800. def get_last_folder(self):
  2801. """
  2802. Get the folder path from where the last file was opened.
  2803. :return: String, last opened folder path
  2804. """
  2805. return self.defaults["global_last_folder"]
  2806. def get_last_save_folder(self):
  2807. """
  2808. Get the folder path from where the last file was saved.
  2809. :return: String, last saved folder path
  2810. """
  2811. loc = self.defaults["global_last_save_folder"]
  2812. if loc is None:
  2813. loc = self.defaults["global_last_folder"]
  2814. if loc is None:
  2815. loc = os.path.dirname(__file__)
  2816. return loc
  2817. def report_usage(self, resource):
  2818. """
  2819. Increments usage counter for the given resource
  2820. in self.defaults['global_stats'].
  2821. :param resource: Name of the resource.
  2822. :return: None
  2823. """
  2824. if resource in self.defaults['global_stats']:
  2825. self.defaults['global_stats'][resource] += 1
  2826. else:
  2827. self.defaults['global_stats'][resource] = 1
  2828. def init_tcl(self):
  2829. """
  2830. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2831. :return: None
  2832. """
  2833. if hasattr(self, 'tcl'):
  2834. # self.tcl = None
  2835. # TODO we need to clean non default variables and procedures here
  2836. # new object cannot be used here as it will not remember values created for next passes,
  2837. # because tcl was execudted in old instance of TCL
  2838. pass
  2839. else:
  2840. self.tcl = tk.Tcl()
  2841. self.setup_shell()
  2842. self.log.debug("TCL Shell has been initialized.")
  2843. # TODO: This shouldn't be here.
  2844. class TclErrorException(Exception):
  2845. """
  2846. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2847. """
  2848. pass
  2849. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2850. """
  2851. Shows a message on the FlatCAM Shell
  2852. :param msg: Message to display.
  2853. :param show: Opens the shell.
  2854. :param error: Shows the message as an error.
  2855. :param warning: Shows the message as an warning.
  2856. :param success: Shows the message as an success.
  2857. :param selected: Indicate that something was selected on canvas
  2858. :return: None
  2859. """
  2860. if show:
  2861. self.ui.shell_dock.show()
  2862. try:
  2863. if error:
  2864. self.shell.append_error(msg + "\n")
  2865. elif warning:
  2866. self.shell.append_warning(msg + "\n")
  2867. elif success:
  2868. self.shell.append_success(msg + "\n")
  2869. elif selected:
  2870. self.shell.append_selected(msg + "\n")
  2871. else:
  2872. self.shell.append_output(msg + "\n")
  2873. except AttributeError:
  2874. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2875. def raise_tcl_unknown_error(self, unknownException):
  2876. """
  2877. Raise exception if is different type than TclErrorException
  2878. this is here mainly to show unknown errors inside TCL shell console.
  2879. :param unknownException:
  2880. :return:
  2881. """
  2882. if not isinstance(unknownException, self.TclErrorException):
  2883. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2884. else:
  2885. raise unknownException
  2886. def display_tcl_error(self, error, error_info=None):
  2887. """
  2888. Escape bracket [ with '\' otherwise there is error
  2889. "ERROR: missing close-bracket" instead of real error
  2890. :param error: it may be text or exception
  2891. :param error_info: Some informations about the error
  2892. :return: None
  2893. """
  2894. if isinstance(error, Exception):
  2895. exc_type, exc_value, exc_traceback = error_info
  2896. if not isinstance(error, self.TclErrorException):
  2897. show_trace = 1
  2898. else:
  2899. show_trace = int(self.defaults['global_verbose_error_level'])
  2900. if show_trace > 0:
  2901. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2902. trc_formated = []
  2903. for a in reversed(trc):
  2904. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2905. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2906. else:
  2907. text = "%s" % error
  2908. else:
  2909. text = error
  2910. text = text.replace('[', '\\[').replace('"', '\\"')
  2911. self.tcl.eval('return -code error "%s"' % text)
  2912. def raise_tcl_error(self, text):
  2913. """
  2914. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2915. :param text: text of error
  2916. :return: raise exception
  2917. """
  2918. self.display_tcl_error(text)
  2919. raise self.TclErrorException(text)
  2920. def exec_command(self, text, no_echo=False):
  2921. """
  2922. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2923. Also handles execution in separated threads
  2924. :param text: FlatCAM TclCommand with parameters
  2925. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2926. will create crashes of the _Expandable_Edit widget
  2927. :return: output if there was any
  2928. """
  2929. self.report_usage('exec_command')
  2930. result = self.exec_command_test(text, False, no_echo=no_echo)
  2931. # MS: added this method call so the geometry is updated once the TCL command is executed
  2932. # if no_plot is None:
  2933. # self.plot_all()
  2934. return result
  2935. def exec_command_test(self, text, reraise=True, no_echo=False):
  2936. """
  2937. Same as exec_command(...) with additional control over exceptions.
  2938. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2939. :param text: Input command
  2940. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2941. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2942. will create crashes of the _Expandable_Edit widget
  2943. :return: Output from the command
  2944. """
  2945. tcl_command_string = str(text)
  2946. try:
  2947. if no_echo is False:
  2948. self.shell.open_proccessing() # Disables input box.
  2949. result = self.tcl.eval(str(tcl_command_string))
  2950. if result != 'None' and no_echo is False:
  2951. self.shell.append_output(result + '\n')
  2952. except tk.TclError as e:
  2953. # This will display more precise answer if something in TCL shell fails
  2954. result = self.tcl.eval("set errorInfo")
  2955. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2956. if no_echo is False:
  2957. self.shell.append_error('ERROR: ' + result + '\n')
  2958. # Show error in console and just return or in test raise exception
  2959. if reraise:
  2960. raise e
  2961. finally:
  2962. if no_echo is False:
  2963. self.shell.close_proccessing()
  2964. pass
  2965. return result
  2966. # """
  2967. # Code below is unsused. Saved for later.
  2968. # """
  2969. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2970. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2971. # self.log.debug(parts)
  2972. # try:
  2973. # if parts[0] not in commands:
  2974. # self.shell.append_error("Unknown command\n")
  2975. # return
  2976. #
  2977. # #import inspect
  2978. # #inspect.getargspec(someMethod)
  2979. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2980. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2981. # self.shell.append_error(
  2982. # "Command %s takes %d arguments. %d given.\n" %
  2983. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2984. # )
  2985. # return
  2986. #
  2987. # cmdfcn = commands[parts[0]]["fcn"]
  2988. # cmdconv = commands[parts[0]]["converters"]
  2989. # if len(parts) - 1 > 0:
  2990. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2991. # else:
  2992. # retval = cmdfcn()
  2993. # retfcn = commands[parts[0]]["retfcn"]
  2994. # if retval and retfcn(retval):
  2995. # self.shell.append_output(retfcn(retval) + "\n")
  2996. #
  2997. # except Exception as e:
  2998. # #self.shell.append_error(''.join(traceback.format_exc()))
  2999. # #self.shell.append_error("?\n")
  3000. # self.shell.append_error(str(e) + "\n")
  3001. def info(self, msg):
  3002. """
  3003. Informs the user. Normally on the status bar, optionally
  3004. also on the shell.
  3005. :param msg: Text to write.
  3006. :return: None
  3007. """
  3008. # Type of message in brackets at the beginning of the message.
  3009. match = re.search("\[([^\]]+)\](.*)", msg)
  3010. if match:
  3011. level = match.group(1)
  3012. msg_ = match.group(2)
  3013. self.ui.fcinfo.set_status(str(msg_), level=level)
  3014. if level.lower() == "error":
  3015. self.shell_message(msg, error=True, show=True)
  3016. elif level.lower() == "warning":
  3017. self.shell_message(msg, warning=True, show=True)
  3018. elif level.lower() == "error_notcl":
  3019. self.shell_message(msg, error=True, show=False)
  3020. elif level.lower() == "warning_notcl":
  3021. self.shell_message(msg, warning=True, show=False)
  3022. elif level.lower() == "success":
  3023. self.shell_message(msg, success=True, show=False)
  3024. elif level.lower() == "selected":
  3025. self.shell_message(msg, selected=True, show=False)
  3026. else:
  3027. self.shell_message(msg, show=False)
  3028. else:
  3029. self.ui.fcinfo.set_status(str(msg), level="info")
  3030. # make sure that if the message is to clear the infobar with a space
  3031. # is not printed over and over on the shell
  3032. if msg != '':
  3033. self.shell_message(msg)
  3034. def restore_toolbar_view(self):
  3035. """
  3036. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3037. was saved in the defaults dictionary.
  3038. :return: None
  3039. """
  3040. tb = self.defaults["global_toolbar_view"]
  3041. if tb & 1:
  3042. self.ui.toolbarfile.setVisible(True)
  3043. else:
  3044. self.ui.toolbarfile.setVisible(False)
  3045. if tb & 2:
  3046. self.ui.toolbargeo.setVisible(True)
  3047. else:
  3048. self.ui.toolbargeo.setVisible(False)
  3049. if tb & 4:
  3050. self.ui.toolbarview.setVisible(True)
  3051. else:
  3052. self.ui.toolbarview.setVisible(False)
  3053. if tb & 8:
  3054. self.ui.toolbartools.setVisible(True)
  3055. else:
  3056. self.ui.toolbartools.setVisible(False)
  3057. if tb & 16:
  3058. self.ui.exc_edit_toolbar.setVisible(True)
  3059. else:
  3060. self.ui.exc_edit_toolbar.setVisible(False)
  3061. if tb & 32:
  3062. self.ui.geo_edit_toolbar.setVisible(True)
  3063. else:
  3064. self.ui.geo_edit_toolbar.setVisible(False)
  3065. if tb & 64:
  3066. self.ui.grb_edit_toolbar.setVisible(True)
  3067. else:
  3068. self.ui.grb_edit_toolbar.setVisible(False)
  3069. if tb & 128:
  3070. self.ui.snap_toolbar.setVisible(True)
  3071. else:
  3072. self.ui.snap_toolbar.setVisible(False)
  3073. if tb & 256:
  3074. self.ui.toolbarshell.setVisible(True)
  3075. else:
  3076. self.ui.toolbarshell.setVisible(False)
  3077. def load_defaults(self, filename):
  3078. """
  3079. Loads the aplication's default settings from current_defaults.FlatConfig into
  3080. ``self.defaults``.
  3081. :return: None
  3082. """
  3083. try:
  3084. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3085. options = f.read()
  3086. f.close()
  3087. except IOError:
  3088. self.log.error("Could not load defaults file.")
  3089. self.inform.emit('[ERROR] %s' %
  3090. _("Could not load defaults file."))
  3091. # in case the defaults file can't be loaded, show all toolbars
  3092. self.defaults["global_toolbar_view"] = 511
  3093. return
  3094. try:
  3095. defaults = json.loads(options)
  3096. except:
  3097. # in case the defaults file can't be loaded, show all toolbars
  3098. self.defaults["global_toolbar_view"] = 511
  3099. e = sys.exc_info()[0]
  3100. App.log.error(str(e))
  3101. self.inform.emit('[ERROR] %s' %
  3102. _("Failed to parse defaults file."))
  3103. return
  3104. self.defaults.update(defaults)
  3105. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3106. # restore the toolbar view
  3107. self.restore_toolbar_view()
  3108. def on_import_preferences(self):
  3109. """
  3110. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3111. ``self.defaults``.
  3112. :return: None
  3113. """
  3114. self.report_usage("on_import_preferences")
  3115. App.log.debug("on_import_preferences()")
  3116. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3117. try:
  3118. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3119. directory=self.data_path,
  3120. filter=filter_)
  3121. except TypeError:
  3122. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3123. filter=filter_)
  3124. filename = str(filename)
  3125. if filename == "":
  3126. self.inform.emit('[WARNING_NOTCL] %s' %
  3127. _("FlatCAM preferences import cancelled."))
  3128. else:
  3129. try:
  3130. f = open(filename)
  3131. options = f.read()
  3132. f.close()
  3133. except IOError:
  3134. self.log.error("Could not load defaults file.")
  3135. self.inform.emit('[ERROR_NOTCL] %s' %
  3136. _("Could not load defaults file."))
  3137. return
  3138. try:
  3139. defaults_from_file = json.loads(options)
  3140. except Exception as e:
  3141. e = sys.exc_info()[0]
  3142. App.log.error(str(e))
  3143. self.inform.emit('[ERROR_NOTCL] %s' %
  3144. _("Failed to parse defaults file."))
  3145. return
  3146. self.defaults.update(defaults_from_file)
  3147. self.on_preferences_edited()
  3148. self.inform.emit('[success] %s: %s' %
  3149. (_("Imported Defaults from"), filename))
  3150. def on_export_preferences(self):
  3151. """
  3152. Save the defaults dictionary to a file.
  3153. :return: None
  3154. """
  3155. self.report_usage("on_export_preferences")
  3156. App.log.debug("on_export_preferences()")
  3157. defaults_file_content = None
  3158. self.date = str(datetime.today()).rpartition('.')[0]
  3159. self.date = ''.join(c for c in self.date if c not in ':-')
  3160. self.date = self.date.replace(' ', '_')
  3161. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3162. try:
  3163. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3164. caption=_("Export FlatCAM Preferences"),
  3165. directory=self.data_path + '/preferences_' + self.date,
  3166. filter=filter__
  3167. )
  3168. except TypeError:
  3169. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3170. filter=filter__)
  3171. filename = str(filename)
  3172. defaults_from_file = {}
  3173. if filename == "":
  3174. self.inform.emit('[WARNING_NOTCL] %s' %
  3175. _("FlatCAM preferences export cancelled."))
  3176. return
  3177. else:
  3178. try:
  3179. f = open(filename, 'w')
  3180. defaults_file_content = f.read()
  3181. f.close()
  3182. except PermissionError:
  3183. self.inform.emit('[WARNING] %s' %
  3184. _("Permission denied, saving not possible.\n"
  3185. "Most likely another app is holding the file open and not accessible."))
  3186. return
  3187. except IOError:
  3188. App.log.debug('Creating a new preferences file ...')
  3189. f = open(filename, 'w')
  3190. json.dump({}, f)
  3191. f.close()
  3192. except:
  3193. e = sys.exc_info()[0]
  3194. App.log.error("Could not load defaults file.")
  3195. App.log.error(str(e))
  3196. self.inform.emit('[ERROR_NOTCL] %s' %
  3197. _("Could not load preferences file."))
  3198. return
  3199. try:
  3200. defaults_from_file = json.loads(defaults_file_content)
  3201. except:
  3202. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3203. # Update options
  3204. self.defaults_read_form()
  3205. defaults_from_file.update(self.defaults)
  3206. self.propagate_defaults(silent=True)
  3207. # Save update options
  3208. try:
  3209. f = open(filename, "w")
  3210. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3211. f.close()
  3212. except:
  3213. self.inform.emit('[ERROR_NOTCL] %s' %
  3214. _("Failed to write defaults to file."))
  3215. return
  3216. if self.defaults["global_open_style"] is False:
  3217. self.file_opened.emit("preferences", filename)
  3218. self.file_saved.emit("preferences", filename)
  3219. self.inform.emit('[success] %s: %s' %
  3220. (_("Exported preferences to"), filename))
  3221. def on_preferences_open_folder(self):
  3222. """
  3223. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3224. :return: None
  3225. """
  3226. self.report_usage("on_preferences_open_folder()")
  3227. if sys.platform == 'win32':
  3228. subprocess.Popen('explorer %s' % self.data_path)
  3229. elif sys.platform == 'darwin':
  3230. os.system('open "%s"' % self.data_path)
  3231. else:
  3232. subprocess.Popen(['xdg-open', self.data_path])
  3233. self.inform.emit('[success] %s' %
  3234. _("FlatCAM Preferences Folder opened."))
  3235. def save_geometry(self, x, y, width, height, notebook_width):
  3236. """
  3237. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3238. launch of the application.
  3239. :param x: X position of the main window
  3240. :param y: Y position of the main window
  3241. :param width: width of the main window
  3242. :param height: height of the main window
  3243. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3244. :return: None
  3245. """
  3246. self.defaults["global_def_win_x"] = x
  3247. self.defaults["global_def_win_y"] = y
  3248. self.defaults["global_def_win_w"] = width
  3249. self.defaults["global_def_win_h"] = height
  3250. self.defaults["global_def_notebook_width"] = notebook_width
  3251. self.save_defaults()
  3252. def restore_main_win_geom(self):
  3253. try:
  3254. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3255. self.defaults["global_def_win_y"],
  3256. self.defaults["global_def_win_w"],
  3257. self.defaults["global_def_win_h"])
  3258. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3259. except KeyError as e:
  3260. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3261. def message_dialog(self, title, message, kind="info"):
  3262. """
  3263. Builds and show a custom QMessageBox to be used in FlatCAM.
  3264. :param title: title of the QMessageBox
  3265. :param message: message to be displayed
  3266. :param kind: type of QMessageBox; will display a specific icon.
  3267. :return:
  3268. """
  3269. icon = {"info": QtWidgets.QMessageBox.Information,
  3270. "warning": QtWidgets.QMessageBox.Warning,
  3271. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3272. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3273. dlg.setText(message)
  3274. dlg.exec_()
  3275. def register_recent(self, kind, filename):
  3276. """
  3277. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3278. dictionary.
  3279. :param kind: type of file that was opened
  3280. :param filename: the path and file name for the file that was opened
  3281. :return:
  3282. """
  3283. self.log.debug("register_recent()")
  3284. self.log.debug(" %s" % kind)
  3285. self.log.debug(" %s" % filename)
  3286. record = {'kind': str(kind), 'filename': str(filename)}
  3287. if record in self.recent:
  3288. return
  3289. if record in self.recent_projects:
  3290. return
  3291. if record['kind'] == 'project':
  3292. self.recent_projects.insert(0, record)
  3293. else:
  3294. self.recent.insert(0, record)
  3295. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3296. self.recent.pop()
  3297. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3298. self.recent_projects.pop()
  3299. try:
  3300. f = open(self.data_path + '/recent.json', 'w')
  3301. except IOError:
  3302. App.log.error("Failed to open recent items file for writing.")
  3303. self.inform.emit('[ERROR_NOTCL] %s' %
  3304. _('Failed to open recent files file for writing.'))
  3305. return
  3306. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3307. f.close()
  3308. try:
  3309. fp = open(self.data_path + '/recent_projects.json', 'w')
  3310. except IOError:
  3311. App.log.error("Failed to open recent items file for writing.")
  3312. self.inform.emit('[ERROR_NOTCL] %s' %
  3313. _('Failed to open recent projects file for writing.'))
  3314. return
  3315. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3316. fp.close()
  3317. # Re-build the recent items menu
  3318. self.setup_recent_items()
  3319. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3320. """
  3321. Creates a new specialized FlatCAMObj and attaches it to the application,
  3322. this is, updates the GUI accordingly, any other records and plots it.
  3323. This method is thread-safe.
  3324. Notes:
  3325. * If the name is in use, the self.collection will modify it
  3326. when appending it to the collection. There is no need to handle
  3327. name conflicts here.
  3328. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3329. :type kind: str
  3330. :param name: Name for the object.
  3331. :type name: str
  3332. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3333. The function is called with 2 parameters: the new object and the App instance.
  3334. :type initialize: function
  3335. :param active:
  3336. :param fit:
  3337. :param plot: If to plot the resulting object
  3338. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3339. self.colleaction
  3340. :return: None
  3341. :rtype: None
  3342. """
  3343. App.log.debug("new_object()")
  3344. obj_plot = plot
  3345. obj_autoselected = autoselected
  3346. t0 = time.time() # Debug
  3347. # ## Create object
  3348. classdict = {
  3349. "gerber": FlatCAMGerber,
  3350. "excellon": FlatCAMExcellon,
  3351. "cncjob": FlatCAMCNCjob,
  3352. "geometry": FlatCAMGeometry,
  3353. "script": FlatCAMScript,
  3354. "document": FlatCAMDocument
  3355. }
  3356. App.log.debug("Calling object constructor...")
  3357. obj = classdict[kind](name)
  3358. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3359. # Set options from "Project options" form
  3360. self.options_read_form()
  3361. # IMPORTANT
  3362. # The key names in defaults and options dictionary's are not random:
  3363. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3364. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3365. # the options from project options form into the self.options. After that, below, depending on the type of
  3366. # object that is created, it will strip the name of the object and the underline (if the original key was
  3367. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3368. # "toolchange"
  3369. for option in self.options:
  3370. if option.find(kind + "_") == 0:
  3371. oname = option[len(kind) + 1:]
  3372. obj.options[oname] = self.options[option]
  3373. obj.isHovering = False
  3374. obj.notHovering = True
  3375. # Initialize as per user request
  3376. # User must take care to implement initialize
  3377. # in a thread-safe way as is is likely that we
  3378. # have been invoked in a separate thread.
  3379. t1 = time.time()
  3380. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3381. try:
  3382. return_value = initialize(obj, self)
  3383. except Exception as e:
  3384. msg = '[ERROR_NOTCL] %s' % \
  3385. _("An internal error has ocurred. See shell.\n")
  3386. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3387. msg += traceback.format_exc()
  3388. self.inform.emit(msg)
  3389. # if str(e) == "Empty Geometry":
  3390. # self.inform.emit("[ERROR_NOTCL] )
  3391. # else:
  3392. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3393. return "fail"
  3394. t2 = time.time()
  3395. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3396. if return_value == 'fail':
  3397. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3398. return "fail"
  3399. # Check units and convert if necessary
  3400. # This condition CAN be true because initialize() can change obj.units
  3401. if self.options["units"].upper() != obj.units.upper():
  3402. self.inform.emit('%s: %s' %
  3403. (_("Converting units to "), self.options["units"]))
  3404. obj.convert_units(self.options["units"])
  3405. t3 = time.time()
  3406. self.log.debug("%f seconds converting units." % (t3 - t2))
  3407. # Create the bounding box for the object and then add the results to the obj.options
  3408. # But not for Scripts or for Documents
  3409. if kind != 'document' and kind != 'script':
  3410. try:
  3411. xmin, ymin, xmax, ymax = obj.bounds()
  3412. obj.options['xmin'] = xmin
  3413. obj.options['ymin'] = ymin
  3414. obj.options['xmax'] = xmax
  3415. obj.options['ymax'] = ymax
  3416. except Exception as e:
  3417. log.warning("The object has no bounds properties. %s" % str(e))
  3418. return "fail"
  3419. # update the KeyWords list with the name of the file
  3420. self.myKeywords.append(obj.options['name'])
  3421. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3422. # Move the object to the main thread and let the app know that it is available.
  3423. obj.moveToThread(self.main_thread)
  3424. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3425. return obj
  3426. def new_excellon_object(self):
  3427. """
  3428. Creates a new, blank Excellon object.
  3429. :return: None
  3430. """
  3431. self.report_usage("new_excellon_object()")
  3432. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3433. def new_geometry_object(self):
  3434. """
  3435. Creates a new, blank and single-tool Geometry object.
  3436. :return: None
  3437. """
  3438. self.report_usage("new_geometry_object()")
  3439. def initialize(obj, self):
  3440. obj.multitool = False
  3441. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3442. def new_gerber_object(self):
  3443. """
  3444. Creates a new, blank Gerber object.
  3445. :return: None
  3446. """
  3447. self.report_usage("new_gerber_object()")
  3448. def initialize(grb_obj, self):
  3449. grb_obj.multitool = False
  3450. grb_obj.source_file = []
  3451. grb_obj.multigeo = False
  3452. grb_obj.follow = False
  3453. grb_obj.apertures = {}
  3454. grb_obj.solid_geometry = []
  3455. try:
  3456. grb_obj.options['xmin'] = 0
  3457. grb_obj.options['ymin'] = 0
  3458. grb_obj.options['xmax'] = 0
  3459. grb_obj.options['ymax'] = 0
  3460. except KeyError:
  3461. pass
  3462. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3463. def new_script_object(self, name=None, text=None):
  3464. """
  3465. Creates a new, blank TCL Script object.
  3466. :param name: a name for the new object
  3467. :return: None
  3468. """
  3469. self.report_usage("new_script_object()")
  3470. if text is not None:
  3471. new_source_file = text
  3472. else:
  3473. new_source_file = _(
  3474. "#\n"
  3475. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  3476. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  3477. "#\n\n"
  3478. "# FlatCAM commands list:\n"
  3479. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, "
  3480. "ClearCopper,\n"
  3481. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, "
  3482. "GetNames,\n"
  3483. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  3484. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  3485. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, "
  3486. "SubtractPoly,\n"
  3487. "# SubtractRectangle, Version, WriteGCode\n"
  3488. "#\n\n"
  3489. )
  3490. def initialize(obj, self):
  3491. obj.source_file = deepcopy(new_source_file)
  3492. if name is None:
  3493. outname = 'new_script'
  3494. else:
  3495. outname = name
  3496. self.new_object('script', outname, initialize, plot=False)
  3497. def new_document_object(self):
  3498. """
  3499. Creates a new, blank Document object.
  3500. :return: None
  3501. """
  3502. self.report_usage("new_document_object()")
  3503. def initialize(obj, self):
  3504. obj.source_file = ""
  3505. self.new_object('document', 'new_document', initialize, plot=False)
  3506. def on_object_created(self, obj, plot, autoselect):
  3507. """
  3508. Event callback for object creation.
  3509. It will add the new object to the collection. After that it will plot the object in a threaded way
  3510. :param obj: The newly created FlatCAM object.
  3511. :param plot: if the newly create object t obe plotted
  3512. :param autoselect: if the newly created object to be autoselected after creation
  3513. :return: None
  3514. """
  3515. t0 = time.time() # DEBUG
  3516. self.log.debug("on_object_created()")
  3517. # The Collection might change the name if there is a collision
  3518. self.collection.append(obj)
  3519. # after adding the object to the collection always update the list of objects that are in the collection
  3520. self.all_objects_list = self.collection.get_list()
  3521. # self.inform.emit('[selected] %s created & selected: %s' %
  3522. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3523. if obj.kind == 'gerber':
  3524. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3525. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3526. elif obj.kind == 'excellon':
  3527. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3528. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3529. elif obj.kind == 'cncjob':
  3530. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3531. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3532. elif obj.kind == 'geometry':
  3533. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3534. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3535. elif obj.kind == 'script':
  3536. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3537. kind=obj.kind.capitalize(), color='orange', name=str(obj.options['name'])))
  3538. elif obj.kind == 'document':
  3539. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3540. kind=obj.kind.capitalize(), color='darkCyan', name=str(obj.options['name'])))
  3541. # update the SHELL auto-completer model with the name of the new object
  3542. self.shell._edit.set_model_data(self.myKeywords)
  3543. if autoselect:
  3544. # select the just opened object but deselect the previous ones
  3545. self.collection.set_all_inactive()
  3546. self.collection.set_active(obj.options["name"])
  3547. else:
  3548. self.collection.set_all_inactive()
  3549. # here it is done the object plotting
  3550. def worker_task(t_obj):
  3551. with self.proc_container.new(_("Plotting")):
  3552. if isinstance(t_obj, FlatCAMCNCjob):
  3553. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3554. else:
  3555. t_obj.plot()
  3556. t1 = time.time() # DEBUG
  3557. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3558. self.object_plotted.emit(t_obj)
  3559. # Send to worker
  3560. # self.worker.add_task(worker_task, [self])
  3561. if plot is True:
  3562. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3563. def on_object_changed(self, obj):
  3564. """
  3565. Called whenever the geometry of the object was changed in some way.
  3566. This require the update of it's bounding values so it can be the selected on canvas.
  3567. Update the bounding box data from obj.options
  3568. :param obj: the object that was changed
  3569. :return: None
  3570. """
  3571. xmin, ymin, xmax, ymax = obj.bounds()
  3572. obj.options['xmin'] = xmin
  3573. obj.options['ymin'] = ymin
  3574. obj.options['xmax'] = xmax
  3575. obj.options['ymax'] = ymax
  3576. log.debug("Object changed, updating the bounding box data on self.options")
  3577. # delete the old selection shape
  3578. self.delete_selection_shape()
  3579. self.should_we_save = True
  3580. def on_object_plotted(self, obj):
  3581. """
  3582. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3583. :param obj: object to be fit into view
  3584. :return: None
  3585. """
  3586. self.on_zoom_fit(None)
  3587. def options_read_form(self):
  3588. """
  3589. Same as it's equivalent from the defaults.
  3590. self.options use to store the preferences per project. No longer used.
  3591. :return: None
  3592. """
  3593. for option in self.options_form_fields:
  3594. self.options[option] = self.options_form_fields[option].get_value()
  3595. def options_write_form(self):
  3596. """
  3597. Same as it's equivalent from the defaults.
  3598. self.options use to store the preferences per project. No longer used.
  3599. :return: None
  3600. """
  3601. for option in self.options:
  3602. self.options_write_form_field(option)
  3603. def options_write_form_field(self, field):
  3604. """
  3605. Same as it's equivalent from the defaults.
  3606. self.options use to store the preferences per project. No longer used.
  3607. :return: None
  3608. """
  3609. try:
  3610. self.options_form_fields[field].set_value(self.options[field])
  3611. except KeyError:
  3612. # Changed from error to debug. This allows to have data stored
  3613. # which is not user-editable.
  3614. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3615. pass
  3616. def on_about(self):
  3617. """
  3618. Displays the "about" dialog found in the Menu --> Help.
  3619. :return: None
  3620. """
  3621. self.report_usage("on_about")
  3622. version = self.version
  3623. version_date = self.version_date
  3624. beta = self.beta
  3625. class AboutDialog(QtWidgets.QDialog):
  3626. def __init__(self, parent=None):
  3627. QtWidgets.QDialog.__init__(self, parent)
  3628. # Icon and title
  3629. self.setWindowIcon(parent.app_icon)
  3630. self.setWindowTitle(_("About FlatCAM"))
  3631. self.resize(600, 200)
  3632. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3633. # self.setStyleSheet(
  3634. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3635. # "background-attachment: fixed"
  3636. # )
  3637. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3638. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3639. # palette = QtGui.QPalette()
  3640. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3641. # self.setPalette(palette)
  3642. logo = QtWidgets.QLabel()
  3643. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3644. title = QtWidgets.QLabel(
  3645. "<font size=8><B>FlatCAM</B></font><BR>"
  3646. "{title}<BR>"
  3647. "<BR>"
  3648. "<BR>"
  3649. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3650. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3651. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3652. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3653. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3654. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3655. "<B>{issue}</B></a><BR>".format(
  3656. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3657. devel=_("Development"),
  3658. down=_("DOWNLOAD"),
  3659. issue=_("Issue tracker"))
  3660. )
  3661. title.setOpenExternalLinks(True)
  3662. closebtn = QtWidgets.QPushButton(_("Close"))
  3663. tab_widget = QtWidgets.QTabWidget()
  3664. description_label = QtWidgets.QLabel(
  3665. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3666. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3667. version=version,
  3668. beta=('BETA' if beta else ''),
  3669. date=version_date,
  3670. arch=platform.architecture()[0])
  3671. )
  3672. description_label.setOpenExternalLinks(True)
  3673. license_label = QtWidgets.QLabel(
  3674. _(
  3675. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3676. 'Licensed under the MIT license:\n'
  3677. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3678. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3679. 'of this software and associated documentation files (the "Software"), to deal\n'
  3680. 'in the Software without restriction, including without limitation the rights\n'
  3681. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3682. 'copies of the Software, and to permit persons to whom the Software is\n'
  3683. ' furnished to do so, subject to the following conditions:\n\n'
  3684. 'The above copyright notice and this permission notice shall be included in\n'
  3685. 'all copies or substantial portions of the Software.\n\n'
  3686. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3687. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3688. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3689. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3690. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3691. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3692. 'THE SOFTWARE.'
  3693. )
  3694. )
  3695. license_label.setOpenExternalLinks(True)
  3696. # layouts
  3697. layout1 = QtWidgets.QVBoxLayout()
  3698. layout1_1 = QtWidgets.QHBoxLayout()
  3699. layout1_2 = QtWidgets.QHBoxLayout()
  3700. layout2 = QtWidgets.QHBoxLayout()
  3701. layout3 = QtWidgets.QHBoxLayout()
  3702. self.setLayout(layout1)
  3703. layout1.addLayout(layout1_1)
  3704. layout1.addLayout(layout1_2)
  3705. layout1.addLayout(layout2)
  3706. layout1.addLayout(layout3)
  3707. layout1_1.addStretch()
  3708. layout1_1.addWidget(description_label)
  3709. layout1_2.addWidget(tab_widget)
  3710. self.splash_tab = QtWidgets.QWidget()
  3711. self.splash_tab.setObjectName("splash_about")
  3712. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3713. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3714. tab_widget.addTab(self.splash_tab, _("Splash"))
  3715. self.programmmers_tab = QtWidgets.QWidget()
  3716. self.programmmers_tab.setObjectName("programmers_about")
  3717. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3718. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3719. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3720. self.translators_tab = QtWidgets.QWidget()
  3721. self.translators_tab.setObjectName("translators_about")
  3722. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3723. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3724. tab_widget.addTab(self.translators_tab, _("Translators"))
  3725. self.license_tab = QtWidgets.QWidget()
  3726. self.license_tab.setObjectName("license_about")
  3727. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3728. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3729. tab_widget.addTab(self.license_tab, _("License"))
  3730. self.splash_tab_layout.addWidget(logo, stretch=0)
  3731. self.splash_tab_layout.addWidget(title, stretch=1)
  3732. pal = QtGui.QPalette()
  3733. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3734. self.prog_form_lay = QtWidgets.QFormLayout()
  3735. self.prog_form_lay.setHorizontalSpacing(20)
  3736. prog_widget = QtWidgets.QWidget()
  3737. prog_widget.setLayout(self.prog_form_lay)
  3738. prog_scroll = QtWidgets.QScrollArea()
  3739. prog_scroll.setWidget(prog_widget)
  3740. prog_scroll.setWidgetResizable(True)
  3741. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3742. prog_scroll.setPalette(pal)
  3743. self.programmmers_tab_layout.addWidget(prog_scroll)
  3744. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3745. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3746. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3747. QtWidgets.QLabel('%s' % _("Program Author")))
  3748. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3749. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3750. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3751. QtWidgets.QLabel('%s' % _("Maintainer >=2019")))
  3752. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3753. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alexandru Lazar"))
  3754. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3755. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3756. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3757. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3758. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3759. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3760. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3761. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3762. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3763. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3764. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3765. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3766. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3767. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3768. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3769. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3770. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3771. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3772. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3773. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3774. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3775. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3776. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3777. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3778. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3779. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3780. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3781. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3782. self.translator_grid_lay = QtWidgets.QGridLayout()
  3783. # trans_widget = QtWidgets.QWidget()
  3784. # trans_widget.setLayout(self.translator_grid_lay)
  3785. # self.translators_tab_layout.addWidget(trans_widget)
  3786. # self.translators_tab_layout.addStretch()
  3787. trans_widget = QtWidgets.QWidget()
  3788. trans_widget.setLayout(self.translator_grid_lay)
  3789. trans_scroll = QtWidgets.QScrollArea()
  3790. trans_scroll.setWidget(trans_widget)
  3791. trans_scroll.setWidgetResizable(True)
  3792. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3793. trans_scroll.setPalette(pal)
  3794. self.translators_tab_layout.addWidget(trans_scroll)
  3795. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3796. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3797. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3798. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3799. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3800. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3801. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3802. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3803. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3804. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3805. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 3, 1)
  3806. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3807. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3808. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3809. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  3810. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3811. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3812. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 2)
  3813. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3814. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 6, 1)
  3815. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 2)
  3816. self.translator_grid_lay.setColumnStretch(0, 0)
  3817. self.translators_tab_layout.addStretch()
  3818. self.license_tab_layout.addWidget(license_label)
  3819. self.license_tab_layout.addStretch()
  3820. layout3.addStretch()
  3821. layout3.addWidget(closebtn)
  3822. closebtn.clicked.connect(self.accept)
  3823. AboutDialog(self.ui).exec_()
  3824. def on_file_savedefaults(self):
  3825. """
  3826. Callback for menu item File->Save Defaults. Saves application default options
  3827. ``self.defaults`` to current_defaults.FlatConfig.
  3828. :return: None
  3829. """
  3830. self.save_defaults()
  3831. # def on_app_exit(self):
  3832. # self.report_usage("on_app_exit()")
  3833. #
  3834. # if self.collection.get_list():
  3835. # msgbox = QtWidgets.QMessageBox()
  3836. # # msgbox.setText("<B>Save changes ...</B>")
  3837. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3838. # "\n"
  3839. # "Do you want to Save the project?")
  3840. # msgbox.setWindowTitle("Save changes")
  3841. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3842. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3843. # QtWidgets.QMessageBox.Cancel)
  3844. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3845. #
  3846. # response = msgbox.exec_()
  3847. #
  3848. # if response == QtWidgets.QMessageBox.Yes:
  3849. # self.on_file_saveprojectas(thread=False)
  3850. # elif response == QtWidgets.QMessageBox.Cancel:
  3851. # return
  3852. # self.save_defaults()
  3853. # else:
  3854. # self.save_defaults()
  3855. # log.debug("Application defaults saved ... Exit event.")
  3856. # QtWidgets.qApp.quit()
  3857. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3858. """
  3859. Saves application default options
  3860. ``self.defaults`` to current_defaults.FlatConfig file.
  3861. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3862. used at the next launch of the application.
  3863. :param silent: whether to display a message in status bar or not; boolean
  3864. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3865. When the application is portable it should be a mobile location.
  3866. :return: None
  3867. """
  3868. self.report_usage("save_defaults")
  3869. if data_path is None:
  3870. data_path = self.data_path
  3871. # Read options from file
  3872. try:
  3873. f = open(data_path + "/current_defaults.FlatConfig")
  3874. defaults_file_content = f.read()
  3875. f.close()
  3876. except:
  3877. e = sys.exc_info()[0]
  3878. App.log.error("Could not load defaults file.")
  3879. App.log.error(str(e))
  3880. self.inform.emit('[ERROR_NOTCL] %s' %
  3881. _("Could not load defaults file."))
  3882. return
  3883. try:
  3884. defaults = json.loads(defaults_file_content)
  3885. except:
  3886. e = sys.exc_info()[0]
  3887. App.log.error("Failed to parse defaults file.")
  3888. App.log.error(str(e))
  3889. self.inform.emit('[ERROR_NOTCL] %s' %
  3890. _("Failed to parse defaults file."))
  3891. return
  3892. # Update options
  3893. self.defaults_read_form()
  3894. defaults.update(self.defaults)
  3895. self.propagate_defaults(silent=True)
  3896. # Save the toolbar view
  3897. tb_status = 0
  3898. if self.ui.toolbarfile.isVisible():
  3899. tb_status += 1
  3900. if self.ui.toolbargeo.isVisible():
  3901. tb_status += 2
  3902. if self.ui.toolbarview.isVisible():
  3903. tb_status += 4
  3904. if self.ui.toolbartools.isVisible():
  3905. tb_status += 8
  3906. if self.ui.exc_edit_toolbar.isVisible():
  3907. tb_status += 16
  3908. if self.ui.geo_edit_toolbar.isVisible():
  3909. tb_status += 32
  3910. if self.ui.grb_edit_toolbar.isVisible():
  3911. tb_status += 64
  3912. if self.ui.snap_toolbar.isVisible():
  3913. tb_status += 128
  3914. if self.ui.toolbarshell.isVisible():
  3915. tb_status += 256
  3916. if first_time is False:
  3917. self.defaults["global_toolbar_view"] = tb_status
  3918. # Save update options
  3919. try:
  3920. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3921. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3922. f.close()
  3923. except:
  3924. self.inform.emit('[ERROR_NOTCL] %s' %
  3925. _("Failed to write defaults to file."))
  3926. return
  3927. if not silent:
  3928. self.inform.emit('[success] %s' %
  3929. _("Preferences saved."))
  3930. def save_factory_defaults(self, silent=False, data_path=None):
  3931. """
  3932. Saves application factory default options
  3933. ``self.defaults`` to factory_defaults.FlatConfig.
  3934. It's a one time job done just after the first install.
  3935. :param silent: whether to display a message in status bar or not; boolean
  3936. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3937. When the application is portable it should be a mobile location.
  3938. :return: None
  3939. """
  3940. self.report_usage("save_factory_defaults")
  3941. if data_path is None:
  3942. data_path = self.data_path
  3943. # Read options from file
  3944. try:
  3945. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3946. factory_defaults_file_content = f_f_def.read()
  3947. f_f_def.close()
  3948. except:
  3949. e = sys.exc_info()[0]
  3950. App.log.error("Could not load factory defaults file.")
  3951. App.log.error(str(e))
  3952. self.inform.emit('[ERROR_NOTCL] %s' %
  3953. _("Could not load factory defaults file."))
  3954. return
  3955. try:
  3956. factory_defaults = json.loads(factory_defaults_file_content)
  3957. except:
  3958. e = sys.exc_info()[0]
  3959. App.log.error("Failed to parse factory defaults file.")
  3960. App.log.error(str(e))
  3961. self.inform.emit('[ERROR_NOTCL] %s' %
  3962. _("Failed to parse factory defaults file."))
  3963. return
  3964. # Update options
  3965. self.defaults_read_form()
  3966. factory_defaults.update(self.defaults)
  3967. self.propagate_defaults(silent=True)
  3968. # Save update options
  3969. try:
  3970. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3971. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3972. f_f_def_s.close()
  3973. except:
  3974. self.inform.emit('[ERROR_NOTCL] %s' %
  3975. _("Failed to write factory defaults to file."))
  3976. return
  3977. if silent is False:
  3978. self.inform.emit(_("Factory defaults saved."))
  3979. def final_save(self):
  3980. """
  3981. Callback for doing a preferences save to file whenever the application is about to quit.
  3982. If the project has changes, it will ask the user to save the project.
  3983. :return: None
  3984. """
  3985. if self.save_in_progress:
  3986. self.inform.emit('[WARNING_NOTCL] %s' %
  3987. _("Application is saving the project. Please wait ..."))
  3988. return
  3989. if self.should_we_save and self.collection.get_list():
  3990. msgbox = QtWidgets.QMessageBox()
  3991. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3992. "\n"
  3993. "Do you want to Save the project?"))
  3994. msgbox.setWindowTitle(_("Save changes"))
  3995. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3996. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3997. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3998. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3999. msgbox.setDefaultButton(bt_yes)
  4000. msgbox.exec_()
  4001. response = msgbox.clickedButton()
  4002. if response == bt_yes:
  4003. try:
  4004. self.trayIcon.hide()
  4005. except:
  4006. pass
  4007. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4008. elif response == bt_no:
  4009. try:
  4010. self.trayIcon.hide()
  4011. except:
  4012. pass
  4013. self.quit_application()
  4014. elif response == bt_cancel:
  4015. return
  4016. else:
  4017. try:
  4018. self.trayIcon.hide()
  4019. except:
  4020. pass
  4021. self.quit_application()
  4022. def quit_application(self):
  4023. """
  4024. Called (as a pyslot or not) when the application is quit.
  4025. :return: None
  4026. """
  4027. self.save_defaults()
  4028. log.debug("App.final_save() --> App Defaults saved.")
  4029. if self.cmd_line_headless != 1:
  4030. # save app state to file
  4031. settings = QSettings("Open Source", "FlatCAM")
  4032. settings.setValue('saved_gui_state', self.ui.saveState())
  4033. settings.setValue('maximized_gui', self.ui.isMaximized())
  4034. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  4035. settings.setValue(
  4036. 'notebook_font_size',
  4037. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4038. )
  4039. settings.setValue('axis_font_size',
  4040. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  4041. settings.setValue(
  4042. 'textbox_font_size',
  4043. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4044. )
  4045. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4046. # This will write the setting to the platform specific storage.
  4047. del settings
  4048. log.debug("App.final_save() --> App UI state saved.")
  4049. QtWidgets.qApp.quit()
  4050. def on_portable_checked(self, state):
  4051. """
  4052. Callback called when the checkbox in Preferences GUI is checked.
  4053. It will set the application as portable by creating the preferences and recent files in the
  4054. 'config' folder found in the FlatCAM installation folder.
  4055. :param state: boolean, the state of the checkbox when clicked/checked
  4056. :return:
  4057. """
  4058. line_no = 0
  4059. data = None
  4060. if sys.platform != 'win32':
  4061. # this won't work in Linux or MacOS
  4062. return
  4063. # test if the app was frozen and choose the path for the configuration file
  4064. if getattr(sys, "frozen", False) is True:
  4065. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4066. else:
  4067. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4068. config_file = current_data_path + '\\configuration.txt'
  4069. try:
  4070. with open(config_file, 'r') as f:
  4071. try:
  4072. data = f.readlines()
  4073. except Exception as e:
  4074. log.debug('App.__init__() -->%s' % str(e))
  4075. return
  4076. except FileNotFoundError:
  4077. pass
  4078. for line in data:
  4079. line = line.strip('\n')
  4080. param = str(line).rpartition('=')
  4081. if param[0] == 'portable':
  4082. break
  4083. line_no += 1
  4084. if state:
  4085. data[line_no] = 'portable=True\n'
  4086. # create the new defauults files
  4087. # create current_defaults.FlatConfig file if there is none
  4088. try:
  4089. f = open(current_data_path + '/current_defaults.FlatConfig')
  4090. f.close()
  4091. except IOError:
  4092. App.log.debug('Creating empty current_defaults.FlatConfig')
  4093. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4094. json.dump({}, f)
  4095. f.close()
  4096. # create factory_defaults.FlatConfig file if there is none
  4097. try:
  4098. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4099. f.close()
  4100. except IOError:
  4101. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4102. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4103. json.dump({}, f)
  4104. f.close()
  4105. try:
  4106. f = open(current_data_path + '/recent.json')
  4107. f.close()
  4108. except IOError:
  4109. App.log.debug('Creating empty recent.json')
  4110. f = open(current_data_path + '/recent.json', 'w')
  4111. json.dump([], f)
  4112. f.close()
  4113. try:
  4114. fp = open(current_data_path + '/recent_projects.json')
  4115. fp.close()
  4116. except IOError:
  4117. App.log.debug('Creating empty recent_projects.json')
  4118. fp = open(current_data_path + '/recent_projects.json', 'w')
  4119. json.dump([], fp)
  4120. fp.close()
  4121. # save the current defaults to the new defaults file
  4122. self.save_defaults(silent=True, data_path=current_data_path)
  4123. self.save_factory_defaults(silent=True, data_path=current_data_path)
  4124. else:
  4125. data[line_no] = 'portable=False\n'
  4126. with open(config_file, 'w') as f:
  4127. f.writelines(data)
  4128. def on_toggle_shell(self):
  4129. """
  4130. Toggle shell: if is visible close it, if it is closed then open it
  4131. :return:
  4132. """
  4133. self.report_usage("on_toggle_shell()")
  4134. if self.ui.shell_dock.isVisible():
  4135. self.ui.shell_dock.hide()
  4136. else:
  4137. self.ui.shell_dock.show()
  4138. def on_register_files(self, obj_type=None):
  4139. """
  4140. Called whenever there is a need to register file extensions with FlatCAM.
  4141. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4142. :param obj_type: the type of object to be register for.
  4143. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4144. :return: None
  4145. """
  4146. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4147. new_reg_path = 'Software\\Classes\\'
  4148. # find if the current user is admin
  4149. try:
  4150. is_admin = os.getuid() == 0
  4151. except AttributeError:
  4152. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4153. if is_admin is True:
  4154. root_path = winreg.HKEY_LOCAL_MACHINE
  4155. else:
  4156. root_path = winreg.HKEY_CURRENT_USER
  4157. # create the keys
  4158. def set_reg(name, root_path, new_reg_path, value):
  4159. try:
  4160. winreg.CreateKey(root_path, new_reg_path)
  4161. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4162. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4163. return True
  4164. except WindowsError:
  4165. return False
  4166. # delete key in registry
  4167. def delete_reg(root_path, reg_path, key_to_del):
  4168. key_to_del_path = reg_path + key_to_del
  4169. try:
  4170. winreg.DeleteKey(root_path, key_to_del_path)
  4171. return True
  4172. except WindowsError:
  4173. return False
  4174. if obj_type is None or obj_type == 'excellon':
  4175. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4176. exc_list = [x for x in exc_list if x != '']
  4177. # register all keys in the Preferences window
  4178. for ext in exc_list:
  4179. new_k = new_reg_path + '.%s' % ext
  4180. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4181. # and unregister those that are no longer in the Preferences windows but are in the file
  4182. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4183. if ext not in exc_list:
  4184. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4185. # now write the updated extensions to the self.defaults
  4186. # new_ext = ''
  4187. # for ext in exc_list:
  4188. # new_ext = new_ext + ext + ', '
  4189. # self.defaults["fa_excellon"] = new_ext
  4190. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4191. if obj_type is None or obj_type == 'gcode':
  4192. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4193. gco_list = [x for x in gco_list if x != '']
  4194. # register all keys in the Preferences window
  4195. for ext in gco_list:
  4196. new_k = new_reg_path + '.%s' % ext
  4197. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4198. # and unregister those that are no longer in the Preferences windows but are in the file
  4199. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4200. if ext not in gco_list:
  4201. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4202. # now write the updated extensions to the self.defaults
  4203. # new_ext = ''
  4204. # for ext in gco_list:
  4205. # new_ext = new_ext + ext + ', '
  4206. # self.defaults["fa_gcode"] = new_ext
  4207. self.inform.emit('[success] %s' %
  4208. _("Selected GCode file extensions registered with FlatCAM."))
  4209. if obj_type is None or obj_type == 'gerber':
  4210. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4211. grb_list = [x for x in grb_list if x != '']
  4212. # register all keys in the Preferences window
  4213. for ext in grb_list:
  4214. new_k = new_reg_path + '.%s' % ext
  4215. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4216. # and unregister those that are no longer in the Preferences windows but are in the file
  4217. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4218. if ext not in grb_list:
  4219. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4220. # now write the updated extensions to the self.defaults
  4221. # new_ext = ''
  4222. # for ext in grb_list:
  4223. # new_ext = new_ext + ext + ', '
  4224. # self.defaults["fa_gerber"] = new_ext
  4225. self.inform.emit('[success] %s' %
  4226. _("Selected Gerber file extensions registered with FlatCAM."))
  4227. def add_extension(self, ext_type):
  4228. if ext_type == 'excellon':
  4229. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4230. if new_ext == '':
  4231. return
  4232. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4233. if new_ext in old_val:
  4234. return
  4235. old_val.append(new_ext)
  4236. old_val.sort()
  4237. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4238. if ext_type == 'gcode':
  4239. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4240. if new_ext == '':
  4241. return
  4242. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4243. if new_ext in old_val:
  4244. return
  4245. old_val.append(new_ext)
  4246. old_val.sort()
  4247. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4248. if ext_type == 'gerber':
  4249. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4250. if new_ext == '':
  4251. return
  4252. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4253. if new_ext in old_val:
  4254. return
  4255. old_val.append(new_ext)
  4256. old_val.sort()
  4257. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4258. if ext_type == 'keyword':
  4259. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4260. if new_kw == '':
  4261. return
  4262. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4263. if new_kw in old_val:
  4264. return
  4265. old_val.append(new_kw)
  4266. old_val.sort()
  4267. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4268. # update the self.myKeywords so the model is updated
  4269. self.autocomplete_kw_list = \
  4270. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4271. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4272. self.shell._edit.set_model_data(self.myKeywords)
  4273. def del_extension(self, ext_type):
  4274. if ext_type == 'excellon':
  4275. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4276. if new_ext == '':
  4277. return
  4278. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4279. if new_ext not in old_val:
  4280. return
  4281. old_val.remove(new_ext)
  4282. old_val.sort()
  4283. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4284. if ext_type == 'gcode':
  4285. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4286. if new_ext == '':
  4287. return
  4288. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4289. if new_ext not in old_val:
  4290. return
  4291. old_val.remove(new_ext)
  4292. old_val.sort()
  4293. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4294. if ext_type == 'gerber':
  4295. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4296. if new_ext == '':
  4297. return
  4298. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4299. if new_ext not in old_val:
  4300. return
  4301. old_val.remove(new_ext)
  4302. old_val.sort()
  4303. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4304. if ext_type == 'keyword':
  4305. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4306. if new_kw == '':
  4307. return
  4308. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4309. if new_kw not in old_val:
  4310. return
  4311. old_val.remove(new_kw)
  4312. old_val.sort()
  4313. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4314. # update the self.myKeywords so the model is updated
  4315. self.autocomplete_kw_list = \
  4316. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4317. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4318. self.shell._edit.set_model_data(self.myKeywords)
  4319. def restore_extensions(self, ext_type):
  4320. if ext_type == 'excellon':
  4321. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4322. # for the ability to open Excellon files with .txt extension
  4323. new_exc_list = deepcopy(self.exc_list)
  4324. try:
  4325. new_exc_list.remove('txt')
  4326. except ValueError:
  4327. pass
  4328. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4329. if ext_type == 'gcode':
  4330. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4331. if ext_type == 'gerber':
  4332. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4333. if ext_type == 'keyword':
  4334. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4335. # update the self.myKeywords so the model is updated
  4336. self.autocomplete_kw_list = self.default_keywords
  4337. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4338. self.shell._edit.set_model_data(self.myKeywords)
  4339. def delete_all_extensions(self, ext_type):
  4340. if ext_type == 'excellon':
  4341. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4342. if ext_type == 'gcode':
  4343. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4344. if ext_type == 'gerber':
  4345. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4346. if ext_type == 'keyword':
  4347. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4348. # update the self.myKeywords so the model is updated
  4349. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4350. self.shell._edit.set_model_data(self.myKeywords)
  4351. def on_edit_join(self, name=None):
  4352. """
  4353. Callback for Edit->Join. Joins the selected geometry objects into
  4354. a new one.
  4355. :return: None
  4356. """
  4357. self.report_usage("on_edit_join()")
  4358. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4359. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4360. geo_type_list = set()
  4361. objs = self.collection.get_selected()
  4362. if len(objs) < 2:
  4363. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4364. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4365. return 'fail'
  4366. for obj in objs:
  4367. geo_type_list.add(obj.multigeo)
  4368. # if len(geo_type_list) == 1 means that all list elements are the same
  4369. if len(geo_type_list) != 1:
  4370. self.inform.emit('[ERROR] %s' %
  4371. _("Failed join. The Geometry objects are of different types.\n"
  4372. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4373. "convert from one to another and retry joining \n"
  4374. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4375. "the result may not be what was expected. \n"
  4376. "Check the generated GCODE."))
  4377. return
  4378. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4379. if True in geo_type_list:
  4380. def initialize(obj, app):
  4381. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4382. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4383. for v in obj.tools.values():
  4384. v['data']['name'] = obj_name_multi
  4385. self.new_object("geometry", obj_name_multi, initialize)
  4386. else:
  4387. def initialize(obj, app):
  4388. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4389. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4390. for v in obj.tools.values():
  4391. v['data']['name'] = obj_name_single
  4392. self.new_object("geometry", obj_name_single, initialize)
  4393. self.should_we_save = True
  4394. def on_edit_join_exc(self):
  4395. """
  4396. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4397. a new Excellon.
  4398. :return: None
  4399. """
  4400. self.report_usage("on_edit_join_exc()")
  4401. objs = self.collection.get_selected()
  4402. for obj in objs:
  4403. if not isinstance(obj, FlatCAMExcellon):
  4404. self.inform.emit('[ERROR_NOTCL] %s' %
  4405. _("Failed. Excellon joining works only on Excellon objects."))
  4406. return
  4407. if len(objs) < 2:
  4408. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4409. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4410. return 'fail'
  4411. def initialize(obj, app):
  4412. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4413. self.new_object("excellon", 'Combo_Excellon', initialize)
  4414. self.should_we_save = True
  4415. def on_edit_join_grb(self):
  4416. """
  4417. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4418. a new Gerber object.
  4419. :return: None
  4420. """
  4421. self.report_usage("on_edit_join_grb()")
  4422. objs = self.collection.get_selected()
  4423. for obj in objs:
  4424. if not isinstance(obj, FlatCAMGerber):
  4425. self.inform.emit('[ERROR_NOTCL] %s' %
  4426. _("Failed. Gerber joining works only on Gerber objects."))
  4427. return
  4428. if len(objs) < 2:
  4429. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4430. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4431. return 'fail'
  4432. def initialize(obj, app):
  4433. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4434. self.new_object("gerber", 'Combo_Gerber', initialize)
  4435. self.should_we_save = True
  4436. def on_convert_singlegeo_to_multigeo(self):
  4437. """
  4438. Called for converting a Geometry object from single-geo to multi-geo.
  4439. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4440. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4441. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4442. the solid-geometry of that tool.
  4443. :return: None
  4444. """
  4445. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4446. obj = self.collection.get_active()
  4447. if obj is None:
  4448. self.inform.emit('[ERROR_NOTCL] %s' %
  4449. _("Failed. Select a Geometry Object and try again."))
  4450. return
  4451. if not isinstance(obj, FlatCAMGeometry):
  4452. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4453. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4454. return
  4455. obj.multigeo = True
  4456. for tooluid, dict_value in obj.tools.items():
  4457. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4458. if not isinstance(obj.solid_geometry, list):
  4459. obj.solid_geometry = [obj.solid_geometry]
  4460. obj.solid_geometry[:] = []
  4461. obj.plot()
  4462. self.should_we_save = True
  4463. self.inform.emit('[success] %s' %
  4464. _("A Geometry object was converted to MultiGeo type."))
  4465. def on_convert_multigeo_to_singlegeo(self):
  4466. """
  4467. Called for converting a Geometry object from multi-geo to single-geo.
  4468. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4469. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4470. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4471. the solid-geometry of that tool.
  4472. :return: None
  4473. """
  4474. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4475. obj = self.collection.get_active()
  4476. if obj is None:
  4477. self.inform.emit('[ERROR_NOTCL] %s' %
  4478. _("Failed. Select a Geometry Object and try again."))
  4479. return
  4480. if not isinstance(obj, FlatCAMGeometry):
  4481. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4482. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4483. return
  4484. obj.multigeo = False
  4485. total_solid_geometry = []
  4486. for tooluid, dict_value in obj.tools.items():
  4487. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4488. # clear the original geometry
  4489. dict_value['solid_geometry'][:] = []
  4490. obj.solid_geometry = deepcopy(total_solid_geometry)
  4491. obj.plot()
  4492. self.should_we_save = True
  4493. self.inform.emit('[success] %s' %
  4494. _("A Geometry object was converted to SingleGeo type."))
  4495. def on_options_dict_change(self, field):
  4496. """
  4497. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4498. current project. This feature is no longer used.
  4499. :param field:
  4500. :return:
  4501. """
  4502. self.options_write_form_field(field)
  4503. if field == "units":
  4504. self.set_screen_units(self.options['units'])
  4505. def on_defaults_dict_change(self, field):
  4506. """
  4507. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4508. Edit -> Preferences tab window.
  4509. :param field: the key of the self.defaults dictionary that was changed.
  4510. :return: None
  4511. """
  4512. self.defaults_write_form_field(field)
  4513. if field == "units":
  4514. self.set_screen_units(self.defaults['units'])
  4515. def set_screen_units(self, units):
  4516. """
  4517. Set the FlatCAM units on the status bar.
  4518. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4519. :return: None
  4520. """
  4521. self.ui.units_label.setText("[" + units.lower() + "]")
  4522. def on_toggle_units(self, no_pref=False):
  4523. """
  4524. Callback for the Units radio-button change in the Preferences tab.
  4525. Changes the application's default units adn for the project too.
  4526. If changing the project's units, the change propagates to all of
  4527. the objects in the project.
  4528. :return: None
  4529. """
  4530. self.report_usage("on_toggle_units")
  4531. if self.toggle_units_ignore:
  4532. return
  4533. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4534. # If option is the same, then ignore
  4535. if new_units == self.defaults["units"].upper():
  4536. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4537. return
  4538. # Options to scale
  4539. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4540. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f"
  4541. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4542. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4543. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4544. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4545. "excellon_editor_slot_lin_pitch",
  4546. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4547. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4548. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4549. "geometry_feedrate_probe", "geometry_startz",
  4550. 'cncjob_tooldia',
  4551. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4552. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4553. "tools_2sided_drilldia", "tools_film_boundary",
  4554. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4555. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4556. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4557. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4558. "tools_transform_offset_y",
  4559. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4560. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4561. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4562. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4563. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4564. def scale_options(sfactor):
  4565. for dim in dimensions:
  4566. if dim == 'excellon_toolchangexy':
  4567. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4568. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4569. coords_xy[0] *= sfactor
  4570. coords_xy[1] *= sfactor
  4571. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4572. elif dim == 'geometry_toolchangexy':
  4573. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4574. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4575. coords_xy[0] *= sfactor
  4576. coords_xy[1] *= sfactor
  4577. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4578. elif dim == 'geometry_cnctooldia':
  4579. tools_diameters = []
  4580. try:
  4581. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4582. tools_diameters = [eval(a) for a in tools_string if a != '']
  4583. except Exception as e:
  4584. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4585. self.options['geometry_cnctooldia'] = ''
  4586. for t in range(len(tools_diameters)):
  4587. tools_diameters[t] *= sfactor
  4588. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4589. elif dim == 'tools_ncctools':
  4590. ncctools = []
  4591. try:
  4592. tools_string = self.defaults["tools_ncctools"].split(",")
  4593. ncctools = [eval(a) for a in tools_string if a != '']
  4594. except Exception as e:
  4595. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4596. self.options['tools_ncctools'] = ''
  4597. for t in range(len(ncctools)):
  4598. ncctools[t] *= sfactor
  4599. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4600. elif dim == 'tools_solderpaste_tools':
  4601. sptools = []
  4602. try:
  4603. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4604. sptools = [eval(a) for a in tools_string if a != '']
  4605. except Exception as e:
  4606. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4607. self.options['tools_solderpaste_tools'] = ""
  4608. for t in range(len(sptools)):
  4609. sptools[t] *= sfactor
  4610. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4611. elif dim == 'tools_solderpaste_xy_toolchange':
  4612. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4613. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4614. sp_coords[0] *= sfactor
  4615. sp_coords[1] *= sfactor
  4616. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4617. elif dim == 'global_gridx' or dim == 'global_gridy':
  4618. if new_units == 'IN':
  4619. val = 0.1
  4620. try:
  4621. val = float(self.defaults[dim]) * sfactor
  4622. except Exception as e:
  4623. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4624. self.options[dim] = float('%.6f' % val)
  4625. else:
  4626. val = 0.1
  4627. try:
  4628. val = float(self.defaults[dim]) * sfactor
  4629. except Exception as e:
  4630. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4631. self.options[dim] = float('%.4f' % val)
  4632. else:
  4633. val = 0.1
  4634. try:
  4635. val = float(self.options[dim]) * sfactor
  4636. except Exception as e:
  4637. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4638. self.options[dim] = val
  4639. def scale_defaults(sfactor):
  4640. for dim in dimensions:
  4641. if dim == 'excellon_toolchangexy':
  4642. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4643. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4644. coords_xy[0] *= sfactor
  4645. coords_xy[1] *= sfactor
  4646. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4647. elif dim == 'geometry_toolchangexy':
  4648. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4649. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4650. coords_xy[0] *= sfactor
  4651. coords_xy[1] *= sfactor
  4652. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4653. elif dim == 'geometry_cnctooldia':
  4654. tools_diameters = []
  4655. try:
  4656. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4657. tools_diameters = [eval(a) for a in tools_string if a != '']
  4658. except Exception as e:
  4659. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4660. self.defaults['geometry_cnctooldia'] = ''
  4661. for t in range(len(tools_diameters)):
  4662. tools_diameters[t] *= sfactor
  4663. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4664. elif dim == 'tools_ncctools':
  4665. ncctools = []
  4666. try:
  4667. tools_string = self.defaults["tools_ncctools"].split(",")
  4668. ncctools = [eval(a) for a in tools_string if a != '']
  4669. except Exception as e:
  4670. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4671. self.defaults['tools_ncctools'] = ''
  4672. for t in range(len(ncctools)):
  4673. ncctools[t] *= sfactor
  4674. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4675. elif dim == 'tools_solderpaste_tools':
  4676. sptools = []
  4677. try:
  4678. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4679. sptools = [eval(a) for a in tools_string if a != '']
  4680. except Exception as e:
  4681. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4682. self.defaults['tools_solderpaste_tools'] = ""
  4683. for t in range(len(sptools)):
  4684. sptools[t] *= sfactor
  4685. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4686. elif dim == 'tools_solderpaste_xy_toolchange':
  4687. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4688. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4689. sp_coords[0] *= sfactor
  4690. sp_coords[1] *= sfactor
  4691. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4692. elif dim == 'global_gridx' or dim == 'global_gridy':
  4693. if new_units == 'IN':
  4694. val = 0.1
  4695. try:
  4696. val = float(self.defaults[dim]) * sfactor
  4697. except Exception as e:
  4698. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4699. self.defaults[dim] = float('%.6f' % val)
  4700. else:
  4701. val = 0.1
  4702. try:
  4703. val = float(self.defaults[dim]) * sfactor
  4704. except Exception as e:
  4705. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4706. self.defaults[dim] = float('%.4f' % val)
  4707. else:
  4708. val = 0.1
  4709. try:
  4710. val = float(self.defaults[dim]) * sfactor
  4711. except Exception as e:
  4712. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4713. self.defaults[dim] = val
  4714. # The scaling factor depending on choice of units.
  4715. factor = 1/25.4
  4716. if new_units == 'MM':
  4717. factor = 25.4
  4718. # Changing project units. Warn user.
  4719. msgbox = QtWidgets.QMessageBox()
  4720. msgbox.setWindowTitle(_("Toggle Units"))
  4721. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4722. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4723. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4724. "properties of all objects to be scaled accordingly.\nContinue?"))
  4725. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4726. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4727. msgbox.setDefaultButton(bt_ok)
  4728. msgbox.exec_()
  4729. response = msgbox.clickedButton()
  4730. if response == bt_ok:
  4731. if no_pref is False:
  4732. self.options_read_form()
  4733. scale_options(factor)
  4734. self.options_write_form()
  4735. self.defaults_read_form()
  4736. scale_defaults(factor)
  4737. self.defaults_write_form(fl_units=new_units)
  4738. # save the defaults to file, some may assume that the conversion is enough and it's not
  4739. self.on_save_button()
  4740. self.should_we_save = True
  4741. # change this only if the workspace is active
  4742. if self.defaults['global_workspace'] is True:
  4743. self.plotcanvas.draw_workspace()
  4744. # adjust the grid values on the main toolbar
  4745. dec = 6 if new_units == 'IN'else 4
  4746. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4747. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4748. if not self.ui.grid_gap_link_cb.isChecked():
  4749. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4750. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4751. for obj in self.collection.get_list():
  4752. obj.convert_units(new_units)
  4753. # make that the properties stored in the object are also updated
  4754. self.object_changed.emit(obj)
  4755. obj.build_ui()
  4756. current = self.collection.get_active()
  4757. if current is not None:
  4758. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4759. if not isinstance(current, FlatCAMGeometry):
  4760. current.to_form()
  4761. self.plot_all()
  4762. self.inform.emit('[success] %s: %s' %
  4763. (_("Converted units to"), new_units))
  4764. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4765. self.set_screen_units(new_units)
  4766. else:
  4767. # Undo toggling
  4768. self.toggle_units_ignore = True
  4769. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4770. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4771. else:
  4772. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4773. self.toggle_units_ignore = False
  4774. self.inform.emit('[WARNING_NOTCL]%s' %
  4775. _(" Units conversion cancelled."))
  4776. self.options_read_form()
  4777. self.defaults_read_form()
  4778. def on_toggle_units_click(self):
  4779. try:
  4780. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4781. except (TypeError, AttributeError):
  4782. pass
  4783. if self.defaults["units"] == 'MM':
  4784. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4785. else:
  4786. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4787. self.on_toggle_units(no_pref=True)
  4788. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4789. lambda: self.on_toggle_units(no_pref=False))
  4790. def on_fullscreen(self, disable=False):
  4791. self.report_usage("on_fullscreen()")
  4792. if self.toggle_fscreen is False and disable is False:
  4793. # self.ui.showFullScreen()
  4794. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4795. a = self.ui.geometry()
  4796. self.x_pos = a.x()
  4797. self.y_pos = a.y()
  4798. self.width = a.width()
  4799. self.height = a.height()
  4800. # set new geometry to full desktop rect
  4801. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4802. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4803. # everything else will not work without this hack. This happen in Windows.
  4804. # https://bugreports.qt.io/browse/QTBUG-41309
  4805. desktop = QtWidgets.QApplication.desktop()
  4806. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4807. rec = desktop.screenGeometry(screen)
  4808. x = rec.x() - 1
  4809. y = rec.y() - 1
  4810. h = rec.height() + 2
  4811. w = rec.width() + 2
  4812. self.ui.setGeometry(x, y, w, h)
  4813. self.ui.show()
  4814. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4815. tb.setVisible(False)
  4816. self.ui.splitter_left.setVisible(False)
  4817. self.toggle_fscreen = True
  4818. elif self.toggle_fscreen is True or disable is True:
  4819. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4820. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4821. self.ui.showNormal()
  4822. self.restore_toolbar_view()
  4823. self.ui.splitter_left.setVisible(True)
  4824. self.toggle_fscreen = False
  4825. def on_toggle_plotarea(self):
  4826. self.report_usage("on_toggle_plotarea()")
  4827. try:
  4828. name = self.ui.plot_tab_area.widget(0).objectName()
  4829. except AttributeError:
  4830. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4831. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4832. self.ui.plot_tab_area.protectTab(0)
  4833. return
  4834. if name != 'plotarea':
  4835. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4836. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4837. self.ui.plot_tab_area.protectTab(0)
  4838. else:
  4839. self.ui.plot_tab_area.closeTab(0)
  4840. def on_toggle_notebook(self):
  4841. if self.ui.splitter.sizes()[0] == 0:
  4842. self.ui.splitter.setSizes([1, 1])
  4843. self.ui.menu_toggle_nb.setChecked(True)
  4844. else:
  4845. self.ui.splitter.setSizes([0, 1])
  4846. self.ui.menu_toggle_nb.setChecked(False)
  4847. def on_toggle_axis(self):
  4848. self.report_usage("on_toggle_axis()")
  4849. if self.toggle_axis is False:
  4850. if self.is_legacy is False:
  4851. # self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4852. # self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4853. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4854. parent=self.plotcanvas.view.scene)
  4855. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4856. parent=self.plotcanvas.view.scene)
  4857. # self.plotcanvas.redraw()
  4858. else:
  4859. self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4860. self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4861. self.plotcanvas.canvas.draw()
  4862. pass
  4863. self.toggle_axis = True
  4864. else:
  4865. if self.is_legacy is False:
  4866. # self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4867. # self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4868. # self.plotcanvas.redraw()
  4869. self.plotcanvas.v_line.parent = None
  4870. self.plotcanvas.h_line.parent = None
  4871. else:
  4872. self.plotcanvas.axes.lines[:] = []
  4873. self.plotcanvas.canvas.draw()
  4874. self.toggle_axis = False
  4875. def on_toggle_grid(self):
  4876. self.report_usage("on_toggle_grid()")
  4877. self.ui.grid_snap_btn.trigger()
  4878. def on_options_combo_change(self, sel):
  4879. """
  4880. Called when the combo box to choose between application defaults and
  4881. project option changes value. The corresponding variables are
  4882. copied to the UI.
  4883. :param sel: The option index that was chosen.
  4884. :return: None
  4885. """
  4886. # combo_sel = self.ui.notebook.combo_options.get_active()
  4887. App.log.debug("Options --> %s" % sel)
  4888. # form = [self.defaults_form, self.options_form][sel]
  4889. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4890. if sel == 0:
  4891. self.gen_form = self.ui.general_defaults_form
  4892. self.ger_form = self.ui.gerber_defaults_form
  4893. self.exc_form = self.ui.excellon_defaults_form
  4894. self.geo_form = self.ui.geometry_defaults_form
  4895. self.cnc_form = self.ui.cncjob_defaults_form
  4896. self.tools_form = self.ui.tools_defaults_form
  4897. self.fa_form = self.ui.util_defaults_form
  4898. elif sel == 1:
  4899. self.gen_form = self.ui.general_options_form
  4900. self.ger_form = self.ui.gerber_options_form
  4901. self.exc_form = self.ui.excellon_options_form
  4902. self.geo_form = self.ui.geometry_options_form
  4903. self.cnc_form = self.ui.cncjob_options_form
  4904. self.tools_form = self.ui.tools_options_form
  4905. self.fa_form = self.ui.util_options_form
  4906. else:
  4907. return
  4908. try:
  4909. self.ui.general_scroll_area.takeWidget()
  4910. except:
  4911. self.log.debug("Nothing to remove")
  4912. self.ui.general_scroll_area.setWidget(self.gen_form)
  4913. self.gen_form.show()
  4914. try:
  4915. self.ui.gerber_scroll_area.takeWidget()
  4916. except:
  4917. self.log.debug("Nothing to remove")
  4918. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4919. self.ger_form.show()
  4920. try:
  4921. self.ui.excellon_scroll_area.takeWidget()
  4922. except:
  4923. self.log.debug("Nothing to remove")
  4924. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4925. self.exc_form.show()
  4926. try:
  4927. self.ui.geometry_scroll_area.takeWidget()
  4928. except:
  4929. self.log.debug("Nothing to remove")
  4930. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4931. self.geo_form.show()
  4932. try:
  4933. self.ui.cncjob_scroll_area.takeWidget()
  4934. except:
  4935. self.log.debug("Nothing to remove")
  4936. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4937. self.cnc_form.show()
  4938. try:
  4939. self.ui.tools_scroll_area.takeWidget()
  4940. except:
  4941. self.log.debug("Nothing to remove")
  4942. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4943. self.tools_form.show()
  4944. try:
  4945. self.ui.fa_scroll_area.takeWidget()
  4946. except:
  4947. self.log.debug("Nothing to remove")
  4948. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4949. self.fa_form.show()
  4950. self.log.debug("Finished GUI form initialization.")
  4951. # self.options2form()
  4952. def on_excellon_defaults_button(self):
  4953. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4954. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4955. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4956. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4957. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4958. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4959. log.debug("Excellon app defaults loaded ...")
  4960. def on_excellon_options_button(self):
  4961. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4962. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4963. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4964. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4965. self.options_form_fields["excellon_zeros"].set_value('L')
  4966. self.options_form_fields["excellon_units"].set_value('INCH')
  4967. log.debug("Excellon options defaults loaded ...")
  4968. def on_update_exc_export(self, state):
  4969. """
  4970. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4971. if the update_excellon_cb checkbox is checked
  4972. :param state: state of the checkbox whose signals is tied to his slot
  4973. :return:
  4974. """
  4975. if state:
  4976. # first try to disconnect
  4977. try:
  4978. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4979. disconnect(self.on_excellon_format_changed)
  4980. except TypeError:
  4981. pass
  4982. try:
  4983. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4984. disconnect(self.on_excellon_format_changed)
  4985. except TypeError:
  4986. pass
  4987. try:
  4988. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4989. disconnect(self.on_excellon_format_changed)
  4990. except TypeError:
  4991. pass
  4992. try:
  4993. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4994. disconnect(self.on_excellon_format_changed)
  4995. except TypeError:
  4996. pass
  4997. try:
  4998. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4999. disconnect(self.on_excellon_zeros_changed)
  5000. except TypeError:
  5001. pass
  5002. try:
  5003. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5004. disconnect(self.on_excellon_zeros_changed)
  5005. except TypeError:
  5006. pass
  5007. # the connect them
  5008. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  5009. self.on_excellon_format_changed)
  5010. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  5011. self.on_excellon_format_changed)
  5012. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  5013. self.on_excellon_format_changed)
  5014. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  5015. self.on_excellon_format_changed)
  5016. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5017. self.on_excellon_zeros_changed)
  5018. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5019. self.on_excellon_units_changed)
  5020. else:
  5021. # disconnect the signals
  5022. try:
  5023. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  5024. disconnect(self.on_excellon_format_changed)
  5025. except TypeError:
  5026. pass
  5027. try:
  5028. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged. \
  5029. disconnect(self.on_excellon_format_changed)
  5030. except TypeError:
  5031. pass
  5032. try:
  5033. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  5034. disconnect(self.on_excellon_format_changed)
  5035. except TypeError:
  5036. pass
  5037. try:
  5038. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  5039. disconnect(self.on_excellon_format_changed)
  5040. except TypeError:
  5041. pass
  5042. try:
  5043. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5044. disconnect(self.on_excellon_zeros_changed)
  5045. except TypeError:
  5046. pass
  5047. try:
  5048. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5049. disconnect(self.on_excellon_zeros_changed)
  5050. except TypeError:
  5051. pass
  5052. def on_excellon_format_changed(self):
  5053. """
  5054. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5055. :return: None
  5056. """
  5057. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5058. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5059. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5060. )
  5061. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5062. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5063. )
  5064. else:
  5065. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5066. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5067. )
  5068. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5069. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5070. )
  5071. def on_excellon_zeros_changed(self):
  5072. """
  5073. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5074. :return: None
  5075. """
  5076. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5077. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5078. )
  5079. def on_excellon_units_changed(self):
  5080. """
  5081. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5082. :return: None
  5083. """
  5084. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5085. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5086. )
  5087. self.on_excellon_format_changed()
  5088. # Setting plot colors handlers
  5089. def on_pf_color_entry(self):
  5090. self.defaults['global_plot_fill'] = \
  5091. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5092. self.defaults['global_plot_fill'][7:9]
  5093. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5094. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5095. def on_pf_color_button(self):
  5096. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5097. c_dialog = QtWidgets.QColorDialog()
  5098. plot_fill_color = c_dialog.getColor(initial=current_color)
  5099. if plot_fill_color.isValid() is False:
  5100. return
  5101. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5102. "background-color:%s" % str(plot_fill_color.name()))
  5103. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5104. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5105. self.defaults['global_plot_fill'] = new_val
  5106. def on_pf_color_spinner(self):
  5107. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5108. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5109. self.defaults['global_plot_fill'] = \
  5110. self.defaults['global_plot_fill'][:7] + \
  5111. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5112. self.defaults['global_plot_line'] = \
  5113. self.defaults['global_plot_line'][:7] + \
  5114. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5115. def on_pf_color_slider(self):
  5116. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5117. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5118. def on_pl_color_entry(self):
  5119. self.defaults['global_plot_line'] = \
  5120. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5121. self.defaults['global_plot_line'][7:9]
  5122. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5123. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5124. def on_pl_color_button(self):
  5125. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5126. # print(current_color)
  5127. c_dialog = QtWidgets.QColorDialog()
  5128. plot_line_color = c_dialog.getColor(initial=current_color)
  5129. if plot_line_color.isValid() is False:
  5130. return
  5131. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5132. "background-color:%s" % str(plot_line_color.name()))
  5133. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5134. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5135. self.defaults['global_plot_line'] = new_val_line
  5136. # Setting selection colors (left - right) handlers
  5137. def on_sf_color_entry(self):
  5138. self.defaults['global_sel_fill'] = \
  5139. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5140. self.defaults['global_sel_fill'][7:9]
  5141. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5142. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5143. def on_sf_color_button(self):
  5144. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5145. c_dialog = QtWidgets.QColorDialog()
  5146. plot_fill_color = c_dialog.getColor(initial=current_color)
  5147. if plot_fill_color.isValid() is False:
  5148. return
  5149. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5150. "background-color:%s" % str(plot_fill_color.name()))
  5151. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5152. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5153. self.defaults['global_sel_fill'] = new_val
  5154. def on_sf_color_spinner(self):
  5155. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5156. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5157. self.defaults['global_sel_fill'] = \
  5158. self.defaults['global_sel_fill'][:7] + \
  5159. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5160. self.defaults['global_sel_line'] = \
  5161. self.defaults['global_sel_line'][:7] + \
  5162. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5163. def on_sf_color_slider(self):
  5164. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5165. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5166. def on_sl_color_entry(self):
  5167. self.defaults['global_sel_line'] = \
  5168. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5169. self.defaults['global_sel_line'][7:9]
  5170. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5171. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5172. def on_sl_color_button(self):
  5173. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5174. c_dialog = QtWidgets.QColorDialog()
  5175. plot_line_color = c_dialog.getColor(initial=current_color)
  5176. if plot_line_color.isValid() is False:
  5177. return
  5178. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5179. "background-color:%s" % str(plot_line_color.name()))
  5180. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5181. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5182. self.defaults['global_sel_line'] = new_val_line
  5183. # Setting selection colors (right - left) handlers
  5184. def on_alt_sf_color_entry(self):
  5185. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5186. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5187. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5188. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5189. def on_alt_sf_color_button(self):
  5190. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5191. c_dialog = QtWidgets.QColorDialog()
  5192. plot_fill_color = c_dialog.getColor(initial=current_color)
  5193. if plot_fill_color.isValid() is False:
  5194. return
  5195. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5196. "background-color:%s" % str(plot_fill_color.name()))
  5197. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5198. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5199. self.defaults['global_alt_sel_fill'] = new_val
  5200. def on_alt_sf_color_spinner(self):
  5201. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5202. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5203. self.defaults['global_alt_sel_fill'] = \
  5204. self.defaults['global_alt_sel_fill'][:7] + \
  5205. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5206. self.defaults['global_alt_sel_line'] = \
  5207. self.defaults['global_alt_sel_line'][:7] + \
  5208. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5209. def on_alt_sf_color_slider(self):
  5210. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5211. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5212. def on_alt_sl_color_entry(self):
  5213. self.defaults['global_alt_sel_line'] = \
  5214. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5215. self.defaults['global_alt_sel_line'][7:9]
  5216. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5217. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5218. def on_alt_sl_color_button(self):
  5219. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5220. c_dialog = QtWidgets.QColorDialog()
  5221. plot_line_color = c_dialog.getColor(initial=current_color)
  5222. if plot_line_color.isValid() is False:
  5223. return
  5224. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5225. "background-color:%s" % str(plot_line_color.name()))
  5226. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5227. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5228. self.defaults['global_alt_sel_line'] = new_val_line
  5229. # Setting Editor colors
  5230. def on_draw_color_entry(self):
  5231. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5232. .draw_color_entry.get_value()
  5233. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5234. "background-color:%s" % str(self.defaults['global_draw_color']))
  5235. def on_draw_color_button(self):
  5236. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5237. c_dialog = QtWidgets.QColorDialog()
  5238. draw_color = c_dialog.getColor(initial=current_color)
  5239. if draw_color.isValid() is False:
  5240. return
  5241. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5242. "background-color:%s" % str(draw_color.name()))
  5243. new_val = str(draw_color.name())
  5244. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5245. self.defaults['global_draw_color'] = new_val
  5246. def on_sel_draw_color_entry(self):
  5247. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5248. .sel_draw_color_entry.get_value()
  5249. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5250. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5251. def on_sel_draw_color_button(self):
  5252. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5253. c_dialog = QtWidgets.QColorDialog()
  5254. sel_draw_color = c_dialog.getColor(initial=current_color)
  5255. if sel_draw_color.isValid() is False:
  5256. return
  5257. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5258. "background-color:%s" % str(sel_draw_color.name()))
  5259. new_val_sel = str(sel_draw_color.name())
  5260. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5261. self.defaults['global_sel_draw_color'] = new_val_sel
  5262. def on_proj_color_entry(self):
  5263. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5264. .proj_color_entry.get_value()
  5265. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5266. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5267. def on_proj_color_button(self):
  5268. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5269. c_dialog = QtWidgets.QColorDialog()
  5270. proj_color = c_dialog.getColor(initial=current_color)
  5271. if proj_color.isValid() is False:
  5272. return
  5273. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5274. "background-color:%s" % str(proj_color.name()))
  5275. new_val_sel = str(proj_color.name())
  5276. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5277. self.defaults['global_proj_item_color'] = new_val_sel
  5278. def on_proj_color_dis_entry(self):
  5279. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5280. .proj_color_dis_entry.get_value()
  5281. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5282. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5283. def on_proj_color_dis_button(self):
  5284. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5285. c_dialog = QtWidgets.QColorDialog()
  5286. proj_color = c_dialog.getColor(initial=current_color)
  5287. if proj_color.isValid() is False:
  5288. return
  5289. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5290. "background-color:%s" % str(proj_color.name()))
  5291. new_val_sel = str(proj_color.name())
  5292. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5293. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5294. def on_annotation_fontcolor_entry(self):
  5295. self.defaults['cncjob_annotation_fontcolor'] = \
  5296. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5297. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5298. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5299. def on_annotation_fontcolor_button(self):
  5300. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5301. c_dialog = QtWidgets.QColorDialog()
  5302. annotation_color = c_dialog.getColor(initial=current_color)
  5303. if annotation_color.isValid() is False:
  5304. return
  5305. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5306. "background-color:%s" % str(annotation_color.name()))
  5307. new_val_sel = str(annotation_color.name())
  5308. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5309. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5310. def on_film_color_entry(self):
  5311. self.defaults['tools_film_color'] = \
  5312. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5313. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5314. "background-color:%s" % str(self.defaults['tools_film_color']))
  5315. def on_film_color_button(self):
  5316. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5317. c_dialog = QtWidgets.QColorDialog()
  5318. film_color = c_dialog.getColor(initial=current_color)
  5319. if film_color.isValid() is False:
  5320. return
  5321. # if new color is different then mark that the Preferences are changed
  5322. if film_color != current_color:
  5323. self.on_preferences_edited()
  5324. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5325. "background-color:%s" % str(film_color.name()))
  5326. new_val_sel = str(film_color.name())
  5327. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5328. self.defaults['tools_film_color'] = new_val_sel
  5329. def on_splash_changed(self, state):
  5330. settings = QSettings("Open Source", "FlatCAM")
  5331. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5332. # This will write the setting to the platform specific storage.
  5333. del settings
  5334. def on_notebook_tab_rmb_click(self, checked):
  5335. self.ui.notebook.set_detachable(val=checked)
  5336. self.defaults["global_tabs_detachable"] = checked
  5337. self.ui.plot_tab_area.set_detachable(val=checked)
  5338. self.defaults["global_tabs_detachable"] = checked
  5339. def on_deselect_all(self):
  5340. self.collection.set_all_inactive()
  5341. self.delete_selection_shape()
  5342. def on_workspace_modified(self):
  5343. self.save_defaults(silent=True)
  5344. self.plotcanvas.draw_workspace()
  5345. def on_workspace(self):
  5346. self.report_usage("on_workspace()")
  5347. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5348. self.plotcanvas.restore_workspace()
  5349. else:
  5350. self.plotcanvas.delete_workspace()
  5351. self.save_defaults(silent=True)
  5352. def on_workspace_menu(self):
  5353. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5354. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5355. else:
  5356. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5357. self.on_workspace()
  5358. def on_layout(self, index=None, lay=None):
  5359. """
  5360. Set the toolbars layout (location)
  5361. :param index:
  5362. :param lay: type of layout to be set on the toolbard
  5363. :return: None
  5364. """
  5365. self.report_usage("on_layout()")
  5366. if lay:
  5367. current_layout = lay
  5368. else:
  5369. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5370. settings = QSettings("Open Source", "FlatCAM")
  5371. settings.setValue('layout', current_layout)
  5372. # This will write the setting to the platform specific storage.
  5373. del settings
  5374. # first remove the toolbars:
  5375. try:
  5376. self.ui.removeToolBar(self.ui.toolbarfile)
  5377. self.ui.removeToolBar(self.ui.toolbargeo)
  5378. self.ui.removeToolBar(self.ui.toolbarview)
  5379. self.ui.removeToolBar(self.ui.toolbarshell)
  5380. self.ui.removeToolBar(self.ui.toolbartools)
  5381. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5382. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5383. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5384. self.ui.removeToolBar(self.ui.snap_toolbar)
  5385. self.ui.removeToolBar(self.ui.toolbarshell)
  5386. except Exception as e:
  5387. pass
  5388. if current_layout == 'standard':
  5389. # ## TOOLBAR INSTALLATION # ##
  5390. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5391. self.ui.toolbarfile.setObjectName('File_TB')
  5392. self.ui.addToolBar(self.ui.toolbarfile)
  5393. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5394. self.ui.toolbargeo.setObjectName('Edit_TB')
  5395. self.ui.addToolBar(self.ui.toolbargeo)
  5396. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5397. self.ui.toolbarview.setObjectName('View_TB')
  5398. self.ui.addToolBar(self.ui.toolbarview)
  5399. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5400. self.ui.toolbarshell.setObjectName('Shell_TB')
  5401. self.ui.addToolBar(self.ui.toolbarshell)
  5402. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5403. self.ui.toolbartools.setObjectName('Tools_TB')
  5404. self.ui.addToolBar(self.ui.toolbartools)
  5405. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5406. # self.ui.exc_edit_toolbar.setVisible(False)
  5407. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5408. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5409. self.ui.addToolBarBreak()
  5410. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5411. # self.ui.geo_edit_toolbar.setVisible(False)
  5412. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5413. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5414. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5415. # self.ui.grb_edit_toolbar.setVisible(False)
  5416. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5417. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5418. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5419. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5420. # self.ui.snap_toolbar.setMaximumHeight(30)
  5421. self.ui.addToolBar(self.ui.snap_toolbar)
  5422. self.ui.corner_snap_btn.setVisible(False)
  5423. self.ui.snap_magnet.setVisible(False)
  5424. elif current_layout == 'compact':
  5425. # ## TOOLBAR INSTALLATION # ##
  5426. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5427. self.ui.toolbarfile.setObjectName('File_TB')
  5428. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5429. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5430. self.ui.toolbargeo.setObjectName('Edit_TB')
  5431. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5432. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5433. self.ui.toolbarshell.setObjectName('Shell_TB')
  5434. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5435. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5436. self.ui.toolbartools.setObjectName('Tools_TB')
  5437. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5438. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5439. # self.ui.geo_edit_toolbar.setVisible(False)
  5440. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5441. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5442. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5443. self.ui.toolbarview.setObjectName('View_TB')
  5444. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5445. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5446. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5447. # self.ui.grb_edit_toolbar.setVisible(False)
  5448. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5449. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5450. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5451. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5452. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5453. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5454. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5455. self.ui.snap_toolbar.setMaximumHeight(30)
  5456. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5457. self.ui.corner_snap_btn.setVisible(True)
  5458. self.ui.snap_magnet.setVisible(True)
  5459. # add all the actions to the toolbars
  5460. self.ui.populate_toolbars()
  5461. # reconnect all the signals to the toolbar actions
  5462. self.connect_toolbar_signals()
  5463. self.ui.grid_snap_btn.setChecked(True)
  5464. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5465. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5466. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5467. self.ui.grid_gap_link_cb.setChecked(True)
  5468. def on_cursor_type(self, val):
  5469. """
  5470. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5471. :return: None
  5472. """
  5473. self.app_cursor.enabled = False
  5474. if val == 'small':
  5475. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5476. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5477. self.app_cursor = self.plotcanvas.new_cursor()
  5478. else:
  5479. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5480. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5481. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5482. if self.ui.grid_snap_btn.isChecked():
  5483. self.app_cursor.enabled = True
  5484. else:
  5485. self.app_cursor.enabled = False
  5486. def on_cnc_custom_parameters(self, signal_text):
  5487. if signal_text == 'Parameters':
  5488. return
  5489. else:
  5490. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5491. def on_save_button(self):
  5492. log.debug("App.on_save_button() --> Saving preferences to file.")
  5493. self.preferences_changed_flag = False
  5494. self.save_defaults(silent=False)
  5495. # load the defaults so they are updated into the app
  5496. self.load_defaults(filename='current_defaults')
  5497. # Re-fresh project options
  5498. self.on_options_app2project()
  5499. settings = QSettings("Open Source", "FlatCAM")
  5500. # save the notebook font size
  5501. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5502. settings.setValue('notebook_font_size', fsize)
  5503. # save the axis font size
  5504. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5505. settings.setValue('axis_font_size', g_fsize)
  5506. # save the textbox font size
  5507. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5508. settings.setValue('textbox_font_size', tb_fsize)
  5509. # This will write the setting to the platform specific storage.
  5510. del settings
  5511. def on_tool_add_keypress(self):
  5512. # ## Current application units in Upper Case
  5513. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5514. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5515. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5516. if notebook_widget_name == 'selected_tab':
  5517. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5518. # Tool add works for Geometry only if Advanced is True in Preferences
  5519. if self.defaults["global_app_level"] == 'a':
  5520. tool_add_popup = FCInputDialog(title="New Tool ...",
  5521. text='Enter a Tool Diameter:',
  5522. min=0.0000, max=99.9999, decimals=4)
  5523. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5524. val, ok = tool_add_popup.get_value()
  5525. if ok:
  5526. if float(val) == 0:
  5527. self.inform.emit('[WARNING_NOTCL] %s' %
  5528. _("Please enter a tool diameter with non-zero value, in Float format."))
  5529. return
  5530. self.collection.get_active().on_tool_add(dia=float(val))
  5531. else:
  5532. self.inform.emit('[WARNING_NOTCL] %s...' %
  5533. _("Adding Tool cancelled"))
  5534. else:
  5535. msgbox = QtWidgets.QMessageBox()
  5536. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5537. "Go to Preferences -> General - Show Advanced Options."))
  5538. msgbox.setWindowTitle("Tool adding ...")
  5539. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5540. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5541. msgbox.setDefaultButton(bt_ok)
  5542. msgbox.exec_()
  5543. # work only if the notebook tab on focus is the Tools_Tab
  5544. if notebook_widget_name == 'tool_tab':
  5545. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5546. tool_add_popup = FCInputDialog(title="New Tool ...",
  5547. text='Enter a Tool Diameter:',
  5548. min=0.0000, max=99.9999, decimals=4)
  5549. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5550. val, ok = tool_add_popup.get_value()
  5551. # and only if the tool is NCC Tool
  5552. if tool_widget == self.ncclear_tool.toolName:
  5553. if ok:
  5554. if float(val) == 0:
  5555. self.inform.emit('[WARNING_NOTCL] %s' %
  5556. _("Please enter a tool diameter with non-zero value, in Float format."))
  5557. return
  5558. self.ncclear_tool.on_tool_add(dia=float(val))
  5559. else:
  5560. self.inform.emit('[WARNING_NOTCL] %s...' %
  5561. _("Adding Tool cancelled"))
  5562. # and only if the tool is Paint Area Tool
  5563. elif tool_widget == self.paint_tool.toolName:
  5564. if ok:
  5565. if float(val) == 0:
  5566. self.inform.emit('[WARNING_NOTCL] %s' %
  5567. _("Please enter a tool diameter with non-zero value, in Float format."))
  5568. return
  5569. self.paint_tool.on_tool_add(dia=float(val))
  5570. else:
  5571. self.inform.emit('[WARNING_NOTCL] %s...' %
  5572. _("Adding Tool cancelled"))
  5573. # and only if the tool is Solder Paste Dispensing Tool
  5574. elif tool_widget == self.paste_tool.toolName:
  5575. if ok:
  5576. if float(val) == 0:
  5577. self.inform.emit('[WARNING_NOTCL] %s' %
  5578. _("Please enter a tool diameter with non-zero value, in Float format."))
  5579. return
  5580. self.paste_tool.on_tool_add(dia=float(val))
  5581. else:
  5582. self.inform.emit('[WARNING_NOTCL] %s...' %
  5583. _("Adding Tool cancelled"))
  5584. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5585. # See description bellow.
  5586. def on_delete_keypress(self):
  5587. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5588. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5589. if notebook_widget_name == 'selected_tab':
  5590. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5591. self.collection.get_active().on_tool_delete()
  5592. # work only if the notebook tab on focus is the Tools_Tab
  5593. elif notebook_widget_name == 'tool_tab':
  5594. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5595. # and only if the tool is NCC Tool
  5596. if tool_widget == self.ncclear_tool.toolName:
  5597. self.ncclear_tool.on_tool_delete()
  5598. # and only if the tool is Paint Tool
  5599. elif tool_widget == self.paint_tool.toolName:
  5600. self.paint_tool.on_tool_delete()
  5601. # and only if the tool is Solder Paste Dispensing Tool
  5602. elif tool_widget == self.paste_tool.toolName:
  5603. self.paste_tool.on_tool_delete()
  5604. else:
  5605. self.on_delete()
  5606. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5607. # some screens you have to be careful where you hover with your mouse.
  5608. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5609. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5610. # Complicated, I know :)
  5611. def on_delete(self):
  5612. """
  5613. Delete the currently selected FlatCAMObjs.
  5614. :return: None
  5615. """
  5616. self.report_usage("on_delete()")
  5617. response = None
  5618. bt_ok = None
  5619. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5620. # a geometry object before we update it.
  5621. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5622. and self.grb_editor.editor_active is False:
  5623. if self.defaults["global_delete_confirmation"] is True:
  5624. msgbox = QtWidgets.QMessageBox()
  5625. msgbox.setWindowTitle(_("Delete objects"))
  5626. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5627. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5628. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5629. "the selected objects?"))
  5630. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5631. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5632. msgbox.setDefaultButton(bt_ok)
  5633. msgbox.exec_()
  5634. response = msgbox.clickedButton()
  5635. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5636. if self.collection.get_active():
  5637. self.log.debug("App.on_delete()")
  5638. while self.collection.get_active():
  5639. obj_active = self.collection.get_active()
  5640. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5641. if isinstance(obj_active, FlatCAMGerber):
  5642. for el in obj_active.mark_shapes:
  5643. obj_active.mark_shapes[el].clear(update=True)
  5644. obj_active.mark_shapes[el].enabled = False
  5645. # obj_active.mark_shapes[el] = None
  5646. del el
  5647. elif isinstance(obj_active, FlatCAMCNCjob):
  5648. try:
  5649. obj_active.annotation.clear(update=True)
  5650. obj_active.annotation.enabled = False
  5651. except AttributeError:
  5652. pass
  5653. self.delete_first_selected()
  5654. self.inform.emit('%s...' %
  5655. _("Object(s) deleted"))
  5656. # make sure that the selection shape is deleted, too
  5657. self.delete_selection_shape()
  5658. else:
  5659. self.inform.emit(_("Failed. No object(s) selected..."))
  5660. else:
  5661. self.inform.emit(_("Save the work in Editor and try again ..."))
  5662. def delete_first_selected(self):
  5663. # Keep this for later
  5664. try:
  5665. sel_obj = self.collection.get_active()
  5666. name = sel_obj.options["name"]
  5667. isPlotted = sel_obj.options["plot"]
  5668. except AttributeError:
  5669. self.log.debug("Nothing selected for deletion")
  5670. return
  5671. if self.is_legacy is True:
  5672. # Remove plot only if the object was plotted otherwise delaxes will fail
  5673. if isPlotted:
  5674. try:
  5675. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5676. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5677. except Exception as e:
  5678. log.debug("App.delete_first_selected() --> %s" % str(e))
  5679. self.plotcanvas.auto_adjust_axes()
  5680. # Remove from dictionary
  5681. self.collection.delete_active()
  5682. # Clear form
  5683. self.setup_component_editor()
  5684. self.inform.emit('%s: %s' %
  5685. (_("Object deleted"), name))
  5686. def on_set_origin(self):
  5687. """
  5688. Set the origin to the left mouse click position
  5689. :return: None
  5690. """
  5691. # display the message for the user
  5692. # and ask him to click on the desired position
  5693. self.report_usage("on_set_origin()")
  5694. def origin_replot():
  5695. def worker_task():
  5696. with self.proc_container.new('%s...' % _("Plotting")):
  5697. for obj in self.collection.get_list():
  5698. obj.plot()
  5699. self.plotcanvas.fit_view()
  5700. if self.is_legacy:
  5701. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5702. else:
  5703. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5704. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5705. self.inform.emit(_('Click to set the origin ...'))
  5706. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5707. # first disconnect it as it may have been used by something else
  5708. try:
  5709. self.replot_signal.disconnect()
  5710. except TypeError:
  5711. pass
  5712. self.replot_signal[list].connect(origin_replot)
  5713. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  5714. """
  5715. :param event:
  5716. :param location:
  5717. :param noplot:
  5718. :param use_thread:
  5719. :return:
  5720. """
  5721. noplot_sig = noplot
  5722. def worker_task():
  5723. with self.proc_container.new(_("Setting Origin...")):
  5724. for obj in self.collection.get_list():
  5725. obj.offset((x, y))
  5726. self.object_changed.emit(obj)
  5727. # Update the object bounding box options
  5728. a, b, c, d = obj.bounds()
  5729. obj.options['xmin'] = a
  5730. obj.options['ymin'] = b
  5731. obj.options['xmax'] = c
  5732. obj.options['ymax'] = d
  5733. self.inform.emit('[success] %s...' %
  5734. _('Origin set'))
  5735. if noplot_sig is False:
  5736. self.replot_signal.emit([])
  5737. if location is not None:
  5738. if len(location) != 2:
  5739. self.inform.emit('[ERROR_NOTCL] %s...' %
  5740. _("Origin coordinates specified but incomplete."))
  5741. return 'fail'
  5742. x, y = location
  5743. if use_thread is True:
  5744. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5745. else:
  5746. worker_task()
  5747. self.should_we_save = True
  5748. return
  5749. if event.button == 1:
  5750. if self.is_legacy is False:
  5751. event_pos = event.pos
  5752. else:
  5753. event_pos = (event.xdata, event.ydata)
  5754. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5755. if self.grid_status() == True:
  5756. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5757. else:
  5758. pos = pos_canvas
  5759. x = 0 - pos[0]
  5760. y = 0 - pos[1]
  5761. if use_thread is True:
  5762. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5763. else:
  5764. worker_task()
  5765. self.should_we_save = True
  5766. def on_jump_to(self, custom_location=None, fit_center=True):
  5767. """
  5768. Jump to a location by setting the mouse cursor location
  5769. :return:
  5770. """
  5771. self.report_usage("on_jump_to()")
  5772. # if self.is_legacy is True:
  5773. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  5774. # return
  5775. if not custom_location:
  5776. dia_box_location = None
  5777. try:
  5778. dia_box_location = eval(self.clipboard.text())
  5779. except Exception as e:
  5780. pass
  5781. if type(dia_box_location) == tuple:
  5782. dia_box_location = str(dia_box_location)
  5783. else:
  5784. dia_box_location = None
  5785. dia_box = Dialog_box(title=_("Jump to ..."),
  5786. label=_("Enter the coordinates in format X,Y:"),
  5787. icon=QtGui.QIcon('share/jump_to16.png'),
  5788. initial_text=dia_box_location)
  5789. if dia_box.ok is True:
  5790. try:
  5791. location = eval(dia_box.location)
  5792. if not isinstance(location, tuple):
  5793. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5794. return
  5795. except:
  5796. return
  5797. else:
  5798. return
  5799. else:
  5800. location = custom_location
  5801. if fit_center:
  5802. self.plotcanvas.fit_center(loc=location)
  5803. cursor = QtGui.QCursor()
  5804. if self.is_legacy is False:
  5805. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5806. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5807. j_pos = (canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5808. cursor.setPos(j_pos[0], j_pos[1])
  5809. else:
  5810. # find the canvas origin which is in the top left corner
  5811. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5812. # determine the coordinates for the lowest left point of the canvas
  5813. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5814. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  5815. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  5816. # canvas) and the point (width, height) is in the top-right location
  5817. loc = self.plotcanvas.axes.transData.transform_point(location)
  5818. j_pos = (x0 + loc[0], y0 - loc[1])
  5819. cursor.setPos(j_pos[0], j_pos[1])
  5820. if self.grid_status() == True:
  5821. # Update cursor
  5822. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  5823. symbol='++', edge_color='black', size=self.defaults["global_cursor_size"])
  5824. # Set the position label
  5825. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5826. "<b>Y</b>: %.4f" % (location[0], location[1]))
  5827. # Set the relative position label
  5828. dx = location[0] - float(self.rel_point1[0])
  5829. dy = location[1] - float(self.rel_point1[1])
  5830. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5831. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5832. self.inform.emit('[success] %s' %
  5833. _("Done."))
  5834. return location
  5835. def on_copy_object(self):
  5836. self.report_usage("on_copy_object()")
  5837. def initialize(obj_init, app):
  5838. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5839. try:
  5840. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5841. except AttributeError:
  5842. pass
  5843. try:
  5844. obj_init.apertures = deepcopy(obj.apertures)
  5845. except AttributeError:
  5846. pass
  5847. try:
  5848. if obj.tools:
  5849. obj_init.tools = deepcopy(obj.tools)
  5850. except Exception as e:
  5851. log.debug("App.on_copy_object() --> %s" % str(e))
  5852. def initialize_excellon(obj_init, app):
  5853. obj_init.tools = deepcopy(obj.tools)
  5854. # drills are offset, so they need to be deep copied
  5855. obj_init.drills = deepcopy(obj.drills)
  5856. # slots are offset, so they need to be deep copied
  5857. obj_init.slots = deepcopy(obj.slots)
  5858. obj_init.create_geometry()
  5859. def initialize_script(obj_init, app_obj):
  5860. obj_init.source_file = deepcopy(obj.source_file)
  5861. def initialize_document(obj_init, app_obj):
  5862. obj_init.source_file = deepcopy(obj.source_file)
  5863. for obj in self.collection.get_selected():
  5864. obj_name = obj.options["name"]
  5865. try:
  5866. if isinstance(obj, FlatCAMExcellon):
  5867. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5868. elif isinstance(obj, FlatCAMGerber):
  5869. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5870. elif isinstance(obj, FlatCAMGeometry):
  5871. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5872. elif isinstance(obj, FlatCAMScript):
  5873. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  5874. elif isinstance(obj, FlatCAMDocument):
  5875. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  5876. except Exception as e:
  5877. return "Operation failed: %s" % str(e)
  5878. def on_copy_object2(self, custom_name):
  5879. def initialize_geometry(obj_init, app):
  5880. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5881. try:
  5882. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5883. except AttributeError:
  5884. pass
  5885. try:
  5886. obj_init.apertures = deepcopy(obj.apertures)
  5887. except AttributeError:
  5888. pass
  5889. try:
  5890. if obj.tools:
  5891. obj_init.tools = deepcopy(obj.tools)
  5892. except Exception as e:
  5893. log.debug("on_copy_object2() --> %s" % str(e))
  5894. def initialize_gerber(obj_init, app):
  5895. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5896. obj_init.apertures = deepcopy(obj.apertures)
  5897. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5898. def initialize_excellon(obj_init, app):
  5899. obj_init.tools = deepcopy(obj.tools)
  5900. # drills are offset, so they need to be deep copied
  5901. obj_init.drills = deepcopy(obj.drills)
  5902. # slots are offset, so they need to be deep copied
  5903. obj_init.slots = deepcopy(obj.slots)
  5904. obj_init.create_geometry()
  5905. for obj in self.collection.get_selected():
  5906. obj_name = obj.options["name"]
  5907. try:
  5908. if isinstance(obj, FlatCAMExcellon):
  5909. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5910. elif isinstance(obj, FlatCAMGerber):
  5911. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5912. elif isinstance(obj, FlatCAMGeometry):
  5913. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5914. except Exception as e:
  5915. return "Operation failed: %s" % str(e)
  5916. def on_rename_object(self, text):
  5917. self.report_usage("on_rename_object()")
  5918. named_obj = self.collection.get_active()
  5919. for obj in named_obj:
  5920. if obj is list:
  5921. self.on_rename_object(text)
  5922. else:
  5923. try:
  5924. obj.options['name'] = text
  5925. except Exception as e:
  5926. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5927. def convert_any2geo(self):
  5928. self.report_usage("convert_any2geo()")
  5929. def initialize(obj_init, app):
  5930. obj_init.solid_geometry = obj.solid_geometry
  5931. try:
  5932. obj_init.follow_geometry = obj.follow_geometry
  5933. except AttributeError:
  5934. pass
  5935. try:
  5936. obj_init.apertures = obj.apertures
  5937. except AttributeError:
  5938. pass
  5939. try:
  5940. if obj.tools:
  5941. obj_init.tools = obj.tools
  5942. except AttributeError:
  5943. pass
  5944. def initialize_excellon(obj_init, app):
  5945. # objs = self.collection.get_selected()
  5946. # FlatCAMGeometry.merge(objs, obj)
  5947. solid_geo = []
  5948. for tool in obj.tools:
  5949. for geo in obj.tools[tool]['solid_geometry']:
  5950. solid_geo.append(geo)
  5951. obj_init.solid_geometry = deepcopy(solid_geo)
  5952. if not self.collection.get_selected():
  5953. log.warning("App.convert_any2geo --> No object selected")
  5954. self.inform.emit('[WARNING_NOTCL] %s' %
  5955. _("No object is selected. Select an object and try again."))
  5956. return
  5957. for obj in self.collection.get_selected():
  5958. obj_name = obj.options["name"]
  5959. try:
  5960. if isinstance(obj, FlatCAMExcellon):
  5961. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5962. else:
  5963. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5964. except Exception as e:
  5965. return "Operation failed: %s" % str(e)
  5966. def convert_any2gerber(self):
  5967. self.report_usage("convert_any2gerber()")
  5968. def initialize_geometry(obj_init, app):
  5969. apertures = {}
  5970. apid = 0
  5971. apertures[str(apid)] = {}
  5972. apertures[str(apid)]['geometry'] = []
  5973. for obj_orig in obj.solid_geometry:
  5974. new_elem = dict()
  5975. new_elem['solid'] = obj_orig
  5976. new_elem['follow'] = obj_orig.exterior
  5977. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5978. apertures[str(apid)]['size'] = 0.0
  5979. apertures[str(apid)]['type'] = 'C'
  5980. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5981. obj_init.apertures = deepcopy(apertures)
  5982. def initialize_excellon(obj_init, app):
  5983. apertures = {}
  5984. apid = 10
  5985. for tool in obj.tools:
  5986. apertures[str(apid)] = {}
  5987. apertures[str(apid)]['geometry'] = []
  5988. for geo in obj.tools[tool]['solid_geometry']:
  5989. new_el = dict()
  5990. new_el['solid'] = geo
  5991. new_el['follow'] = geo.exterior
  5992. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5993. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5994. apertures[str(apid)]['type'] = 'C'
  5995. apid += 1
  5996. # create solid_geometry
  5997. solid_geometry = []
  5998. for apid in apertures:
  5999. for geo_el in apertures[apid]['geometry']:
  6000. solid_geometry.append(geo_el['solid'])
  6001. solid_geometry = MultiPolygon(solid_geometry)
  6002. solid_geometry = solid_geometry.buffer(0.0000001)
  6003. obj_init.solid_geometry = deepcopy(solid_geometry)
  6004. obj_init.apertures = deepcopy(apertures)
  6005. # clear the working objects (perhaps not necessary due of Python GC)
  6006. apertures.clear()
  6007. if not self.collection.get_selected():
  6008. log.warning("App.convert_any2gerber --> No object selected")
  6009. self.inform.emit('[WARNING_NOTCL] %s' %
  6010. _("No object is selected. Select an object and try again."))
  6011. return
  6012. for obj in self.collection.get_selected():
  6013. obj_name = obj.options["name"]
  6014. try:
  6015. if isinstance(obj, FlatCAMExcellon):
  6016. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6017. elif isinstance(obj, FlatCAMGeometry):
  6018. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6019. else:
  6020. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6021. except Exception as e:
  6022. return "Operation failed: %s" % str(e)
  6023. def abort_all_tasks(self):
  6024. if self.abort_flag is False:
  6025. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6026. self.abort_flag = True
  6027. def app_is_idle(self):
  6028. if self.abort_flag:
  6029. self.inform.emit('[WARNING_NOTCL] %s' %
  6030. _("The current task was gracefully closed on user request..."))
  6031. self.abort_flag = False
  6032. def on_selectall(self):
  6033. self.report_usage("on_selectall()")
  6034. # delete the possible selection box around a possible selected object
  6035. self.delete_selection_shape()
  6036. for name in self.collection.get_names():
  6037. self.collection.set_active(name)
  6038. curr_sel_obj = self.collection.get_by_name(name)
  6039. # create the selection box around the selected object
  6040. if self.defaults['global_selection_shape'] is True:
  6041. self.draw_selection_shape(curr_sel_obj)
  6042. def on_preferences(self):
  6043. # add the tab if it was closed
  6044. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6045. # delete the absolute and relative position and messages in the infobar
  6046. self.ui.position_label.setText("")
  6047. self.ui.rel_position_label.setText("")
  6048. # Switch plot_area to preferences page
  6049. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6050. # self.ui.show()
  6051. # this disconnect() is done so the slot will be connected only once
  6052. try:
  6053. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  6054. except (TypeError, AttributeError):
  6055. pass
  6056. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  6057. # detect changes in the preferences
  6058. for idx in range(self.ui.pref_tab_area.count()):
  6059. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6060. try:
  6061. try:
  6062. tb.textEdited.disconnect(self.on_preferences_edited)
  6063. except (TypeError, AttributeError):
  6064. pass
  6065. tb.textEdited.connect(self.on_preferences_edited)
  6066. except AttributeError:
  6067. pass
  6068. try:
  6069. try:
  6070. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6071. except (TypeError, AttributeError):
  6072. pass
  6073. tb.modificationChanged.connect(self.on_preferences_edited)
  6074. except AttributeError:
  6075. pass
  6076. try:
  6077. try:
  6078. tb.toggled.disconnect(self.on_preferences_edited)
  6079. except (TypeError, AttributeError):
  6080. pass
  6081. tb.toggled.connect(self.on_preferences_edited)
  6082. except AttributeError:
  6083. pass
  6084. try:
  6085. try:
  6086. tb.valueChanged.disconnect(self.on_preferences_edited)
  6087. except (TypeError, AttributeError):
  6088. pass
  6089. tb.valueChanged.connect(self.on_preferences_edited)
  6090. except AttributeError:
  6091. pass
  6092. try:
  6093. try:
  6094. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6095. except (TypeError, AttributeError):
  6096. pass
  6097. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6098. except AttributeError:
  6099. pass
  6100. def on_preferences_edited(self):
  6101. self.inform.emit('[WARNING_NOTCL] %s' %
  6102. _("Preferences edited but not saved."))
  6103. self.preferences_changed_flag = True
  6104. def on_preferences_closed(self):
  6105. # disconnect
  6106. for idx in range(self.ui.pref_tab_area.count()):
  6107. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6108. try:
  6109. tb.textEdited.disconnect(self.on_preferences_edited)
  6110. except (TypeError, AttributeError):
  6111. pass
  6112. try:
  6113. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6114. except (TypeError, AttributeError):
  6115. pass
  6116. try:
  6117. tb.toggled.disconnect(self.on_preferences_edited)
  6118. except (TypeError, AttributeError):
  6119. pass
  6120. try:
  6121. tb.valueChanged.disconnect(self.on_preferences_edited)
  6122. except (TypeError, AttributeError):
  6123. pass
  6124. try:
  6125. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6126. except (TypeError, AttributeError):
  6127. pass
  6128. if self.preferences_changed_flag is True:
  6129. msgbox = QtWidgets.QMessageBox()
  6130. msgbox.setText(_("One or more values are changed.\n"
  6131. "Do you want to save the Preferences?"))
  6132. msgbox.setWindowTitle(_("Save Preferences"))
  6133. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6134. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6135. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6136. msgbox.setDefaultButton(bt_yes)
  6137. msgbox.exec_()
  6138. response = msgbox.clickedButton()
  6139. if response == bt_yes:
  6140. self.on_save_button()
  6141. self.inform.emit('[success] %s' %
  6142. _("Preferences saved."))
  6143. else:
  6144. self.preferences_changed_flag = False
  6145. return
  6146. def on_flipy(self):
  6147. self.report_usage("on_flipy()")
  6148. obj_list = self.collection.get_selected()
  6149. xminlist = []
  6150. yminlist = []
  6151. xmaxlist = []
  6152. ymaxlist = []
  6153. if not obj_list:
  6154. self.inform.emit('[WARNING_NOTCL] %s' %
  6155. _("No object selected to Flip on Y axis."))
  6156. else:
  6157. try:
  6158. # first get a bounding box to fit all
  6159. for obj in obj_list:
  6160. xmin, ymin, xmax, ymax = obj.bounds()
  6161. xminlist.append(xmin)
  6162. yminlist.append(ymin)
  6163. xmaxlist.append(xmax)
  6164. ymaxlist.append(ymax)
  6165. # get the minimum x,y and maximum x,y for all objects selected
  6166. xminimal = min(xminlist)
  6167. yminimal = min(yminlist)
  6168. xmaximal = max(xmaxlist)
  6169. ymaximal = max(ymaxlist)
  6170. px = 0.5 * (xminimal + xmaximal)
  6171. py = 0.5 * (yminimal + ymaximal)
  6172. # execute mirroring
  6173. for obj in obj_list:
  6174. obj.mirror('X', [px, py])
  6175. obj.plot()
  6176. self.object_changed.emit(obj)
  6177. self.inform.emit('[success] %s' %
  6178. _("Flip on Y axis done."))
  6179. except Exception as e:
  6180. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6181. (_("Flip action was not executed."), str(e)))
  6182. return
  6183. def on_flipx(self):
  6184. self.report_usage("on_flipx()")
  6185. obj_list = self.collection.get_selected()
  6186. xminlist = []
  6187. yminlist = []
  6188. xmaxlist = []
  6189. ymaxlist = []
  6190. if not obj_list:
  6191. self.inform.emit('[WARNING_NOTCL] %s' %
  6192. _("No object selected to Flip on X axis."))
  6193. else:
  6194. try:
  6195. # first get a bounding box to fit all
  6196. for obj in obj_list:
  6197. xmin, ymin, xmax, ymax = obj.bounds()
  6198. xminlist.append(xmin)
  6199. yminlist.append(ymin)
  6200. xmaxlist.append(xmax)
  6201. ymaxlist.append(ymax)
  6202. # get the minimum x,y and maximum x,y for all objects selected
  6203. xminimal = min(xminlist)
  6204. yminimal = min(yminlist)
  6205. xmaximal = max(xmaxlist)
  6206. ymaximal = max(ymaxlist)
  6207. px = 0.5 * (xminimal + xmaximal)
  6208. py = 0.5 * (yminimal + ymaximal)
  6209. # execute mirroring
  6210. for obj in obj_list:
  6211. obj.mirror('Y', [px, py])
  6212. obj.plot()
  6213. self.object_changed.emit(obj)
  6214. self.inform.emit('[success] %s' %
  6215. _("Flip on X axis done."))
  6216. except Exception as e:
  6217. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6218. (_("Flip action was not executed."), str(e)))
  6219. return
  6220. def on_rotate(self, silent=False, preset=None):
  6221. self.report_usage("on_rotate()")
  6222. obj_list = self.collection.get_selected()
  6223. xminlist = []
  6224. yminlist = []
  6225. xmaxlist = []
  6226. ymaxlist = []
  6227. if not obj_list:
  6228. self.inform.emit('[WARNING_NOTCL] %s' %
  6229. _("No object selected to Rotate."))
  6230. else:
  6231. if silent is False:
  6232. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6233. min=-360, max=360, decimals=4,
  6234. init_val=float(self.defaults['tools_transform_rotate']))
  6235. num, ok = rotatebox.get_value()
  6236. else:
  6237. num = preset
  6238. ok = True
  6239. if ok:
  6240. try:
  6241. # first get a bounding box to fit all
  6242. for obj in obj_list:
  6243. xmin, ymin, xmax, ymax = obj.bounds()
  6244. xminlist.append(xmin)
  6245. yminlist.append(ymin)
  6246. xmaxlist.append(xmax)
  6247. ymaxlist.append(ymax)
  6248. # get the minimum x,y and maximum x,y for all objects selected
  6249. xminimal = min(xminlist)
  6250. yminimal = min(yminlist)
  6251. xmaximal = max(xmaxlist)
  6252. ymaximal = max(ymaxlist)
  6253. px = 0.5 * (xminimal + xmaximal)
  6254. py = 0.5 * (yminimal + ymaximal)
  6255. for sel_obj in obj_list:
  6256. sel_obj.rotate(-float(num), point=(px, py))
  6257. sel_obj.plot()
  6258. self.object_changed.emit(sel_obj)
  6259. self.inform.emit('[success] %s' %
  6260. _("Rotation done."))
  6261. except Exception as e:
  6262. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6263. (_("Rotation movement was not executed."), str(e)))
  6264. return
  6265. def on_skewx(self):
  6266. self.report_usage("on_skewx()")
  6267. obj_list = self.collection.get_selected()
  6268. xminlist = []
  6269. yminlist = []
  6270. if not obj_list:
  6271. self.inform.emit('[WARNING_NOTCL] %s' %
  6272. _("No object selected to Skew/Shear on X axis."))
  6273. else:
  6274. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6275. min=-360, max=360, decimals=4,
  6276. init_val=float(self.defaults['tools_transform_skew_x']))
  6277. num, ok = skewxbox.get_value()
  6278. if ok:
  6279. # first get a bounding box to fit all
  6280. for obj in obj_list:
  6281. xmin, ymin, xmax, ymax = obj.bounds()
  6282. xminlist.append(xmin)
  6283. yminlist.append(ymin)
  6284. # get the minimum x,y and maximum x,y for all objects selected
  6285. xminimal = min(xminlist)
  6286. yminimal = min(yminlist)
  6287. for obj in obj_list:
  6288. obj.skew(num, 0, point=(xminimal, yminimal))
  6289. obj.plot()
  6290. self.object_changed.emit(obj)
  6291. self.inform.emit('[success] %s' %
  6292. _("Skew on X axis done."))
  6293. def on_skewy(self):
  6294. self.report_usage("on_skewy()")
  6295. obj_list = self.collection.get_selected()
  6296. xminlist = []
  6297. yminlist = []
  6298. if not obj_list:
  6299. self.inform.emit('[WARNING_NOTCL] %s' %
  6300. _("No object selected to Skew/Shear on Y axis."))
  6301. else:
  6302. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6303. min=-360, max=360, decimals=4,
  6304. init_val=float(self.defaults['tools_transform_skew_y']))
  6305. num, ok = skewybox.get_value()
  6306. if ok:
  6307. # first get a bounding box to fit all
  6308. for obj in obj_list:
  6309. xmin, ymin, xmax, ymax = obj.bounds()
  6310. xminlist.append(xmin)
  6311. yminlist.append(ymin)
  6312. # get the minimum x,y and maximum x,y for all objects selected
  6313. xminimal = min(xminlist)
  6314. yminimal = min(yminlist)
  6315. for obj in obj_list:
  6316. obj.skew(0, num, point=(xminimal, yminimal))
  6317. obj.plot()
  6318. self.object_changed.emit(obj)
  6319. self.inform.emit('[success] %s' %
  6320. _("Skew on Y axis done."))
  6321. def on_plots_updated(self):
  6322. """
  6323. Callback used to report when the plots have changed.
  6324. Adjust axes and zooms to fit.
  6325. :return: None
  6326. """
  6327. if self.is_legacy is False:
  6328. self.plotcanvas.update() # TODO: Need update canvas?
  6329. else:
  6330. self.plotcanvas.auto_adjust_axes()
  6331. self.on_zoom_fit(None)
  6332. self.collection.update_view()
  6333. # self.inform.emit(_("Plots updated ..."))
  6334. # TODO: Rework toolbar 'clear', 'replot' functions
  6335. def on_toolbar_replot(self):
  6336. """
  6337. Callback for toolbar button. Re-plots all objects.
  6338. :return: None
  6339. """
  6340. self.report_usage("on_toolbar_replot")
  6341. self.log.debug("on_toolbar_replot()")
  6342. try:
  6343. self.collection.get_active().read_form()
  6344. except AttributeError:
  6345. self.log.debug("on_toolbar_replot(): AttributeError")
  6346. pass
  6347. self.plot_all()
  6348. def on_row_activated(self, index):
  6349. if index.isValid():
  6350. if index.internalPointer().parent_item != self.collection.root_item:
  6351. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6352. self.collection.on_item_activated(index)
  6353. def on_collection_updated(self, obj, state, old_name):
  6354. """
  6355. Create a menu from the object loaded in the collection.
  6356. TODO: should use the collection model to do this
  6357. :param obj: object that was changd (added, deleted, renamed)
  6358. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6359. :param old_name: the old name of the object before the action that triggered this slot happened
  6360. :return: None
  6361. """
  6362. icon_files = {
  6363. "gerber": "share/flatcam_icon16.png",
  6364. "excellon": "share/drill16.png",
  6365. "cncjob": "share/cnc16.png",
  6366. "geometry": "share/geometry16.png",
  6367. "script": "share/script_new16.png",
  6368. "document": "share/notes16_1.png"
  6369. }
  6370. if state == 'append':
  6371. for act in self.ui.menuobjects.actions():
  6372. try:
  6373. act.triggered.disconnect()
  6374. except TypeError:
  6375. pass
  6376. self.ui.menuobjects.clear()
  6377. gerber_list = list()
  6378. exc_list = list()
  6379. cncjob_list = list()
  6380. geo_list = list()
  6381. script_list = list()
  6382. doc_list = list()
  6383. for name in self.collection.get_names():
  6384. obj_named = self.collection.get_by_name(name)
  6385. if obj_named.kind == 'gerber':
  6386. gerber_list.append(name)
  6387. elif obj_named.kind == 'excellon':
  6388. exc_list.append(name)
  6389. elif obj_named.kind == 'cncjob':
  6390. cncjob_list.append(name)
  6391. elif obj_named.kind == 'geometry':
  6392. geo_list.append(name)
  6393. elif obj_named.kind == 'script':
  6394. script_list.append(name)
  6395. elif obj_named.kind == 'document':
  6396. doc_list.append(name)
  6397. def add_act(name):
  6398. obj_for_icon = self.collection.get_by_name(name)
  6399. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6400. add_action.setText(name)
  6401. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6402. add_action.triggered.connect(lambda: self.collection.set_exclusive_active(name))
  6403. self.ui.menuobjects.addAction(add_action)
  6404. for name in gerber_list:
  6405. add_act(name)
  6406. self.ui.menuobjects.addSeparator()
  6407. for name in exc_list:
  6408. add_act(name)
  6409. self.ui.menuobjects.addSeparator()
  6410. for name in cncjob_list:
  6411. add_act(name)
  6412. self.ui.menuobjects.addSeparator()
  6413. for name in geo_list:
  6414. add_act(name)
  6415. self.ui.menuobjects.addSeparator()
  6416. for name in script_list:
  6417. add_act(name)
  6418. self.ui.menuobjects.addSeparator()
  6419. for name in doc_list:
  6420. add_act(name)
  6421. elif state == 'delete':
  6422. for act in self.ui.menuobjects.actions():
  6423. if act.text() == obj.options['name']:
  6424. try:
  6425. act.triggered.disconnect()
  6426. except TypeError:
  6427. pass
  6428. self.ui.menuobjects.removeAction(act)
  6429. break
  6430. elif state == 'rename':
  6431. for act in self.ui.menuobjects.actions():
  6432. if act.text() == old_name:
  6433. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6434. add_action.setText(obj.options['name'])
  6435. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6436. add_action.triggered.connect(lambda: self.collection.set_exclusive_active(obj.options['name']))
  6437. self.ui.menuobjects.insertAction(act, add_action)
  6438. try:
  6439. act.triggered.disconnect()
  6440. except TypeError:
  6441. pass
  6442. self.ui.menuobjects.removeAction(act)
  6443. break
  6444. elif state =='delete_all':
  6445. for act in self.ui.menuobjects.actions():
  6446. try:
  6447. act.triggered.disconnect()
  6448. except TypeError:
  6449. pass
  6450. self.ui.menuobjects.clear()
  6451. def grid_status(self):
  6452. if self.ui.grid_snap_btn.isChecked():
  6453. return True
  6454. else:
  6455. return False
  6456. def populate_cmenu_grids(self):
  6457. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6458. self.ui.cmenu_gridmenu.clear()
  6459. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6460. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6461. grid_toggle.setCheckable(True)
  6462. if self.grid_status() == True:
  6463. grid_toggle.setChecked(True)
  6464. else:
  6465. grid_toggle.setChecked(False)
  6466. self.ui.cmenu_gridmenu.addSeparator()
  6467. for grid in sorted_list:
  6468. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6469. action.triggered.connect(self.set_grid)
  6470. self.ui.cmenu_gridmenu.addSeparator()
  6471. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6472. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6473. grid_add.triggered.connect(self.on_grid_add)
  6474. grid_delete.triggered.connect(self.on_grid_delete)
  6475. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6476. def set_grid(self):
  6477. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6478. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6479. def on_grid_add(self):
  6480. # ## Current application units in lower Case
  6481. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6482. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6483. text=_('Enter a Grid Value:'),
  6484. min=0.0000, max=99.9999, decimals=4)
  6485. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6486. val, ok = grid_add_popup.get_value()
  6487. if ok:
  6488. if float(val) == 0:
  6489. self.inform.emit('[WARNING_NOTCL] %s' %
  6490. _("Please enter a grid value with non-zero value, in Float format."))
  6491. return
  6492. else:
  6493. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6494. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6495. self.inform.emit('[success] %s...' %
  6496. _("New Grid added"))
  6497. else:
  6498. self.inform.emit('[WARNING_NOTCL] %s...' %
  6499. _("Grid already exists"))
  6500. else:
  6501. self.inform.emit('[WARNING_NOTCL] %s...' %
  6502. _("Adding New Grid cancelled"))
  6503. def on_grid_delete(self):
  6504. # ## Current application units in lower Case
  6505. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6506. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6507. text='Enter a Grid Value:',
  6508. min=0.0000, max=99.9999, decimals=4)
  6509. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6510. val, ok = grid_del_popup.get_value()
  6511. if ok:
  6512. if float(val) == 0:
  6513. self.inform.emit('[WARNING_NOTCL] %s' %
  6514. _("Please enter a grid value with non-zero value, in Float format."))
  6515. return
  6516. else:
  6517. try:
  6518. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6519. except ValueError:
  6520. self.inform.emit('[ERROR_NOTCL]%s...' %
  6521. _(" Grid Value does not exist"))
  6522. return
  6523. self.inform.emit('[success] %s...' %
  6524. _("Grid Value deleted"))
  6525. else:
  6526. self.inform.emit('[WARNING_NOTCL] %s...' %
  6527. _("Delete Grid value cancelled"))
  6528. def on_shortcut_list(self):
  6529. self.report_usage("on_shortcut_list()")
  6530. # add the tab if it was closed
  6531. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6532. # delete the absolute and relative position and messages in the infobar
  6533. self.ui.position_label.setText("")
  6534. self.ui.rel_position_label.setText("")
  6535. # Switch plot_area to preferences page
  6536. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6537. # self.ui.show()
  6538. def on_select_tab(self, name):
  6539. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6540. if self.ui.splitter.sizes()[0] == 0:
  6541. self.ui.splitter.setSizes([1, 1])
  6542. else:
  6543. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6544. self.ui.splitter.setSizes([0, 1])
  6545. if name == 'project':
  6546. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6547. elif name == 'selected':
  6548. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6549. elif name == 'tool':
  6550. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6551. def on_copy_name(self):
  6552. self.report_usage("on_copy_name()")
  6553. obj = self.collection.get_active()
  6554. try:
  6555. name = obj.options["name"]
  6556. except AttributeError:
  6557. log.debug("on_copy_name() --> No object selected to copy it's name")
  6558. self.inform.emit('[WARNING_NOTCL]%s' %
  6559. _(" No object selected to copy it's name"))
  6560. return
  6561. self.clipboard.setText(name)
  6562. self.inform.emit(_("Name copied on clipboard ..."))
  6563. def on_mouse_click_over_plot(self, event):
  6564. """
  6565. Default actions are:
  6566. :param event: Contains information about the event, like which button
  6567. was clicked, the pixel coordinates and the axes coordinates.
  6568. :return: None
  6569. """
  6570. self.pos = []
  6571. if self.is_legacy is False:
  6572. event_pos = event.pos
  6573. if self.defaults["global_pan_button"] == '2':
  6574. pan_button = 2
  6575. else:
  6576. pan_button = 3
  6577. # Set the mouse button for panning
  6578. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6579. else:
  6580. event_pos = (event.xdata, event.ydata)
  6581. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6582. if self.defaults["global_pan_button"] == '2':
  6583. pan_button = 3
  6584. else:
  6585. pan_button = 2
  6586. # So it can receive key presses
  6587. self.plotcanvas.native.setFocus()
  6588. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6589. if self.grid_status() == True:
  6590. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6591. else:
  6592. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6593. try:
  6594. if event.button == 1:
  6595. # Reset here the relative coordinates so there is a new reference on the click position
  6596. if self.rel_point1 is None:
  6597. self.rel_point1 = self.pos
  6598. else:
  6599. self.rel_point2 = copy(self.rel_point1)
  6600. self.rel_point1 = self.pos
  6601. self.on_mouse_move_over_plot(event, origin_click=True)
  6602. except Exception as e:
  6603. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6604. def on_double_click_over_plot(self, event):
  6605. if event.button == 1:
  6606. self.doubleclick = True
  6607. def on_mouse_move_over_plot(self, event, origin_click=None):
  6608. """
  6609. Callback for the mouse motion event over the plot.
  6610. :param event: Contains information about the event.
  6611. :param origin_click
  6612. :return: None
  6613. """
  6614. if self.is_legacy is False:
  6615. event_pos = event.pos
  6616. if self.defaults["global_pan_button"] == '2':
  6617. pan_button = 2
  6618. else:
  6619. pan_button = 3
  6620. event_is_dragging = event.is_dragging
  6621. else:
  6622. event_pos = (event.xdata, event.ydata)
  6623. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6624. if self.defaults["global_pan_button"] == '2':
  6625. pan_button = 3
  6626. else:
  6627. pan_button = 2
  6628. event_is_dragging = self.plotcanvas.is_dragging
  6629. # So it can receive key presses
  6630. self.plotcanvas.native.setFocus()
  6631. self.pos_jump = event_pos
  6632. self.ui.popMenu.mouse_is_panning = False
  6633. if not origin_click:
  6634. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6635. if event.button == pan_button and event_is_dragging == 1:
  6636. self.ui.popMenu.mouse_is_panning = True
  6637. return
  6638. if self.rel_point1 is not None:
  6639. try: # May fail in case mouse not within axes
  6640. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6641. if self.grid_status() == True:
  6642. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6643. # Update cursor
  6644. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6645. symbol='++', edge_color='black', size=self.defaults["global_cursor_size"])
  6646. else:
  6647. pos = (pos_canvas[0], pos_canvas[1])
  6648. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6649. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6650. dx = pos[0] - float(self.rel_point1[0])
  6651. dy = pos[1] - float(self.rel_point1[1])
  6652. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6653. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6654. self.mouse = [pos[0], pos[1]]
  6655. # if the mouse is moved and the LMB is clicked then the action is a selection
  6656. if event_is_dragging == 1 and event.button == 1:
  6657. self.delete_selection_shape()
  6658. if dx < 0:
  6659. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6660. face_color=self.defaults['global_alt_sel_fill'])
  6661. self.selection_type = False
  6662. elif dx > 0:
  6663. self.draw_moving_selection_shape(self.pos, pos)
  6664. self.selection_type = True
  6665. else:
  6666. self.selection_type = None
  6667. # hover effect - enabled in Preferences -> General -> GUI Settings
  6668. if self.defaults['global_hover']:
  6669. for obj in self.collection.get_list():
  6670. try:
  6671. # select the object(s) only if it is enabled (plotted)
  6672. if obj.options['plot']:
  6673. if obj not in self.collection.get_selected():
  6674. poly_obj = Polygon(
  6675. [(obj.options['xmin'], obj.options['ymin']),
  6676. (obj.options['xmax'], obj.options['ymin']),
  6677. (obj.options['xmax'], obj.options['ymax']),
  6678. (obj.options['xmin'], obj.options['ymax'])]
  6679. )
  6680. if Point(pos).within(poly_obj):
  6681. if obj.isHovering is False:
  6682. obj.isHovering = True
  6683. obj.notHovering = True
  6684. # create the selection box around the selected object
  6685. self.draw_hover_shape(obj, color='#d1e0e0FF')
  6686. else:
  6687. if obj.notHovering is True:
  6688. obj.notHovering = False
  6689. obj.isHovering = False
  6690. self.delete_hover_shape()
  6691. except:
  6692. # the Exception here will happen if we try to select on screen and we have an
  6693. # newly (and empty) just created Geometry or Excellon object that do not have the
  6694. # xmin, xmax, ymin, ymax options.
  6695. # In this case poly_obj creation (see above) will fail
  6696. pass
  6697. except:
  6698. self.ui.position_label.setText("")
  6699. self.ui.rel_position_label.setText("")
  6700. self.mouse = None
  6701. def on_mouse_click_release_over_plot(self, event):
  6702. """
  6703. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6704. and has been registered in ''self.__init__()''.
  6705. :param event: contains information about the event.
  6706. :return:
  6707. """
  6708. pos = 0, 0
  6709. if self.is_legacy is False:
  6710. event_pos = event.pos
  6711. right_button = 2
  6712. else:
  6713. event_pos = (event.xdata, event.ydata)
  6714. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6715. right_button = 3
  6716. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6717. if self.grid_status() == True:
  6718. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6719. else:
  6720. pos = (pos_canvas[0], pos_canvas[1])
  6721. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6722. # canvas menu
  6723. if event.button == right_button: # right click
  6724. if self.ui.popMenu.mouse_is_panning is False:
  6725. self.cursor = QtGui.QCursor()
  6726. self.populate_cmenu_grids()
  6727. self.ui.popMenu.popup(self.cursor.pos())
  6728. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6729. # selection and then select a type of selection ("enclosing" or "touching")
  6730. try:
  6731. if event.button == 1: # left click
  6732. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6733. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6734. if modifiers == QtCore.Qt.ShiftModifier:
  6735. # do not auto open the Project Tab
  6736. self.click_noproject = True
  6737. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6738. self.inform.emit('[success] %s' %
  6739. _("Coordinates copied to clipboard."))
  6740. return
  6741. if self.doubleclick is True:
  6742. self.doubleclick = False
  6743. if self.collection.get_selected():
  6744. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6745. if self.ui.splitter.sizes()[0] == 0:
  6746. self.ui.splitter.setSizes([1, 1])
  6747. # delete the selection shape(S) as it may be in the way
  6748. self.delete_selection_shape()
  6749. self.delete_hover_shape()
  6750. else:
  6751. if self.selection_type is not None:
  6752. self.selection_area_handler(self.pos, pos, self.selection_type)
  6753. self.selection_type = None
  6754. else:
  6755. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6756. if key_modifier == QtCore.Qt.ShiftModifier:
  6757. mod_key = 'Shift'
  6758. elif key_modifier == QtCore.Qt.ControlModifier:
  6759. mod_key = 'Control'
  6760. else:
  6761. mod_key = None
  6762. if mod_key == self.defaults["global_mselect_key"]:
  6763. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6764. # deselect, and if it's not selected then it will be selected
  6765. # If there is no active command (self.command_active is None) then we check if we clicked
  6766. # on a object by checking the bounding limits against mouse click position
  6767. if self.command_active is None:
  6768. self.select_objects(key='CTRL')
  6769. self.delete_hover_shape()
  6770. else:
  6771. # If there is no active command (self.command_active is None) then we check if we clicked
  6772. # on a object by checking the bounding limits against mouse click position
  6773. if self.command_active is None:
  6774. self.select_objects()
  6775. self.delete_hover_shape()
  6776. except Exception as e:
  6777. log.warning("Error: %s" % str(e))
  6778. return
  6779. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6780. """
  6781. :param start_pos: mouse position when the selection LMB click was done
  6782. :param end_pos: mouse position when the left mouse button is released
  6783. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6784. :return:
  6785. """
  6786. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6787. self.delete_selection_shape()
  6788. for obj in self.collection.get_list():
  6789. try:
  6790. # select the object(s) only if it is enabled (plotted)
  6791. if obj.options['plot']:
  6792. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6793. (obj.options['xmax'], obj.options['ymin']),
  6794. (obj.options['xmax'], obj.options['ymax']),
  6795. (obj.options['xmin'], obj.options['ymax'])])
  6796. if sel_type is True:
  6797. if poly_obj.within(poly_selection):
  6798. # create the selection box around the selected object
  6799. if self.defaults['global_selection_shape'] is True:
  6800. self.draw_selection_shape(obj)
  6801. self.collection.set_active(obj.options['name'])
  6802. else:
  6803. if poly_selection.intersects(poly_obj):
  6804. # create the selection box around the selected object
  6805. if self.defaults['global_selection_shape'] is True:
  6806. self.draw_selection_shape(obj)
  6807. self.collection.set_active(obj.options['name'])
  6808. except Exception as e:
  6809. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6810. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6811. # In this case poly_obj creation (see above) will fail
  6812. log.debug("App.selection_area_handler() --> %s" % str(e))
  6813. def select_objects(self, key=None):
  6814. # list where we store the overlapped objects under our mouse left click position
  6815. objects_under_the_click_list = []
  6816. # Populate the list with the overlapped objects on the click position
  6817. curr_x, curr_y = self.pos
  6818. for obj in self.all_objects_list:
  6819. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6820. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6821. if obj.options['name'] not in objects_under_the_click_list:
  6822. if obj.options['plot']:
  6823. # add objects to the objects_under_the_click list only if the object is plotted
  6824. # (active and not disabled)
  6825. objects_under_the_click_list.append(obj.options['name'])
  6826. try:
  6827. # If there is no element in the overlapped objects list then make everyone inactive
  6828. # because we selected "nothing"
  6829. if not objects_under_the_click_list:
  6830. self.collection.set_all_inactive()
  6831. # delete the possible selection box around a possible selected object
  6832. self.delete_selection_shape()
  6833. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6834. # only when working on App
  6835. if self.call_source == 'app':
  6836. if self.click_noproject is False:
  6837. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6838. else:
  6839. # restore auto open the Project Tab
  6840. self.click_noproject = False
  6841. # delete any text in the status bar, implicitly the last object name that was selected
  6842. self.inform.emit("")
  6843. else:
  6844. self.call_source = 'app'
  6845. else:
  6846. # case when there is only an object under the click and we toggle it
  6847. if len(objects_under_the_click_list) == 1:
  6848. if self.collection.get_active() is None:
  6849. self.collection.set_active(objects_under_the_click_list[0])
  6850. # create the selection box around the selected object
  6851. curr_sel_obj = self.collection.get_active()
  6852. if self.defaults['global_selection_shape'] is True:
  6853. self.draw_selection_shape(curr_sel_obj)
  6854. # self.inform.emit('[selected] %s: %s selected' %
  6855. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6856. if curr_sel_obj.kind == 'gerber':
  6857. self.inform.emit(
  6858. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6859. color='green', name=str(curr_sel_obj.options['name'])))
  6860. elif curr_sel_obj.kind == 'excellon':
  6861. self.inform.emit(
  6862. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6863. color='brown', name=str(curr_sel_obj.options['name'])))
  6864. elif curr_sel_obj.kind == 'cncjob':
  6865. self.inform.emit(
  6866. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6867. color='blue', name=str(curr_sel_obj.options['name'])))
  6868. elif curr_sel_obj.kind == 'geometry':
  6869. self.inform.emit(
  6870. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6871. color='red', name=str(curr_sel_obj.options['name'])))
  6872. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6873. self.collection.set_all_inactive()
  6874. self.delete_selection_shape()
  6875. self.collection.set_active(objects_under_the_click_list[0])
  6876. # create the selection box around the selected object
  6877. curr_sel_obj = self.collection.get_active()
  6878. if self.defaults['global_selection_shape'] is True:
  6879. self.draw_selection_shape(curr_sel_obj)
  6880. # self.inform.emit('[selected] %s: %s selected' %
  6881. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6882. if curr_sel_obj.kind == 'gerber':
  6883. self.inform.emit(
  6884. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6885. color='green', name=str(curr_sel_obj.options['name'])))
  6886. elif curr_sel_obj.kind == 'excellon':
  6887. self.inform.emit(
  6888. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6889. color='brown', name=str(curr_sel_obj.options['name'])))
  6890. elif curr_sel_obj.kind == 'cncjob':
  6891. self.inform.emit(
  6892. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6893. color='blue', name=str(curr_sel_obj.options['name'])))
  6894. elif curr_sel_obj.kind == 'geometry':
  6895. self.inform.emit(
  6896. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6897. color='red', name=str(curr_sel_obj.options['name'])))
  6898. else:
  6899. self.collection.set_all_inactive()
  6900. self.delete_selection_shape()
  6901. if self.call_source == 'app':
  6902. # delete any text in the status bar, implicitly the last object name that was selected
  6903. self.inform.emit("")
  6904. else:
  6905. self.call_source = 'app'
  6906. else:
  6907. # If there is no selected object
  6908. # make active the first element of the overlapped objects list
  6909. if self.collection.get_active() is None:
  6910. self.collection.set_active(objects_under_the_click_list[0])
  6911. name_sel_obj = self.collection.get_active().options['name']
  6912. # In case that there is a selected object but it is not in the overlapped object list
  6913. # make that object inactive and activate the first element in the overlapped object list
  6914. if name_sel_obj not in objects_under_the_click_list:
  6915. self.collection.set_inactive(name_sel_obj)
  6916. name_sel_obj = objects_under_the_click_list[0]
  6917. self.collection.set_active(name_sel_obj)
  6918. else:
  6919. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6920. self.collection.set_all_inactive()
  6921. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6922. len(objects_under_the_click_list)])
  6923. curr_sel_obj = self.collection.get_active()
  6924. # delete the possible selection box around a possible selected object
  6925. self.delete_selection_shape()
  6926. # create the selection box around the selected object
  6927. if self.defaults['global_selection_shape'] is True:
  6928. self.draw_selection_shape(curr_sel_obj)
  6929. # self.inform.emit('[selected] %s: %s selected' %
  6930. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6931. if curr_sel_obj.kind == 'gerber':
  6932. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6933. color='green', name=str(curr_sel_obj.options['name'])))
  6934. elif curr_sel_obj.kind == 'excellon':
  6935. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6936. color='brown', name=str(curr_sel_obj.options['name'])))
  6937. elif curr_sel_obj.kind == 'cncjob':
  6938. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6939. color='blue', name=str(curr_sel_obj.options['name'])))
  6940. elif curr_sel_obj.kind == 'geometry':
  6941. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6942. color='red', name=str(curr_sel_obj.options['name'])))
  6943. # for obj in self.collection.get_list():
  6944. # obj.plot()
  6945. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6946. # TODO: on selected objects change the object colors and do not draw the selection box
  6947. # self.plotcanvas.update() # this updates the canvas
  6948. except Exception as e:
  6949. log.error("[ERROR] Something went bad. %s" % str(e))
  6950. return
  6951. def delete_hover_shape(self):
  6952. self.hover_shapes.clear()
  6953. self.hover_shapes.redraw()
  6954. def draw_hover_shape(self, sel_obj, color=None):
  6955. """
  6956. :param sel_obj: the object for which the hover shape must be drawn
  6957. :return:
  6958. """
  6959. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6960. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6961. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6962. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6963. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6964. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6965. hover_rect = hover_rect.buffer(-0.1)
  6966. hover_rect = hover_rect.buffer(0.2)
  6967. else:
  6968. hover_rect = hover_rect.buffer(-0.00393)
  6969. hover_rect = hover_rect.buffer(0.00787)
  6970. # if color:
  6971. # face = Color(color)
  6972. # face.alpha = 0.2
  6973. # outline = Color(color, alpha=0.8)
  6974. # else:
  6975. # face = Color(self.defaults['global_sel_fill'])
  6976. # face.alpha = 0.2
  6977. # outline = self.defaults['global_sel_line']
  6978. if color:
  6979. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6980. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6981. else:
  6982. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6983. outline = self.defaults['global_sel_line']
  6984. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6985. if self.is_legacy is True:
  6986. self.hover_shapes.redraw()
  6987. def delete_selection_shape(self):
  6988. self.move_tool.sel_shapes.clear()
  6989. self.move_tool.sel_shapes.redraw()
  6990. def draw_selection_shape(self, sel_obj, color=None):
  6991. """
  6992. :param sel_obj: the object for which the selection shape must be drawn
  6993. :return:
  6994. """
  6995. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6996. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6997. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6998. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6999. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7000. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  7001. sel_rect = sel_rect.buffer(-0.1)
  7002. sel_rect = sel_rect.buffer(0.2)
  7003. else:
  7004. sel_rect = sel_rect.buffer(-0.00393)
  7005. sel_rect = sel_rect.buffer(0.00787)
  7006. # if color:
  7007. # face = Color(color, alpha=0.2)
  7008. # outline = Color(color, alpha=0.8)
  7009. # else:
  7010. # face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  7011. # outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  7012. if color:
  7013. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7014. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7015. else:
  7016. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7017. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7018. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7019. color=outline,
  7020. face_color=face,
  7021. update=True,
  7022. layer=0,
  7023. tolerance=None))
  7024. if self.is_legacy is True:
  7025. self.move_tool.sel_shapes.redraw()
  7026. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7027. """
  7028. :param old_coords: old coordinates
  7029. :param coords: new coordinates
  7030. :return:
  7031. """
  7032. if 'color' in kwargs:
  7033. color = kwargs['color']
  7034. else:
  7035. color = self.defaults['global_sel_line']
  7036. if 'face_color' in kwargs:
  7037. face_color = kwargs['face_color']
  7038. else:
  7039. face_color = self.defaults['global_sel_fill']
  7040. if 'face_alpha' in kwargs:
  7041. face_alpha = kwargs['face_alpha']
  7042. else:
  7043. face_alpha = 0.3
  7044. x0, y0 = old_coords
  7045. x1, y1 = coords
  7046. pt1 = (x0, y0)
  7047. pt2 = (x1, y0)
  7048. pt3 = (x1, y1)
  7049. pt4 = (x0, y1)
  7050. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7051. # color_t = Color(face_color)
  7052. # color_t.alpha = face_alpha
  7053. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7054. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7055. layer=0, tolerance=None)
  7056. if self.is_legacy is True:
  7057. self.move_tool.sel_shapes.redraw()
  7058. def on_file_new_click(self):
  7059. if self.collection.get_list() and self.should_we_save:
  7060. msgbox = QtWidgets.QMessageBox()
  7061. # msgbox.setText("<B>Save changes ...</B>")
  7062. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7063. "Creating a New project will delete them.\n"
  7064. "Do you want to Save the project?"))
  7065. msgbox.setWindowTitle(_("Save changes"))
  7066. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7067. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7068. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7069. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7070. msgbox.setDefaultButton(bt_yes)
  7071. msgbox.exec_()
  7072. response = msgbox.clickedButton()
  7073. if response == bt_yes:
  7074. self.on_file_saveprojectas()
  7075. elif response == bt_cancel:
  7076. return
  7077. elif response == bt_no:
  7078. self.on_file_new()
  7079. else:
  7080. self.on_file_new()
  7081. self.inform.emit('[success] %s...' %
  7082. _("New Project created"))
  7083. def on_file_new(self, cli=None):
  7084. """
  7085. Callback for menu item File->New. Returns the application to its
  7086. startup state. This method is thread-safe.
  7087. :return: None
  7088. """
  7089. self.report_usage("on_file_new")
  7090. # Remove everything from memory
  7091. App.log.debug("on_file_new()")
  7092. if self.call_source != 'app':
  7093. self.editor2object(cleanup=True)
  7094. # ## EDITOR section
  7095. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7096. self.exc_editor = FlatCAMExcEditor(self)
  7097. self.grb_editor = FlatCAMGrbEditor(self)
  7098. # Clear pool
  7099. self.clear_pool()
  7100. for obj in self.collection.get_list():
  7101. # delete shapes left drawn from mark shape_collections, if any
  7102. if isinstance(obj, FlatCAMGerber):
  7103. try:
  7104. obj.mark_shapes.enabled = False
  7105. obj.mark_shapes.clear(update=True)
  7106. except AttributeError:
  7107. pass
  7108. # also delete annotation shapes, if any
  7109. elif isinstance(obj, FlatCAMCNCjob):
  7110. try:
  7111. obj.annotation.enabled = False
  7112. obj.annotation.clear(update=True)
  7113. except AttributeError:
  7114. pass
  7115. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7116. self.init_tcl()
  7117. self.delete_selection_shape()
  7118. self.collection.delete_all()
  7119. self.setup_component_editor()
  7120. # Clear project filename
  7121. self.project_filename = None
  7122. # Load the application defaults
  7123. self.load_defaults(filename='current_defaults')
  7124. # Re-fresh project options
  7125. self.on_options_app2project()
  7126. # Init Tools
  7127. self.init_tools()
  7128. if cli is None:
  7129. # Close any Tabs opened in the Plot Tab Area section
  7130. for index in range(self.ui.plot_tab_area.count()):
  7131. self.ui.plot_tab_area.closeTab(index)
  7132. # for whatever reason previous command does not close the last tab so I do it manually
  7133. self.ui.plot_tab_area.closeTab(0)
  7134. # # And then add again the Plot Area
  7135. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7136. self.ui.plot_tab_area.protectTab(0)
  7137. # take the focus of the Notebook on Project Tab.
  7138. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7139. self.set_ui_title(name=_("New Project - Not saved"))
  7140. def obj_properties(self):
  7141. self.report_usage("obj_properties()")
  7142. self.properties_tool.run(toggle=False)
  7143. def on_project_context_save(self):
  7144. obj = self.collection.get_active()
  7145. if type(obj) == FlatCAMGeometry:
  7146. self.on_file_exportdxf()
  7147. elif type(obj) == FlatCAMExcellon:
  7148. self.on_file_saveexcellon()
  7149. elif type(obj) == FlatCAMCNCjob:
  7150. obj.on_exportgcode_button_click()
  7151. elif type(obj) == FlatCAMGerber:
  7152. self.on_file_savegerber()
  7153. elif type(obj) == FlatCAMScript:
  7154. self.on_file_savescript()
  7155. elif type(obj) == FlatCAMDocument:
  7156. self.on_file_savedocument()
  7157. def obj_move(self):
  7158. self.report_usage("obj_move()")
  7159. self.move_tool.run(toggle=False)
  7160. def on_fileopengerber(self, checked=None, name=None):
  7161. """
  7162. File menu callback for opening a Gerber.
  7163. :return: None
  7164. """
  7165. self.report_usage("on_fileopengerber")
  7166. App.log.debug("on_fileopengerber()")
  7167. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7168. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7169. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7170. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7171. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7172. "*.mil);;" \
  7173. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7174. "Allegro Files (*.art);;" \
  7175. "Mentor Files (*.pho *.gdo);;" \
  7176. "All Files (*.*)"
  7177. if name is None:
  7178. try:
  7179. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7180. directory=self.get_last_folder(),
  7181. filter=_filter_)
  7182. except TypeError:
  7183. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7184. filenames = [str(filename) for filename in filenames]
  7185. else:
  7186. filenames = [name]
  7187. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7188. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7189. _("Opening Gerber file.")),
  7190. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7191. color=QtGui.QColor("gray"))
  7192. if len(filenames) == 0:
  7193. self.inform.emit('[WARNING_NOTCL] %s' %
  7194. _("Open Gerber cancelled."))
  7195. else:
  7196. for filename in filenames:
  7197. if filename != '':
  7198. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7199. def on_fileopenexcellon(self, checked=None, name=None):
  7200. """
  7201. File menu callback for opening an Excellon file.
  7202. :return: None
  7203. """
  7204. self.report_usage("on_fileopenexcellon")
  7205. App.log.debug("on_fileopenexcellon()")
  7206. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7207. "All Files (*.*)"
  7208. if name is None:
  7209. try:
  7210. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7211. directory=self.get_last_folder(),
  7212. filter=_filter_)
  7213. except TypeError:
  7214. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7215. filenames = [str(filename) for filename in filenames]
  7216. else:
  7217. filenames = [str(name)]
  7218. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7219. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7220. _("Opening Excellon file.")),
  7221. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7222. color=QtGui.QColor("gray"))
  7223. if len(filenames) == 0:
  7224. self.inform.emit('[WARNING_NOTCL]%s' %
  7225. _(" Open Excellon cancelled."))
  7226. else:
  7227. for filename in filenames:
  7228. if filename != '':
  7229. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7230. def on_fileopengcode(self, checked=None, name=None):
  7231. """
  7232. File menu call back for opening gcode.
  7233. :return: None
  7234. """
  7235. self.report_usage("on_fileopengcode")
  7236. App.log.debug("on_fileopengcode()")
  7237. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7238. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7239. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7240. "All Files (*.*)"
  7241. if name is None:
  7242. try:
  7243. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7244. directory=self.get_last_folder(),
  7245. filter=_filter_)
  7246. except TypeError:
  7247. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7248. filenames = [str(filename) for filename in filenames]
  7249. else:
  7250. filenames = [name]
  7251. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7252. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7253. _("Opening G-Code file.")),
  7254. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7255. color=QtGui.QColor("gray"))
  7256. if len(filenames) == 0:
  7257. self.inform.emit('[WARNING_NOTCL] %s' %
  7258. _("Open G-Code cancelled."))
  7259. else:
  7260. for filename in filenames:
  7261. if filename != '':
  7262. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  7263. def on_file_openproject(self, checked=None):
  7264. """
  7265. File menu callback for opening a project.
  7266. :return: None
  7267. """
  7268. self.report_usage("on_file_openproject")
  7269. App.log.debug("on_file_openproject()")
  7270. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7271. try:
  7272. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7273. directory=self.get_last_folder(), filter=_filter_)
  7274. except TypeError:
  7275. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7276. # The Qt methods above will return a QString which can cause problems later.
  7277. # So far json.dump() will fail to serialize it.
  7278. # TODO: Improve the serialization methods and remove this fix.
  7279. filename = str(filename)
  7280. if filename == "":
  7281. self.inform.emit('[WARNING_NOTCL] %s' %
  7282. _("Open Project cancelled."))
  7283. else:
  7284. # self.worker_task.emit({'fcn': self.open_project,
  7285. # 'params': [filename]})
  7286. # The above was failing because open_project() is not
  7287. # thread safe. The new_project()
  7288. self.open_project(filename)
  7289. def on_file_openconfig(self, checked=None):
  7290. """
  7291. File menu callback for opening a config file.
  7292. :return: None
  7293. """
  7294. self.report_usage("on_file_openconfig")
  7295. App.log.debug("on_file_openconfig()")
  7296. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7297. try:
  7298. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7299. directory=self.data_path, filter=_filter_)
  7300. except TypeError:
  7301. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7302. filter=_filter_)
  7303. if filename == "":
  7304. self.inform.emit('[WARNING_NOTCL] %s' %
  7305. _("Open Config cancelled."))
  7306. else:
  7307. self.open_config_file(filename)
  7308. def on_file_exportsvg(self):
  7309. """
  7310. Callback for menu item File->Export SVG.
  7311. :return: None
  7312. """
  7313. self.report_usage("on_file_exportsvg")
  7314. App.log.debug("on_file_exportsvg()")
  7315. obj = self.collection.get_active()
  7316. if obj is None:
  7317. self.inform.emit('[WARNING_NOTCL] %s' %
  7318. _("No object selected."))
  7319. msg = _("Please Select a Geometry object to export")
  7320. msgbox = QtWidgets.QMessageBox()
  7321. msgbox.setInformativeText(msg)
  7322. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7323. msgbox.setDefaultButton(bt_ok)
  7324. msgbox.exec_()
  7325. return
  7326. # Check for more compatible types and add as required
  7327. if (not isinstance(obj, FlatCAMGeometry)
  7328. and not isinstance(obj, FlatCAMGerber)
  7329. and not isinstance(obj, FlatCAMCNCjob)
  7330. and not isinstance(obj, FlatCAMExcellon)):
  7331. msg = '[ERROR_NOTCL] %s' % \
  7332. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7333. msgbox = QtWidgets.QMessageBox()
  7334. msgbox.setInformativeText(msg)
  7335. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7336. msgbox.setDefaultButton(bt_ok)
  7337. msgbox.exec_()
  7338. return
  7339. name = obj.options["name"]
  7340. _filter = "SVG File (*.svg);;All Files (*.*)"
  7341. try:
  7342. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7343. caption=_("Export SVG"),
  7344. directory=self.get_last_save_folder() + '/' + str(name),
  7345. filter=_filter)
  7346. except TypeError:
  7347. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7348. filename = str(filename)
  7349. if filename == "":
  7350. self.inform.emit('[WARNING_NOTCL]%s' %
  7351. _(" Export SVG cancelled."))
  7352. return
  7353. else:
  7354. self.export_svg(name, filename)
  7355. if self.defaults["global_open_style"] is False:
  7356. self.file_opened.emit("SVG", filename)
  7357. self.file_saved.emit("SVG", filename)
  7358. def on_file_exportpng(self):
  7359. self.report_usage("on_file_exportpng")
  7360. App.log.debug("on_file_exportpng()")
  7361. self.date = str(datetime.today()).rpartition('.')[0]
  7362. self.date = ''.join(c for c in self.date if c not in ':-')
  7363. self.date = self.date.replace(' ', '_')
  7364. image = _screenshot()
  7365. data = np.asarray(image)
  7366. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7367. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7368. _('Data must be a 3D array with last dimension 3 or 4'))
  7369. return
  7370. filter_ = "PNG File (*.png);;All Files (*.*)"
  7371. try:
  7372. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7373. caption=_("Export PNG Image"),
  7374. directory=self.get_last_save_folder() + '/png_' + self.date,
  7375. filter=filter_)
  7376. except TypeError:
  7377. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7378. filename = str(filename)
  7379. if filename == "":
  7380. self.inform.emit(_("Export PNG cancelled."))
  7381. return
  7382. else:
  7383. write_png(filename, data)
  7384. if self.defaults["global_open_style"] is False:
  7385. self.file_opened.emit("png", filename)
  7386. self.file_saved.emit("png", filename)
  7387. def on_file_savegerber(self):
  7388. """
  7389. Callback for menu item in Project context menu.
  7390. :return: None
  7391. """
  7392. self.report_usage("on_file_savegerber")
  7393. App.log.debug("on_file_savegerber()")
  7394. obj = self.collection.get_active()
  7395. if obj is None:
  7396. self.inform.emit('[WARNING_NOTCL] %s' %
  7397. _("No object selected. Please select an Gerber object to export."))
  7398. return
  7399. # Check for more compatible types and add as required
  7400. if not isinstance(obj, FlatCAMGerber):
  7401. self.inform.emit('[ERROR_NOTCL] %s' %
  7402. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7403. return
  7404. name = self.collection.get_active().options["name"]
  7405. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7406. try:
  7407. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7408. caption="Save Gerber source file",
  7409. directory=self.get_last_save_folder() + '/' + name,
  7410. filter=_filter)
  7411. except TypeError:
  7412. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7413. filename = str(filename)
  7414. if filename == "":
  7415. self.inform.emit('[WARNING_NOTCL] %s' %
  7416. _("Save Gerber source file cancelled."))
  7417. return
  7418. else:
  7419. self.save_source_file(name, filename)
  7420. if self.defaults["global_open_style"] is False:
  7421. self.file_opened.emit("Gerber", filename)
  7422. self.file_saved.emit("Gerber", filename)
  7423. def on_file_savescript(self):
  7424. """
  7425. Callback for menu item in Project context menu.
  7426. :return: None
  7427. """
  7428. self.report_usage("on_file_savescript")
  7429. App.log.debug("on_file_savescript()")
  7430. obj = self.collection.get_active()
  7431. if obj is None:
  7432. self.inform.emit('[WARNING_NOTCL] %s' %
  7433. _("No object selected. Please select an Script object to export."))
  7434. return
  7435. # Check for more compatible types and add as required
  7436. if not isinstance(obj, FlatCAMScript):
  7437. self.inform.emit('[ERROR_NOTCL] %s' %
  7438. _("Failed. Only Script objects can be saved as TCL Script files..."))
  7439. return
  7440. name = self.collection.get_active().options["name"]
  7441. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7442. try:
  7443. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7444. caption="Save Script source file",
  7445. directory=self.get_last_save_folder() + '/' + name,
  7446. filter=_filter)
  7447. except TypeError:
  7448. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  7449. filename = str(filename)
  7450. if filename == "":
  7451. self.inform.emit('[WARNING_NOTCL] %s' %
  7452. _("Save Script source file cancelled."))
  7453. return
  7454. else:
  7455. self.save_source_file(name, filename)
  7456. if self.defaults["global_open_style"] is False:
  7457. self.file_opened.emit("Script", filename)
  7458. self.file_saved.emit("Script", filename)
  7459. def on_file_savedocument(self):
  7460. """
  7461. Callback for menu item in Project context menu.
  7462. :return: None
  7463. """
  7464. self.report_usage("on_file_savedocument")
  7465. App.log.debug("on_file_savedocument()")
  7466. obj = self.collection.get_active()
  7467. if obj is None:
  7468. self.inform.emit('[WARNING_NOTCL] %s' %
  7469. _("No object selected. Please select an Document object to export."))
  7470. return
  7471. # Check for more compatible types and add as required
  7472. if not isinstance(obj, FlatCAMScript):
  7473. self.inform.emit('[ERROR_NOTCL] %s' %
  7474. _("Failed. Only Document objects can be saved as Document files..."))
  7475. return
  7476. name = self.collection.get_active().options["name"]
  7477. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7478. try:
  7479. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7480. caption="Save Document source file",
  7481. directory=self.get_last_save_folder() + '/' + name,
  7482. filter=_filter)
  7483. except TypeError:
  7484. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  7485. filename = str(filename)
  7486. if filename == "":
  7487. self.inform.emit('[WARNING_NOTCL] %s' %
  7488. _("Save Document source file cancelled."))
  7489. return
  7490. else:
  7491. self.save_source_file(name, filename)
  7492. if self.defaults["global_open_style"] is False:
  7493. self.file_opened.emit("Document", filename)
  7494. self.file_saved.emit("Document", filename)
  7495. def on_file_saveexcellon(self):
  7496. """
  7497. Callback for menu item in project context menu.
  7498. :return: None
  7499. """
  7500. self.report_usage("on_file_saveexcellon")
  7501. App.log.debug("on_file_saveexcellon()")
  7502. obj = self.collection.get_active()
  7503. if obj is None:
  7504. self.inform.emit('[WARNING_NOTCL] %s' %
  7505. _("No object selected. Please select an Excellon object to export."))
  7506. return
  7507. # Check for more compatible types and add as required
  7508. if not isinstance(obj, FlatCAMExcellon):
  7509. self.inform.emit('[ERROR_NOTCL] %s' %
  7510. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7511. return
  7512. name = self.collection.get_active().options["name"]
  7513. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7514. try:
  7515. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7516. caption=_("Save Excellon source file"),
  7517. directory=self.get_last_save_folder() + '/' + name,
  7518. filter=_filter)
  7519. except TypeError:
  7520. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7521. filename = str(filename)
  7522. if filename == "":
  7523. self.inform.emit('[WARNING_NOTCL] %s' %
  7524. _("Saving Excellon source file cancelled."))
  7525. return
  7526. else:
  7527. self.save_source_file(name, filename)
  7528. if self.defaults["global_open_style"] is False:
  7529. self.file_opened.emit("Excellon", filename)
  7530. self.file_saved.emit("Excellon", filename)
  7531. def on_file_exportexcellon(self):
  7532. """
  7533. Callback for menu item File->Export->Excellon.
  7534. :return: None
  7535. """
  7536. self.report_usage("on_file_exportexcellon")
  7537. App.log.debug("on_file_exportexcellon()")
  7538. obj = self.collection.get_active()
  7539. if obj is None:
  7540. self.inform.emit('[WARNING_NOTCL] %s' %
  7541. _("No object selected. Please Select an Excellon object to export."))
  7542. return
  7543. # Check for more compatible types and add as required
  7544. if not isinstance(obj, FlatCAMExcellon):
  7545. self.inform.emit('[ERROR_NOTCL] %s' %
  7546. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7547. return
  7548. name = self.collection.get_active().options["name"]
  7549. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7550. try:
  7551. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7552. caption=_("Export Excellon"),
  7553. directory=self.get_last_save_folder() + '/' + name,
  7554. filter=_filter)
  7555. except TypeError:
  7556. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7557. filename = str(filename)
  7558. if filename == "":
  7559. self.inform.emit('[WARNING_NOTCL] %s' %
  7560. _("Export Excellon cancelled."))
  7561. return
  7562. else:
  7563. self.export_excellon(name, filename)
  7564. if self.defaults["global_open_style"] is False:
  7565. self.file_opened.emit("Excellon", filename)
  7566. self.file_saved.emit("Excellon", filename)
  7567. def on_file_exportgerber(self):
  7568. """
  7569. Callback for menu item File->Export->Gerber.
  7570. :return: None
  7571. """
  7572. self.report_usage("on_file_exportgerber")
  7573. App.log.debug("on_file_exportgerber()")
  7574. obj = self.collection.get_active()
  7575. if obj is None:
  7576. self.inform.emit('[WARNING_NOTCL] %s' %
  7577. _("No object selected. Please Select an Gerber object to export."))
  7578. return
  7579. # Check for more compatible types and add as required
  7580. if not isinstance(obj, FlatCAMGerber):
  7581. self.inform.emit('[ERROR_NOTCL] %s' %
  7582. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7583. return
  7584. name = self.collection.get_active().options["name"]
  7585. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7586. try:
  7587. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7588. caption=_("Export Gerber"),
  7589. directory=self.get_last_save_folder() + '/' + name,
  7590. filter=_filter_)
  7591. except TypeError:
  7592. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7593. filename = str(filename)
  7594. if filename == "":
  7595. self.inform.emit('[WARNING_NOTCL] %s' %
  7596. _("Export Gerber cancelled."))
  7597. return
  7598. else:
  7599. self.export_gerber(name, filename)
  7600. if self.defaults["global_open_style"] is False:
  7601. self.file_opened.emit("Gerber", filename)
  7602. self.file_saved.emit("Gerber", filename)
  7603. def on_file_exportdxf(self):
  7604. """
  7605. Callback for menu item File->Export DXF.
  7606. :return: None
  7607. """
  7608. self.report_usage("on_file_exportdxf")
  7609. App.log.debug("on_file_exportdxf()")
  7610. obj = self.collection.get_active()
  7611. if obj is None:
  7612. self.inform.emit('[WARNING_NOTCL] %s' %
  7613. _("No object selected."))
  7614. msg = _("Please Select a Geometry object to export")
  7615. msgbox = QtWidgets.QMessageBox()
  7616. msgbox.setInformativeText(msg)
  7617. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7618. msgbox.setDefaultButton(bt_ok)
  7619. msgbox.exec_()
  7620. return
  7621. # Check for more compatible types and add as required
  7622. if not isinstance(obj, FlatCAMGeometry):
  7623. msg = '[ERROR_NOTCL] %s' % \
  7624. _("Only Geometry objects can be used.")
  7625. msgbox = QtWidgets.QMessageBox()
  7626. msgbox.setInformativeText(msg)
  7627. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7628. msgbox.setDefaultButton(bt_ok)
  7629. msgbox.exec_()
  7630. return
  7631. name = self.collection.get_active().options["name"]
  7632. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7633. try:
  7634. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7635. caption=_("Export DXF"),
  7636. directory=self.get_last_save_folder() + '/' + name,
  7637. filter=_filter_)
  7638. except TypeError:
  7639. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7640. filter=_filter_)
  7641. filename = str(filename)
  7642. if filename == "":
  7643. self.inform.emit('[WARNING_NOTCL] %s' %
  7644. _("Export DXF cancelled."))
  7645. return
  7646. else:
  7647. self.export_dxf(name, filename)
  7648. if self.defaults["global_open_style"] is False:
  7649. self.file_opened.emit("DXF", filename)
  7650. self.file_saved.emit("DXF", filename)
  7651. def on_file_importsvg(self, type_of_obj):
  7652. """
  7653. Callback for menu item File->Import SVG.
  7654. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7655. :type type_of_obj: str
  7656. :return: None
  7657. """
  7658. self.report_usage("on_file_importsvg")
  7659. App.log.debug("on_file_importsvg()")
  7660. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7661. try:
  7662. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7663. directory=self.get_last_folder(), filter=_filter_)
  7664. except TypeError:
  7665. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7666. filter=_filter_)
  7667. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7668. type_of_obj = "geometry"
  7669. filenames = [str(filename) for filename in filenames]
  7670. if len(filenames) == 0:
  7671. self.inform.emit('[WARNING_NOTCL] %s' %
  7672. _("Open SVG cancelled."))
  7673. else:
  7674. for filename in filenames:
  7675. if filename != '':
  7676. self.worker_task.emit({'fcn': self.import_svg,
  7677. 'params': [filename, type_of_obj]})
  7678. def on_file_importdxf(self, type_of_obj):
  7679. """
  7680. Callback for menu item File->Import DXF.
  7681. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7682. :type type_of_obj: str
  7683. :return: None
  7684. """
  7685. self.report_usage("on_file_importdxf")
  7686. App.log.debug("on_file_importdxf()")
  7687. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7688. try:
  7689. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7690. directory=self.get_last_folder(),
  7691. filter=_filter_)
  7692. except TypeError:
  7693. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7694. filter=_filter_)
  7695. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7696. type_of_obj = "geometry"
  7697. filenames = [str(filename) for filename in filenames]
  7698. if len(filenames) == 0:
  7699. self.inform.emit('[WARNING_NOTCL] %s' %
  7700. _("Open DXF cancelled."))
  7701. else:
  7702. for filename in filenames:
  7703. if filename != '':
  7704. self.worker_task.emit({'fcn': self.import_dxf,
  7705. 'params': [filename, type_of_obj]})
  7706. # ###############################################################################################################
  7707. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7708. # ###############################################################################################################
  7709. def init_code_editor(self, name):
  7710. self.ui.text_editor_tab = TextEditor(app=self)
  7711. # add the tab if it was closed
  7712. self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, '%s' % name)
  7713. self.ui.text_editor_tab.setObjectName('text_editor_tab')
  7714. # delete the absolute and relative position and messages in the infobar
  7715. self.ui.position_label.setText("")
  7716. self.ui.rel_position_label.setText("")
  7717. # first clear previous text in text editor (if any)
  7718. self.ui.text_editor_tab.code_editor.clear()
  7719. self.ui.text_editor_tab.code_editor.setReadOnly(False)
  7720. self.toggle_codeeditor = True
  7721. self.ui.text_editor_tab.code_editor.completer_enable = False
  7722. self.ui.text_editor_tab.buttonRun.hide()
  7723. # make sure to keep a reference to the code editor
  7724. self.reference_code_editor = self.ui.text_editor_tab.code_editor
  7725. # Switch plot_area to CNCJob tab
  7726. self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7727. def on_view_source(self):
  7728. self.inform.emit('%s' %
  7729. _("Viewing the source code of the selected object."))
  7730. self.proc_container.view.set_busy(_("Loading..."))
  7731. try:
  7732. obj = self.collection.get_active()
  7733. except Exception as e:
  7734. log.debug("App.on_view_source() --> %s" % str(e))
  7735. self.inform.emit('[WARNING_NOTCL] %s' %
  7736. _("Select an Gerber or Excellon file to view it's source file."))
  7737. return 'fail'
  7738. if obj.kind == 'gerber':
  7739. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7740. elif obj.kind == 'excellon':
  7741. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7742. elif obj.kind == 'cncjob':
  7743. "GCode Files (*.NC);;All Files (*.*)"
  7744. else:
  7745. flt = "All Files (*.*)"
  7746. self.source_editor_tab = TextEditor(app=self)
  7747. # add the tab if it was closed
  7748. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  7749. self.source_editor_tab.setObjectName('source_editor_tab')
  7750. # delete the absolute and relative position and messages in the infobar
  7751. self.ui.position_label.setText("")
  7752. self.ui.rel_position_label.setText("")
  7753. # first clear previous text in text editor (if any)
  7754. self.source_editor_tab.code_editor.clear()
  7755. self.source_editor_tab.code_editor.setReadOnly(False)
  7756. self.source_editor_tab.code_editor.completer_enable = False
  7757. self.source_editor_tab.buttonRun.hide()
  7758. # Switch plot_area to CNCJob tab
  7759. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  7760. self.source_editor_tab.buttonOpen.clicked.disconnect()
  7761. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  7762. self.source_editor_tab.buttonSave.clicked.disconnect()
  7763. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  7764. # then append the text from GCode to the text editor
  7765. if obj.kind == 'cncjob':
  7766. try:
  7767. file = obj.export_gcode(
  7768. preamble=self.defaults["cncjob_prepend"],
  7769. postamble=self.defaults["cncjob_append"],
  7770. to_file=True)
  7771. if file == 'fail':
  7772. return 'fail'
  7773. except AttributeError:
  7774. self.inform.emit('[WARNING_NOTCL] %s' %
  7775. _("There is no selected object for which to see it's source file code."))
  7776. return 'fail'
  7777. else:
  7778. try:
  7779. file = StringIO(obj.source_file)
  7780. except AttributeError:
  7781. self.inform.emit('[WARNING_NOTCL] %s' %
  7782. _("There is no selected object for which to see it's source file code."))
  7783. return 'fail'
  7784. self.source_editor_tab.t_frame.hide()
  7785. try:
  7786. for line in file:
  7787. QtWidgets.QApplication.processEvents()
  7788. proc_line = str(line).strip('\n')
  7789. self.source_editor_tab.code_editor.append(proc_line)
  7790. except Exception as e:
  7791. log.debug('App.on_view_source() -->%s' % str(e))
  7792. self.inform.emit('[ERROR] %s: %s' %
  7793. (_('Failed to load the source code for the selected object'), str(e)))
  7794. return
  7795. self.source_editor_tab.handleTextChanged()
  7796. self.source_editor_tab.t_frame.show()
  7797. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7798. self.proc_container.view.set_idle()
  7799. # self.ui.show()
  7800. def on_toggle_code_editor(self):
  7801. self.report_usage("on_toggle_code_editor()")
  7802. if self.toggle_codeeditor is False:
  7803. self.init_code_editor(name=_("Code Editor"))
  7804. self.ui.text_editor_tab.buttonOpen.clicked.disconnect()
  7805. self.ui.text_editor_tab.buttonOpen.clicked.connect(lambda: self.ui.text_editor_tab.handleOpen())
  7806. self.ui.text_editor_tab.buttonSave.clicked.disconnect()
  7807. self.ui.text_editor_tab.buttonSave.clicked.connect(lambda: self.ui.text_editor_tab.handleSaveGCode())
  7808. else:
  7809. for idx in range(self.ui.plot_tab_area.count()):
  7810. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  7811. self.ui.plot_tab_area.closeTab(idx)
  7812. break
  7813. self.toggle_codeeditor = False
  7814. def on_filenewscript(self, silent=False, name=None, text=None):
  7815. """
  7816. Will create a new script file and open it in the Code Editor
  7817. :param silent: if True will not display status messages
  7818. :return: None
  7819. """
  7820. if silent is False:
  7821. self.inform.emit('[success] %s' %
  7822. _("New TCL script file created in Code Editor."))
  7823. # delete the absolute and relative position and messages in the infobar
  7824. self.ui.position_label.setText("")
  7825. self.ui.rel_position_label.setText("")
  7826. if name is not None:
  7827. self.new_script_object(name=name, text=text)
  7828. else:
  7829. self.new_script_object(text=text)
  7830. # script_text = script_obj.source_file
  7831. #
  7832. # self.proc_container.view.set_busy(_("Loading..."))
  7833. # script_obj.script_editor_tab.t_frame.hide()
  7834. #
  7835. # script_obj.script_editor_tab.t_frame.show()
  7836. # self.proc_container.view.set_idle()
  7837. def on_fileopenscript(self, name=None, silent=False):
  7838. """
  7839. Will open a Tcl script file into the Code Editor
  7840. :param silent: if True will not display status messages
  7841. :param name: name of a Tcl script file to open
  7842. :return:
  7843. """
  7844. self.report_usage("on_fileopenscript")
  7845. App.log.debug("on_fileopenscript()")
  7846. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7847. if name:
  7848. filenames = [name]
  7849. else:
  7850. try:
  7851. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7852. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  7853. except TypeError:
  7854. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7855. if len(filenames) == 0:
  7856. if silent is False:
  7857. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  7858. else:
  7859. for filename in filenames:
  7860. if filename != '':
  7861. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7862. def on_filerunscript(self, name=None, silent=False):
  7863. """
  7864. File menu callback for loading and running a TCL script.
  7865. :param silent: if True will not display status messages
  7866. :param name: name of a Tcl script file to be run by FlatCAM
  7867. :return: None
  7868. """
  7869. self.report_usage("on_filerunscript")
  7870. App.log.debug("on_file_runscript()")
  7871. if name:
  7872. filename = name
  7873. if self.cmd_line_headless != 1:
  7874. self.splash.showMessage('%s: %ssec\n%s' %
  7875. (_("Canvas initialization started.\n"
  7876. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7877. _("Executing FlatCAMScript file.")
  7878. ),
  7879. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7880. color=QtGui.QColor("gray"))
  7881. else:
  7882. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7883. try:
  7884. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7885. directory=self.get_last_folder(), filter=_filter_)
  7886. except TypeError:
  7887. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7888. # The Qt methods above will return a QString which can cause problems later.
  7889. # So far json.dump() will fail to serialize it.
  7890. # TODO: Improve the serialization methods and remove this fix.
  7891. filename = str(filename)
  7892. if filename == "":
  7893. if silent is False:
  7894. self.inform.emit('[WARNING_NOTCL] %s' %
  7895. _("Run TCL script cancelled."))
  7896. else:
  7897. if self.cmd_line_headless != 1:
  7898. if self.ui.shell_dock.isHidden():
  7899. self.ui.shell_dock.show()
  7900. try:
  7901. with open(filename, "r") as tcl_script:
  7902. cmd_line_shellfile_content = tcl_script.read()
  7903. if self.cmd_line_headless != 1:
  7904. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7905. else:
  7906. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7907. if silent is False:
  7908. self.inform.emit('[success] %s' %
  7909. _("TCL script file opened in Code Editor and executed."))
  7910. except Exception as e:
  7911. log.debug("App.on_filerunscript() -> %s" % str(e))
  7912. sys.exit(2)
  7913. def on_file_saveproject(self, silent=False):
  7914. """
  7915. Callback for menu item File->Save Project. Saves the project to
  7916. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7917. if set to None. The project is saved by calling ``self.save_project()``.
  7918. :param silent: if True will not display status messages
  7919. :return: None
  7920. """
  7921. self.report_usage("on_file_saveproject")
  7922. if self.project_filename is None:
  7923. self.on_file_saveprojectas()
  7924. else:
  7925. self.worker_task.emit({'fcn': self.save_project,
  7926. 'params': [self.project_filename, silent]})
  7927. if self.defaults["global_open_style"] is False:
  7928. self.file_opened.emit("project", self.project_filename)
  7929. self.file_saved.emit("project", self.project_filename)
  7930. self.set_ui_title(name=self.project_filename)
  7931. self.should_we_save = False
  7932. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7933. """
  7934. Callback for menu item File->Save Project As... Opens a file
  7935. chooser and saves the project to the given file via
  7936. ``self.save_project()``.
  7937. :param make_copy if to be create a copy of the project; boolean
  7938. :param use_thread: if to be run in a separate thread; boolean
  7939. :param quit_action: if to be followed by quiting the application; boolean
  7940. :return: None
  7941. """
  7942. self.report_usage("on_file_saveprojectas")
  7943. self.date = str(datetime.today()).rpartition('.')[0]
  7944. self.date = ''.join(c for c in self.date if c not in ':-')
  7945. self.date = self.date.replace(' ', '_')
  7946. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7947. try:
  7948. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7949. caption=_("Save Project As ..."),
  7950. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7951. filter=filter_)
  7952. except TypeError:
  7953. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7954. filename = str(filename)
  7955. if filename == '':
  7956. self.inform.emit('[WARNING_NOTCL] %s' %
  7957. _("Save Project cancelled."))
  7958. return
  7959. try:
  7960. f = open(filename, 'r')
  7961. f.close()
  7962. except IOError:
  7963. pass
  7964. if use_thread is True:
  7965. self.worker_task.emit({'fcn': self.save_project,
  7966. 'params': [filename, quit_action]})
  7967. else:
  7968. self.save_project(filename, quit_action)
  7969. # self.save_project(filename)
  7970. if self.defaults["global_open_style"] is False:
  7971. self.file_opened.emit("project", filename)
  7972. self.file_saved.emit("project", filename)
  7973. if not make_copy:
  7974. self.project_filename = filename
  7975. self.set_ui_title(name=self.project_filename)
  7976. self.should_we_save = False
  7977. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7978. """
  7979. Exports a Geometry Object to an SVG file.
  7980. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7981. :param filename: Path to the SVG file to save to.
  7982. :param scale_factor: factor by which to change/scale the thickness of the features
  7983. :return:
  7984. """
  7985. self.report_usage("export_svg()")
  7986. if filename is None:
  7987. filename = self.defaults["global_last_save_folder"]
  7988. self.log.debug("export_svg()")
  7989. try:
  7990. obj = self.collection.get_by_name(str(obj_name))
  7991. except:
  7992. # TODO: The return behavior has not been established... should raise exception?
  7993. return "Could not retrieve object: %s" % obj_name
  7994. with self.proc_container.new(_("Exporting SVG")) as proc:
  7995. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7996. # Determine bounding area for svg export
  7997. bounds = obj.bounds()
  7998. size = obj.size()
  7999. # Convert everything to strings for use in the xml doc
  8000. svgwidth = str(size[0])
  8001. svgheight = str(size[1])
  8002. minx = str(bounds[0])
  8003. miny = str(bounds[1] - size[1])
  8004. uom = obj.units.lower()
  8005. # Add a SVG Header and footer to the svg output from shapely
  8006. # The transform flips the Y Axis so that everything renders
  8007. # properly within svg apps such as inkscape
  8008. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8009. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8010. svg_header += 'width="' + svgwidth + uom + '" '
  8011. svg_header += 'height="' + svgheight + uom + '" '
  8012. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8013. svg_header += '<g transform="scale(1,-1)">'
  8014. svg_footer = '</g> </svg>'
  8015. svg_elem = svg_header + exported_svg + svg_footer
  8016. # Parse the xml through a xml parser just to add line feeds
  8017. # and to make it look more pretty for the output
  8018. svgcode = parse_xml_string(svg_elem)
  8019. try:
  8020. with open(filename, 'w') as fp:
  8021. fp.write(svgcode.toprettyxml())
  8022. except PermissionError:
  8023. self.inform.emit('[WARNING] %s' %
  8024. _("Permission denied, saving not possible.\n"
  8025. "Most likely another app is holding the file open and not accessible."))
  8026. return 'fail'
  8027. if self.defaults["global_open_style"] is False:
  8028. self.file_opened.emit("SVG", filename)
  8029. self.file_saved.emit("SVG", filename)
  8030. self.inform.emit('[success] %s: %s' %
  8031. (_("SVG file exported to"), filename))
  8032. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  8033. """
  8034. Exports a Geometry Object to an SVG file in negative.
  8035. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8036. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8037. :param filename: Path to the SVG file to save to.
  8038. :param boundary: thickness of a black border to surround all the features
  8039. :param scale_factor: factor by which to change/scale the thickness of the features
  8040. :param use_thread: if to be run in a separate thread; boolean
  8041. :return:
  8042. """
  8043. self.report_usage("export_negative()")
  8044. if filename is None:
  8045. filename = self.defaults["global_last_save_folder"]
  8046. self.log.debug("export_svg() negative")
  8047. try:
  8048. obj = self.collection.get_by_name(str(obj_name))
  8049. except:
  8050. # TODO: The return behavior has not been established... should raise exception?
  8051. return "Could not retrieve object: %s" % obj_name
  8052. try:
  8053. box = self.collection.get_by_name(str(box_name))
  8054. except:
  8055. # TODO: The return behavior has not been established... should raise exception?
  8056. return "Could not retrieve object: %s" % box_name
  8057. if box is None:
  8058. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8059. (_("No object Box. Using instead"), obj))
  8060. box = obj
  8061. def make_negative_film():
  8062. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8063. # Determine bounding area for svg export
  8064. bounds = box.bounds()
  8065. size = box.size()
  8066. uom = obj.units.lower()
  8067. # Convert everything to strings for use in the xml doc
  8068. svgwidth = str(size[0] + (2 * boundary))
  8069. svgheight = str(size[1] + (2 * boundary))
  8070. minx = str(bounds[0] - boundary)
  8071. miny = str(bounds[1] + boundary + size[1])
  8072. miny_rect = str(bounds[1] - boundary)
  8073. # Add a SVG Header and footer to the svg output from shapely
  8074. # The transform flips the Y Axis so that everything renders
  8075. # properly within svg apps such as inkscape
  8076. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8077. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8078. svg_header += 'width="' + svgwidth + uom + '" '
  8079. svg_header += 'height="' + svgheight + uom + '" '
  8080. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8081. svg_header += '>'
  8082. svg_header += '<g transform="scale(1,-1)">'
  8083. svg_footer = '</g> </svg>'
  8084. # Change the attributes of the exported SVG
  8085. # We don't need stroke-width - wrong, we do when we have lines with certain width
  8086. # We set opacity to maximum
  8087. # We set the color to WHITE
  8088. root = ET.fromstring(exported_svg)
  8089. for child in root:
  8090. child.set('fill', '#FFFFFF')
  8091. child.set('opacity', '1.0')
  8092. child.set('stroke', '#FFFFFF')
  8093. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  8094. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  8095. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  8096. first_svg_elem_tag = 'rect'
  8097. first_svg_elem_attribs = {
  8098. 'x': minx,
  8099. 'y': miny_rect,
  8100. 'width': svgwidth,
  8101. 'height': svgheight,
  8102. 'id': 'neg_rect',
  8103. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  8104. }
  8105. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  8106. exported_svg = ET.tostring(root)
  8107. svg_elem = svg_header + str(exported_svg) + svg_footer
  8108. # Parse the xml through a xml parser just to add line feeds
  8109. # and to make it look more pretty for the output
  8110. doc = parse_xml_string(svg_elem)
  8111. try:
  8112. with open(filename, 'w') as fp:
  8113. fp.write(doc.toprettyxml())
  8114. except PermissionError:
  8115. self.inform.emit('[WARNING] %s' %
  8116. _("Permission denied, saving not possible.\n"
  8117. "Most likely another app is holding the file open and not accessible."))
  8118. return 'fail'
  8119. if self.defaults["global_open_style"] is False:
  8120. self.file_opened.emit("SVG", filename)
  8121. self.file_saved.emit("SVG", filename)
  8122. self.inform.emit('[success] %s: %s' %
  8123. (_("SVG file exported to"), filename))
  8124. if use_thread is True:
  8125. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8126. def job_thread_film(app_obj):
  8127. try:
  8128. make_negative_film()
  8129. except Exception as e:
  8130. proc.done()
  8131. return
  8132. proc.done()
  8133. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8134. else:
  8135. make_negative_film()
  8136. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  8137. """
  8138. Exports a Geometry Object to an SVG file in positive black.
  8139. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8140. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8141. :param filename: Path to the SVG file to save to.
  8142. :param scale_factor: factor by which to change/scale the thickness of the features
  8143. :param use_thread: if to be run in a separate thread; boolean
  8144. :return:
  8145. """
  8146. self.report_usage("export_svg_positive()")
  8147. if filename is None:
  8148. filename = self.defaults["global_last_save_folder"]
  8149. self.log.debug("export_svg() black")
  8150. try:
  8151. obj = self.collection.get_by_name(str(obj_name))
  8152. except:
  8153. # TODO: The return behavior has not been established... should raise exception?
  8154. return "Could not retrieve object: %s" % obj_name
  8155. try:
  8156. box = self.collection.get_by_name(str(box_name))
  8157. except:
  8158. # TODO: The return behavior has not been established... should raise exception?
  8159. return "Could not retrieve object: %s" % box_name
  8160. if box is None:
  8161. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8162. (_("No object Box. Using instead"), obj))
  8163. box = obj
  8164. def make_positive_film():
  8165. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8166. self.progress.emit(40)
  8167. # Change the attributes of the exported SVG
  8168. # We don't need stroke-width
  8169. # We set opacity to maximum
  8170. # We set the colour to WHITE
  8171. root = ET.fromstring(exported_svg)
  8172. for child in root:
  8173. child.set('fill', str(self.defaults['tools_film_color']))
  8174. child.set('opacity', '1.0')
  8175. child.set('stroke', str(self.defaults['tools_film_color']))
  8176. exported_svg = ET.tostring(root)
  8177. # Determine bounding area for svg export
  8178. bounds = box.bounds()
  8179. size = box.size()
  8180. # This contain the measure units
  8181. uom = obj.units.lower()
  8182. # Define a boundary around SVG of about 1.0mm (~39mils)
  8183. if uom in "mm":
  8184. boundary = 1.0
  8185. else:
  8186. boundary = 0.0393701
  8187. self.progress.emit(80)
  8188. # Convert everything to strings for use in the xml doc
  8189. svgwidth = str(size[0] + (2 * boundary))
  8190. svgheight = str(size[1] + (2 * boundary))
  8191. minx = str(bounds[0] - boundary)
  8192. miny = str(bounds[1] + boundary + size[1])
  8193. self.log.debug(minx)
  8194. self.log.debug(miny)
  8195. # Add a SVG Header and footer to the svg output from shapely
  8196. # The transform flips the Y Axis so that everything renders
  8197. # properly within svg apps such as inkscape
  8198. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8199. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8200. svg_header += 'width="' + svgwidth + uom + '" '
  8201. svg_header += 'height="' + svgheight + uom + '" '
  8202. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8203. svg_header += '>'
  8204. svg_header += '<g transform="scale(1,-1)">'
  8205. svg_footer = '</g> </svg>'
  8206. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  8207. self.progress.emit(90)
  8208. # Parse the xml through a xml parser just to add line feeds
  8209. # and to make it look more pretty for the output
  8210. doc = parse_xml_string(svg_elem)
  8211. try:
  8212. with open(filename, 'w') as fp:
  8213. fp.write(doc.toprettyxml())
  8214. except PermissionError:
  8215. self.inform.emit('[WARNING] %s' %
  8216. _("Permission denied, saving not possible.\n"
  8217. "Most likely another app is holding the file open and not accessible."))
  8218. return 'fail'
  8219. self.progress.emit(100)
  8220. if self.defaults["global_open_style"] is False:
  8221. self.file_opened.emit("SVG", filename)
  8222. self.file_saved.emit("SVG", filename)
  8223. self.inform.emit('[success] %s: %s' %
  8224. (_("SVG file exported to"), filename))
  8225. if use_thread is True:
  8226. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8227. def job_thread_film(app_obj):
  8228. try:
  8229. make_positive_film()
  8230. except Exception as e:
  8231. proc.done()
  8232. return
  8233. proc.done()
  8234. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8235. else:
  8236. make_positive_film()
  8237. def save_source_file(self, obj_name, filename, use_thread=True):
  8238. """
  8239. Exports a FlatCAM Object to an Gerber/Excellon file.
  8240. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8241. :param filename: Path to the Gerber file to save to.
  8242. :param use_thread: if to be run in a separate thread
  8243. :return:
  8244. """
  8245. self.report_usage("save source file()")
  8246. if filename is None:
  8247. filename = self.defaults["global_last_save_folder"]
  8248. self.log.debug("save source file()")
  8249. obj = self.collection.get_by_name(obj_name)
  8250. file_string = StringIO(obj.source_file)
  8251. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8252. try:
  8253. with open(filename, 'w') as file:
  8254. file.writelines('G04*\n')
  8255. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8256. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8257. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8258. file.writelines('G04 Created on : %s*\n' % time_string)
  8259. for line in file_string:
  8260. file.writelines(line)
  8261. except PermissionError:
  8262. self.inform.emit('[WARNING] %s' %
  8263. _("Permission denied, saving not possible.\n"
  8264. "Most likely another app is holding the file open and not accessible."))
  8265. return 'fail'
  8266. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8267. """
  8268. Exports a Excellon Object to an Excellon file.
  8269. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8270. :param filename: Path to the Excellon file to save to.
  8271. :param use_thread: if to be run in a separate thread
  8272. :return:
  8273. """
  8274. self.report_usage("export_excellon()")
  8275. if filename is None:
  8276. filename = self.defaults["global_last_save_folder"]
  8277. self.log.debug("export_excellon()")
  8278. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8279. self.defaults["excellon_exp_decimals"]
  8280. )
  8281. units = ''
  8282. if local_use is None:
  8283. try:
  8284. obj = self.collection.get_by_name(str(obj_name))
  8285. except:
  8286. # TODO: The return behavior has not been established... should raise exception?
  8287. return "Could not retrieve object: %s" % obj_name
  8288. else:
  8289. obj = local_use
  8290. # updated units
  8291. eunits = self.defaults["excellon_exp_units"]
  8292. ewhole = self.defaults["excellon_exp_integer"]
  8293. efract = self.defaults["excellon_exp_decimals"]
  8294. ezeros = self.defaults["excellon_exp_zeros"]
  8295. eformat = self.defaults["excellon_exp_format"]
  8296. slot_type = self.defaults["excellon_exp_slot_type"]
  8297. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8298. if fc_units == 'MM':
  8299. factor = 1 if eunits == 'METRIC' else 0.03937
  8300. else:
  8301. factor = 25.4 if eunits == 'METRIC' else 1
  8302. def make_excellon():
  8303. try:
  8304. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8305. header = 'M48\n'
  8306. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8307. (str(self.version), str(self.version_date))
  8308. header += ';Filename: %s' % str(obj_name) + '\n'
  8309. header += ';Created on : %s' % time_str + '\n'
  8310. if eformat == 'dec':
  8311. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8312. header += eunits + '\n'
  8313. for tool in obj.tools:
  8314. if eunits == 'METRIC':
  8315. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8316. tool=str(tool),
  8317. dec=2)
  8318. else:
  8319. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8320. tool=str(tool),
  8321. dec=4)
  8322. else:
  8323. if ezeros == 'LZ':
  8324. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8325. form='ndec', e_zeros='LZ', factor=factor,
  8326. slot_type=slot_type)
  8327. header += '%s,%s\n' % (eunits, 'LZ')
  8328. header += format_exc
  8329. for tool in obj.tools:
  8330. if eunits == 'METRIC':
  8331. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8332. tool=str(tool),
  8333. dec=2)
  8334. else:
  8335. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8336. tool=str(tool),
  8337. dec=4)
  8338. else:
  8339. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8340. form='ndec', e_zeros='TZ', factor=factor,
  8341. slot_type=slot_type)
  8342. header += '%s,%s\n' % (eunits, 'TZ')
  8343. header += format_exc
  8344. for tool in obj.tools:
  8345. if eunits == 'METRIC':
  8346. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8347. tool=str(tool),
  8348. dec=2)
  8349. else:
  8350. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8351. tool=str(tool),
  8352. dec=4)
  8353. header += '%\n'
  8354. footer = 'M30\n'
  8355. exported_excellon = header
  8356. exported_excellon += excellon_code
  8357. exported_excellon += footer
  8358. if local_use is None:
  8359. try:
  8360. with open(filename, 'w') as fp:
  8361. fp.write(exported_excellon)
  8362. except PermissionError:
  8363. self.inform.emit('[WARNING] %s' %
  8364. _("Permission denied, saving not possible.\n"
  8365. "Most likely another app is holding the file open and not accessible."))
  8366. return 'fail'
  8367. if self.defaults["global_open_style"] is False:
  8368. self.file_opened.emit("Excellon", filename)
  8369. self.file_saved.emit("Excellon", filename)
  8370. self.inform.emit('[success] %s: %s' %
  8371. (_("Excellon file exported to"), filename))
  8372. else:
  8373. return exported_excellon
  8374. except Exception as e:
  8375. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8376. return 'fail'
  8377. if use_thread is True:
  8378. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8379. def job_thread_exc(app_obj):
  8380. ret = make_excellon()
  8381. if ret == 'fail':
  8382. self.inform.emit('[ERROR_NOTCL] %s' %
  8383. _('Could not export Excellon file.'))
  8384. return
  8385. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8386. else:
  8387. ret = make_excellon()
  8388. if ret == 'fail':
  8389. self.inform.emit('[ERROR_NOTCL] %s' %
  8390. _('Could not export Excellon file.'))
  8391. return 'fail'
  8392. if local_use is not None:
  8393. return ret
  8394. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8395. """
  8396. Exports a Gerber Object to an Gerber file.
  8397. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8398. :param filename: Path to the Gerber file to save to.
  8399. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8400. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8401. :param use_thread: if to be run in a separate thread
  8402. :return:
  8403. """
  8404. self.report_usage("export_gerber()")
  8405. if filename is None:
  8406. filename = self.defaults["global_last_save_folder"]
  8407. self.log.debug("export_gerber()")
  8408. if local_use is None:
  8409. try:
  8410. obj = self.collection.get_by_name(str(obj_name))
  8411. except:
  8412. # TODO: The return behavior has not been established... should raise exception?
  8413. return "Could not retrieve object: %s" % obj_name
  8414. else:
  8415. obj = local_use
  8416. # updated units
  8417. gunits = self.defaults["gerber_exp_units"]
  8418. gwhole = self.defaults["gerber_exp_integer"]
  8419. gfract = self.defaults["gerber_exp_decimals"]
  8420. gzeros = self.defaults["gerber_exp_zeros"]
  8421. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8422. if fc_units == 'MM':
  8423. factor = 1 if gunits == 'MM' else 0.03937
  8424. else:
  8425. factor = 25.4 if gunits == 'MM' else 1
  8426. def make_gerber():
  8427. try:
  8428. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8429. header = 'G04*\n'
  8430. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8431. (str(self.version), str(self.version_date))
  8432. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8433. header += 'G04 Created on : %s*' % time_str + '\n'
  8434. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8435. header += "%MO{units}*%\n".format(units=gunits)
  8436. for apid in obj.apertures:
  8437. if obj.apertures[apid]['type'] == 'C':
  8438. header += "%ADD{apid}{type},{size}*%\n".format(
  8439. apid=str(apid),
  8440. type='C',
  8441. size=(factor * obj.apertures[apid]['size'])
  8442. )
  8443. elif obj.apertures[apid]['type'] == 'R':
  8444. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8445. apid=str(apid),
  8446. type='R',
  8447. width=(factor * obj.apertures[apid]['width']),
  8448. height=(factor * obj.apertures[apid]['height'])
  8449. )
  8450. elif obj.apertures[apid]['type'] == 'O':
  8451. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8452. apid=str(apid),
  8453. type='O',
  8454. width=(factor * obj.apertures[apid]['width']),
  8455. height=(factor * obj.apertures[apid]['height'])
  8456. )
  8457. header += '\n'
  8458. # obsolete units but some software may need it
  8459. if gunits == 'IN':
  8460. header += 'G70*\n'
  8461. else:
  8462. header += 'G71*\n'
  8463. # Absolute Mode
  8464. header += 'G90*\n'
  8465. header += 'G01*\n'
  8466. # positive polarity
  8467. header += '%LPD*%\n'
  8468. footer = 'M02*\n'
  8469. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8470. exported_gerber = header
  8471. exported_gerber += gerber_code
  8472. exported_gerber += footer
  8473. if local_use is None:
  8474. try:
  8475. with open(filename, 'w') as fp:
  8476. fp.write(exported_gerber)
  8477. except PermissionError:
  8478. self.inform.emit('[WARNING] %s' %
  8479. _("Permission denied, saving not possible.\n"
  8480. "Most likely another app is holding the file open and not accessible."))
  8481. return 'fail'
  8482. if self.defaults["global_open_style"] is False:
  8483. self.file_opened.emit("Gerber", filename)
  8484. self.file_saved.emit("Gerber", filename)
  8485. self.inform.emit('[success] %s: %s' %
  8486. (_("Gerber file exported to"), filename))
  8487. else:
  8488. return exported_gerber
  8489. except Exception as e:
  8490. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8491. return 'fail'
  8492. if use_thread is True:
  8493. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8494. def job_thread_grb(app_obj):
  8495. ret = make_gerber()
  8496. if ret == 'fail':
  8497. self.inform.emit('[ERROR_NOTCL] %s' %
  8498. _('Could not export Gerber file.'))
  8499. return
  8500. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8501. else:
  8502. ret = make_gerber()
  8503. if ret == 'fail':
  8504. self.inform.emit('[ERROR_NOTCL] %s' %
  8505. _('Could not export Gerber file.'))
  8506. return 'fail'
  8507. if local_use is not None:
  8508. return ret
  8509. def export_dxf(self, obj_name, filename, use_thread=True):
  8510. """
  8511. Exports a Geometry Object to an DXF file.
  8512. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8513. :param filename: Path to the DXF file to save to.
  8514. :param use_thread: if to be run in a separate thread
  8515. :return:
  8516. """
  8517. self.report_usage("export_dxf()")
  8518. if filename is None:
  8519. filename = self.defaults["global_last_save_folder"]
  8520. self.log.debug("export_dxf()")
  8521. format_exc = ''
  8522. units = ''
  8523. try:
  8524. obj = self.collection.get_by_name(str(obj_name))
  8525. except:
  8526. # TODO: The return behavior has not been established... should raise exception?
  8527. return "Could not retrieve object: %s" % obj_name
  8528. # updated units
  8529. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8530. if units == 'IN' or units == 'INCH':
  8531. units = 'INCH'
  8532. elif units == 'MM' or units == 'METIRC':
  8533. units ='METRIC'
  8534. def make_dxf():
  8535. try:
  8536. dxf_code = obj.export_dxf()
  8537. dxf_code.saveas(filename)
  8538. if self.defaults["global_open_style"] is False:
  8539. self.file_opened.emit("DXF", filename)
  8540. self.file_saved.emit("DXF", filename)
  8541. self.inform.emit('[success] %s: %s' %
  8542. (_("DXF file exported to"), filename))
  8543. except:
  8544. return 'fail'
  8545. if use_thread is True:
  8546. with self.proc_container.new(_("Exporting DXF")) as proc:
  8547. def job_thread_exc(app_obj):
  8548. ret = make_dxf()
  8549. if ret == 'fail':
  8550. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8551. _('Could not export DXF file.'))
  8552. return
  8553. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8554. else:
  8555. ret = make_dxf()
  8556. if ret == 'fail':
  8557. self.inform.emit('[WARNING_NOTCL] %s' %
  8558. _('Could not export DXF file.'))
  8559. return
  8560. def import_svg(self, filename, geo_type='geometry', outname=None):
  8561. """
  8562. Adds a new Geometry Object to the projects and populates
  8563. it with shapes extracted from the SVG file.
  8564. :param filename: Path to the SVG file.
  8565. :param geo_type: Type of FlatCAM object that will be created from SVG
  8566. :param outname:
  8567. :return:
  8568. """
  8569. self.report_usage("import_svg()")
  8570. obj_type = ""
  8571. if geo_type is None or geo_type == "geometry":
  8572. obj_type = "geometry"
  8573. elif geo_type == "gerber":
  8574. obj_type = geo_type
  8575. else:
  8576. self.inform.emit('[ERROR_NOTCL] %s' %
  8577. _("Not supported type is picked as parameter. "
  8578. "Only Geometry and Gerber are supported"))
  8579. return
  8580. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8581. def obj_init(geo_obj, app_obj):
  8582. geo_obj.import_svg(filename, obj_type, units=units)
  8583. geo_obj.multigeo = False
  8584. with self.proc_container.new(_("Importing SVG")) as proc:
  8585. # Object name
  8586. name = outname or filename.split('/')[-1].split('\\')[-1]
  8587. self.new_object(obj_type, name, obj_init, autoselected=False)
  8588. self.progress.emit(20)
  8589. # Register recent file
  8590. self.file_opened.emit("svg", filename)
  8591. # GUI feedback
  8592. self.inform.emit('[success] %s: %s' %
  8593. (_("Opened"), filename))
  8594. self.progress.emit(100)
  8595. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8596. """
  8597. Adds a new Geometry Object to the projects and populates
  8598. it with shapes extracted from the DXF file.
  8599. :param filename: Path to the DXF file.
  8600. :param geo_type: Type of FlatCAM object that will be created from DXF
  8601. :param outname:
  8602. :type putname: str
  8603. :return:
  8604. """
  8605. self.report_usage("import_dxf()")
  8606. obj_type = ""
  8607. if geo_type is None or geo_type == "geometry":
  8608. obj_type = "geometry"
  8609. elif geo_type == "gerber":
  8610. obj_type = geo_type
  8611. else:
  8612. self.inform.emit('[ERROR_NOTCL] %s' %
  8613. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8614. return
  8615. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8616. def obj_init(geo_obj, app_obj):
  8617. geo_obj.import_dxf(filename, obj_type, units=units)
  8618. geo_obj.multigeo = False
  8619. with self.proc_container.new(_("Importing DXF")) as proc:
  8620. # Object name
  8621. name = outname or filename.split('/')[-1].split('\\')[-1]
  8622. self.new_object(obj_type, name, obj_init, autoselected=False)
  8623. self.progress.emit(20)
  8624. # Register recent file
  8625. self.file_opened.emit("dxf", filename)
  8626. # GUI feedback
  8627. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8628. self.progress.emit(100)
  8629. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8630. """
  8631. Adds a new Geometry Object to the projects and populates
  8632. it with shapes extracted from the SVG file.
  8633. :param filename: Path to the SVG file.
  8634. :param o_type: type of FlatCAM objeect
  8635. :param dpi: dot per inch
  8636. :param mode: black or color
  8637. :param mask: dictate the level of detail
  8638. :param outname: name for the resulting file
  8639. :return:
  8640. """
  8641. self.report_usage("import_image()")
  8642. if o_type is None or o_type == "geometry":
  8643. obj_type = "geometry"
  8644. elif o_type == "gerber":
  8645. obj_type = o_type
  8646. else:
  8647. self.inform.emit('[ERROR_NOTCL] %s' %
  8648. _("Not supported type is picked as parameter. "
  8649. "Only Geometry and Gerber are supported"))
  8650. return
  8651. def obj_init(geo_obj, app_obj):
  8652. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8653. geo_obj.multigeo = False
  8654. with self.proc_container.new(_("Importing Image")) as proc:
  8655. # Object name
  8656. name = outname or filename.split('/')[-1].split('\\')[-1]
  8657. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8658. self.new_object(obj_type, name, obj_init)
  8659. self.progress.emit(20)
  8660. # Register recent file
  8661. self.file_opened.emit("image", filename)
  8662. # GUI feedback
  8663. self.inform.emit('[success] %s: %s' %
  8664. (_("Opened"), filename))
  8665. self.progress.emit(100)
  8666. def open_gerber(self, filename, outname=None):
  8667. """
  8668. Opens a Gerber file, parses it and creates a new object for
  8669. it in the program. Thread-safe.
  8670. :param outname: Name of the resulting object. None causes the
  8671. name to be that of the file.
  8672. :param filename: Gerber file filename
  8673. :type filename: str
  8674. :param follow: If true, the parser will not create polygons, just lines
  8675. following the gerber path.
  8676. :type follow: bool
  8677. :return: None
  8678. """
  8679. # How the object should be initialized
  8680. def obj_init(gerber_obj, app_obj):
  8681. assert isinstance(gerber_obj, FlatCAMGerber), \
  8682. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8683. # Opening the file happens here
  8684. self.progress.emit(30)
  8685. try:
  8686. gerber_obj.parse_file(filename)
  8687. except IOError:
  8688. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8689. (_("Failed to open file"), filename))
  8690. app_obj.progress.emit(0)
  8691. return "fail"
  8692. except ParseError as err:
  8693. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8694. (_("Failed to parse file"), filename, str(err)))
  8695. app_obj.progress.emit(0)
  8696. self.log.error(str(err))
  8697. return "fail"
  8698. except Exception as e:
  8699. log.debug("App.open_gerber() --> %s" % str(e))
  8700. msg = '[ERROR] %s' % \
  8701. _("An internal error has occurred. See shell.\n")
  8702. msg += traceback.format_exc()
  8703. app_obj.inform.emit(msg)
  8704. return "fail"
  8705. if gerber_obj.is_empty():
  8706. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8707. # self.collection.set_active(gerber_obj.options["name"])
  8708. # self.collection.delete_active()
  8709. self.inform.emit('[ERROR_NOTCL] %s' %
  8710. _("Object is not Gerber file or empty. Aborting object creation."))
  8711. return "fail"
  8712. # Further parsing
  8713. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8714. App.log.debug("open_gerber()")
  8715. with self.proc_container.new(_("Opening Gerber")) as proc:
  8716. self.progress.emit(10)
  8717. # Object name
  8718. name = outname or filename.split('/')[-1].split('\\')[-1]
  8719. # # ## Object creation # ##
  8720. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8721. if ret == 'fail':
  8722. self.inform.emit('[ERROR_NOTCL]%s' %
  8723. _(' Open Gerber failed. Probable not a Gerber file.'))
  8724. return
  8725. # Register recent file
  8726. self.file_opened.emit("gerber", filename)
  8727. self.progress.emit(100)
  8728. # GUI feedback
  8729. self.inform.emit('[success] %s: %s' %
  8730. (_("Opened"), filename))
  8731. def open_excellon(self, filename, outname=None, plot=True):
  8732. """
  8733. Opens an Excellon file, parses it and creates a new object for
  8734. it in the program. Thread-safe.
  8735. :param outname: Name of the resulting object. None causes the
  8736. name to be that of the file.
  8737. :param filename: Excellon file filename
  8738. :type filename: str
  8739. :return: None
  8740. """
  8741. App.log.debug("open_excellon()")
  8742. # How the object should be initialized
  8743. def obj_init(excellon_obj, app_obj):
  8744. # self.progress.emit(20)
  8745. try:
  8746. ret = excellon_obj.parse_file(filename=filename)
  8747. if ret == "fail":
  8748. log.debug("Excellon parsing failed.")
  8749. self.inform.emit('[ERROR_NOTCL] %s' %
  8750. _("This is not Excellon file."))
  8751. return "fail"
  8752. except IOError:
  8753. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8754. (_("Cannot open file"), filename))
  8755. log.debug("Could not open Excellon object.")
  8756. self.progress.emit(0) # TODO: self and app_bjj mixed
  8757. return "fail"
  8758. except:
  8759. msg = '[ERROR_NOTCL] %s' % \
  8760. _("An internal error has occurred. See shell.\n")
  8761. msg += traceback.format_exc()
  8762. app_obj.inform.emit(msg)
  8763. return "fail"
  8764. ret = excellon_obj.create_geometry()
  8765. if ret == 'fail':
  8766. log.debug("Could not create geometry for Excellon object.")
  8767. return "fail"
  8768. for tool in excellon_obj.tools:
  8769. if excellon_obj.tools[tool]['solid_geometry']:
  8770. return
  8771. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8772. (_("No geometry found in file"), filename))
  8773. return "fail"
  8774. with self.proc_container.new(_("Opening Excellon.")):
  8775. # Object name
  8776. name = outname or filename.split('/')[-1].split('\\')[-1]
  8777. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8778. if ret_val == 'fail':
  8779. self.inform.emit('[ERROR_NOTCL] %s' %
  8780. _('Open Excellon file failed. Probable not an Excellon file.'))
  8781. return
  8782. # Register recent file
  8783. self.file_opened.emit("excellon", filename)
  8784. # GUI feedback
  8785. self.inform.emit('[success] %s: %s' %
  8786. (_("Opened"), filename))
  8787. def open_gcode(self, filename, outname=None, plot=True):
  8788. """
  8789. Opens a G-gcode file, parses it and creates a new object for
  8790. it in the program. Thread-safe.
  8791. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8792. :param filename: G-code file filename
  8793. :type filename: str
  8794. :return: None
  8795. """
  8796. App.log.debug("open_gcode()")
  8797. # How the object should be initialized
  8798. def obj_init(job_obj, app_obj_):
  8799. """
  8800. :param job_obj: the resulting object
  8801. :type app_obj_: App
  8802. """
  8803. assert isinstance(app_obj_, App), \
  8804. "Initializer expected App, got %s" % type(app_obj_)
  8805. try:
  8806. f = open(filename)
  8807. gcode = f.read()
  8808. f.close()
  8809. except IOError:
  8810. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8811. (_("Failed to open"), filename))
  8812. return "fail"
  8813. job_obj.gcode = gcode
  8814. ret = job_obj.gcode_parse()
  8815. if ret == "fail":
  8816. self.inform.emit('[ERROR_NOTCL] %s' %
  8817. _("This is not GCODE"))
  8818. return "fail"
  8819. job_obj.create_geometry()
  8820. with self.proc_container.new(_("Opening G-Code.")):
  8821. # Object name
  8822. name = outname or filename.split('/')[-1].split('\\')[-1]
  8823. # New object creation and file processing
  8824. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8825. if ret == 'fail':
  8826. self.inform.emit('[ERROR_NOTCL] %s' %
  8827. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8828. "Attempting to create a FlatCAM CNCJob Object from "
  8829. "G-Code file failed during processing"))
  8830. return "fail"
  8831. # Register recent file
  8832. self.file_opened.emit("cncjob", filename)
  8833. # GUI feedback
  8834. self.inform.emit('[success] %s: %s' %
  8835. (_("Opened"), filename))
  8836. def open_script(self, filename, outname=None, silent=False):
  8837. """
  8838. Opens a Script file, parses it and creates a new object for
  8839. it in the program. Thread-safe.
  8840. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8841. :param filename: Script file filename
  8842. :type filename: str
  8843. :return: None
  8844. """
  8845. App.log.debug("open_script()")
  8846. with self.proc_container.new(_("Opening TCL Script...")):
  8847. try:
  8848. with open(filename, "r") as opened_script:
  8849. script_content = opened_script.readlines()
  8850. script_content = ''.join(script_content)
  8851. if silent is False:
  8852. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8853. except Exception as e:
  8854. log.debug("App.open_script() -> %s" % str(e))
  8855. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  8856. return
  8857. # Object name
  8858. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8859. # New object creation and file processing
  8860. self.on_filenewscript(name=script_name, text=script_content)
  8861. # Register recent file
  8862. self.file_opened.emit("script", filename)
  8863. # GUI feedback
  8864. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8865. def open_config_file(self, filename, run_from_arg=None):
  8866. """
  8867. Loads a config file from the specified file.
  8868. :param filename: Name of the file from which to load.
  8869. :type filename: str
  8870. :return: None
  8871. """
  8872. App.log.debug("Opening config file: " + filename)
  8873. if run_from_arg:
  8874. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8875. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8876. _("Opening FlatCAM Config file.")),
  8877. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8878. color=QtGui.QColor("gray"))
  8879. # add the tab if it was closed
  8880. self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8881. # first clear previous text in text editor (if any)
  8882. self.ui.text_editor_tab.code_editor.clear()
  8883. # Switch plot_area to CNCJob tab
  8884. self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8885. try:
  8886. if filename:
  8887. f = QtCore.QFile(filename)
  8888. if f.open(QtCore.QIODevice.ReadOnly):
  8889. stream = QtCore.QTextStream(f)
  8890. gcode_edited = stream.readAll()
  8891. self.ui.text_editor_tab.code_editor.setPlainText(gcode_edited)
  8892. f.close()
  8893. except IOError:
  8894. App.log.error("Failed to open config file: %s" % filename)
  8895. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8896. (_("Failed to open config file"), filename))
  8897. return
  8898. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8899. """
  8900. Loads a project from the specified file.
  8901. 1) Loads and parses file
  8902. 2) Registers the file as recently opened.
  8903. 3) Calls on_file_new()
  8904. 4) Updates options
  8905. 5) Calls new_object() with the object's from_dict() as init method.
  8906. 6) Calls plot_all() if plot=True
  8907. :param filename: Name of the file from which to load.
  8908. :type filename: str
  8909. :param run_from_arg: True if run for arguments
  8910. :param plot: If True plot all objects in the project
  8911. :param cli: run from command line
  8912. :return: None
  8913. """
  8914. App.log.debug("Opening project: " + filename)
  8915. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8916. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8917. if cli is None:
  8918. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8919. if run_from_arg:
  8920. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8921. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8922. _("Opening FlatCAM Project file.")),
  8923. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8924. color=QtGui.QColor("gray"))
  8925. # Open and parse an uncompressed Project file
  8926. try:
  8927. f = open(filename, 'r')
  8928. except IOError:
  8929. App.log.error("Failed to open project file: %s" % filename)
  8930. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8931. (_("Failed to open project file"), filename))
  8932. return
  8933. try:
  8934. d = json.load(f, object_hook=dict2obj)
  8935. except Exception as e:
  8936. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8937. (filename, str(e)))
  8938. f.close()
  8939. # Open and parse a compressed Project file
  8940. try:
  8941. with lzma.open(filename) as f:
  8942. file_content = f.read().decode('utf-8')
  8943. d = json.loads(file_content, object_hook=dict2obj)
  8944. except Exception as e:
  8945. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8946. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8947. (_("Failed to open project file"), filename))
  8948. return
  8949. # Clear the current project
  8950. # # NOT THREAD SAFE # ##
  8951. if run_from_arg is True:
  8952. pass
  8953. elif cli is True:
  8954. self.delete_selection_shape()
  8955. else:
  8956. self.on_file_new()
  8957. # Project options
  8958. self.options.update(d['options'])
  8959. self.project_filename = filename
  8960. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8961. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8962. if cli is None:
  8963. self.set_screen_units(self.options["units"])
  8964. # Re create objects
  8965. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8966. for obj in d['objs']:
  8967. def obj_init(obj_inst, app_inst):
  8968. obj_inst.from_dict(obj)
  8969. App.log.debug("Recreating from opened project an %s object: %s" %
  8970. (obj['kind'].capitalize(), obj['options']['name']))
  8971. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8972. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8973. if cli is None:
  8974. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8975. obj['kind'].upper(),
  8976. obj['options']['name']
  8977. )
  8978. )
  8979. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8980. self.inform.emit('[success] %s: %s' %
  8981. (_("Project loaded from"), filename))
  8982. self.should_we_save = False
  8983. self.file_opened.emit("project", filename)
  8984. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8985. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8986. if cli is None:
  8987. self.set_ui_title(name=self.project_filename)
  8988. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8989. def propagate_defaults(self, silent=False):
  8990. """
  8991. This method is used to set default values in classes. It's
  8992. an alternative to project options but allows the use
  8993. of values invisible to the user.
  8994. :return: None
  8995. """
  8996. if silent is False:
  8997. self.log.debug("propagate_defaults()")
  8998. # Which objects to update the given parameters.
  8999. routes = {
  9000. "global_zdownrate": CNCjob,
  9001. "excellon_zeros": Excellon,
  9002. "excellon_format_upper_in": Excellon,
  9003. "excellon_format_lower_in": Excellon,
  9004. "excellon_format_upper_mm": Excellon,
  9005. "excellon_format_lower_mm": Excellon,
  9006. "excellon_units": Excellon,
  9007. "gerber_use_buffer_for_union": Gerber,
  9008. "geometry_multidepth": Geometry
  9009. }
  9010. for param in routes:
  9011. if param in routes[param].defaults:
  9012. try:
  9013. routes[param].defaults[param] = self.defaults[param]
  9014. if silent is False:
  9015. self.log.debug(" " + param + " OK")
  9016. except KeyError:
  9017. if silent is False:
  9018. self.log.debug(" ERROR: " + param + " not in defaults.")
  9019. else:
  9020. # Try extracting the name:
  9021. # classname_param here is param in the object
  9022. if param.find(routes[param].__name__.lower() + "_") == 0:
  9023. p = param[len(routes[param].__name__) + 1:]
  9024. if p in routes[param].defaults:
  9025. routes[param].defaults[p] = self.defaults[param]
  9026. if silent is False:
  9027. self.log.debug(" " + param + " OK!")
  9028. def plot_all(self, zoom=True):
  9029. """
  9030. Re-generates all plots from all objects.
  9031. :return: None
  9032. """
  9033. self.log.debug("Plot_all()")
  9034. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9035. for obj in self.collection.get_list():
  9036. def worker_task(obj):
  9037. with self.proc_container.new("Plotting"):
  9038. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9039. if zoom:
  9040. self.object_plotted.emit(obj)
  9041. # Send to worker
  9042. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9043. def register_folder(self, filename):
  9044. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9045. def register_save_folder(self, filename):
  9046. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9047. def set_progress_bar(self, percentage, text=""):
  9048. self.ui.progress_bar.setValue(int(percentage))
  9049. def setup_shell(self):
  9050. """
  9051. Creates shell functions. Runs once at startup.
  9052. :return: None
  9053. """
  9054. self.log.debug("setup_shell()")
  9055. def shelp(p=None):
  9056. if not p:
  9057. return _("Available commands:\n") + \
  9058. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9059. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9060. if p not in commands:
  9061. return "Unknown command: %s" % p
  9062. return commands[p]["help"]
  9063. # --- Migrated to new architecture ---
  9064. # def options(name):
  9065. # ops = self.collection.get_by_name(str(name)).options
  9066. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9067. def h(*args):
  9068. """
  9069. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9070. and standalone parameters into list.
  9071. """
  9072. kwa = {}
  9073. a = []
  9074. n = len(args)
  9075. name = None
  9076. for i in range(n):
  9077. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9078. if match:
  9079. assert name is None
  9080. name = match.group(1)
  9081. continue
  9082. if name is None:
  9083. a.append(args[i])
  9084. else:
  9085. kwa[name] = args[i]
  9086. name = None
  9087. return a, kwa
  9088. @contextmanager
  9089. def wait_signal(signal, timeout=10000):
  9090. """
  9091. Block loop until signal emitted, timeout (ms) elapses
  9092. or unhandled exception happens in a thread.
  9093. :param timeout: time after which the loop is exited
  9094. :param signal: Signal to wait for.
  9095. """
  9096. loop = QtCore.QEventLoop()
  9097. # Normal termination
  9098. signal.connect(loop.quit)
  9099. # Termination by exception in thread
  9100. self.thread_exception.connect(loop.quit)
  9101. status = {'timed_out': False}
  9102. def report_quit():
  9103. status['timed_out'] = True
  9104. loop.quit()
  9105. yield
  9106. # Temporarily change how exceptions are managed.
  9107. oeh = sys.excepthook
  9108. ex = []
  9109. def except_hook(type_, value, traceback_):
  9110. ex.append(value)
  9111. oeh(type_, value, traceback_)
  9112. sys.excepthook = except_hook
  9113. # Terminate on timeout
  9114. if timeout is not None:
  9115. QtCore.QTimer.singleShot(timeout, report_quit)
  9116. # # ## Block ## ##
  9117. loop.exec_()
  9118. # Restore exception management
  9119. sys.excepthook = oeh
  9120. if ex:
  9121. self.raiseTclError(str(ex[0]))
  9122. if status['timed_out']:
  9123. raise Exception('Timed out!')
  9124. def make_docs():
  9125. output = ''
  9126. import collections
  9127. od = collections.OrderedDict(sorted(commands.items()))
  9128. for cmd_, val in od.items():
  9129. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9130. t = val['help']
  9131. usage_i = t.find('>')
  9132. if usage_i < 0:
  9133. expl = t
  9134. output += expl + '\n\n'
  9135. continue
  9136. expl = t[:usage_i - 1]
  9137. output += expl + '\n\n'
  9138. end_usage_i = t[usage_i:].find('\n')
  9139. if end_usage_i < 0:
  9140. end_usage_i = len(t[usage_i:])
  9141. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9142. else:
  9143. extras = t[usage_i+end_usage_i+1:]
  9144. parts = [s.strip() for s in extras.split('\n')]
  9145. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9146. for p in parts:
  9147. output += ' ' + p + '\n\n'
  9148. return output
  9149. '''
  9150. Howto implement TCL shell commands:
  9151. All parameters passed to command should be possible to set as None and test it afterwards.
  9152. This is because we need to see error caused in tcl,
  9153. if None value as default parameter is not allowed TCL will return empty error.
  9154. Use:
  9155. def mycommand(name=None,...):
  9156. Test it like this:
  9157. if name is None:
  9158. self.raise_tcl_error('Argument name is missing.')
  9159. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9160. otherwise we will miss it and processing will silently continue.
  9161. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9162. which is catched in exec_command and displayed in TCL shell console with red background.
  9163. Error in console is displayed with TCL trace.
  9164. This behavior works only within main thread,
  9165. errors with promissed tasks can be catched and detected only with log.
  9166. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9167. TCL shell.
  9168. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9169. '''
  9170. commands = {
  9171. 'help': {
  9172. 'fcn': shelp,
  9173. 'help': _("Shows list of commands.")
  9174. },
  9175. }
  9176. # Import/overwrite tcl commands as objects of TclCommand descendants
  9177. # This modifies the variable 'commands'.
  9178. tclCommands.register_all_commands(self, commands)
  9179. # Add commands to the tcl interpreter
  9180. for cmd in commands:
  9181. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9182. # Make the tcl puts function return instead of print to stdout
  9183. self.tcl.eval('''
  9184. rename puts original_puts
  9185. proc puts {args} {
  9186. if {[llength $args] == 1} {
  9187. return "[lindex $args 0]"
  9188. } else {
  9189. eval original_puts $args
  9190. }
  9191. }
  9192. ''')
  9193. def setup_recent_items(self):
  9194. # TODO: Move this to constructor
  9195. icons = {
  9196. "gerber": "share/flatcam_icon16.png",
  9197. "excellon": "share/drill16.png",
  9198. 'geometry': "share/geometry16.png",
  9199. "cncjob": "share/cnc16.png",
  9200. "script": "share/script_new24.png",
  9201. "document": "share/notes16_1.png",
  9202. "project": "share/project16.png",
  9203. "svg": "share/geometry16.png",
  9204. "dxf": "share/dxf16.png",
  9205. "pdf": "share/pdf32.png",
  9206. "image": "share/image16.png"
  9207. }
  9208. openers = {
  9209. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9210. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9211. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9212. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9213. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9214. "document": None,
  9215. 'project': self.open_project,
  9216. 'svg': self.import_svg,
  9217. 'dxf': self.import_dxf,
  9218. 'image': self.import_image,
  9219. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9220. }
  9221. # Open recent file for files
  9222. try:
  9223. f = open(self.data_path + '/recent.json')
  9224. except IOError:
  9225. App.log.error("Failed to load recent item list.")
  9226. self.inform.emit('[ERROR_NOTCL] %s' %
  9227. _("Failed to load recent item list."))
  9228. return
  9229. try:
  9230. self.recent = json.load(f)
  9231. except json.scanner.JSONDecodeError:
  9232. App.log.error("Failed to parse recent item list.")
  9233. self.inform.emit('[ERROR_NOTCL] %s' %
  9234. _("Failed to parse recent item list."))
  9235. f.close()
  9236. return
  9237. f.close()
  9238. # Open recent file for projects
  9239. try:
  9240. fp = open(self.data_path + '/recent_projects.json')
  9241. except IOError:
  9242. App.log.error("Failed to load recent project item list.")
  9243. self.inform.emit('[ERROR_NOTCL] %s' %
  9244. _("Failed to load recent projects item list."))
  9245. return
  9246. try:
  9247. self.recent_projects = json.load(fp)
  9248. except json.scanner.JSONDecodeError:
  9249. App.log.error("Failed to parse recent project item list.")
  9250. self.inform.emit('[ERROR_NOTCL] %s' %
  9251. _("Failed to parse recent project item list."))
  9252. fp.close()
  9253. return
  9254. fp.close()
  9255. # Closure needed to create callbacks in a loop.
  9256. # Otherwise late binding occurs.
  9257. def make_callback(func, fname):
  9258. def opener():
  9259. func(fname)
  9260. return opener
  9261. def reset_recent_files():
  9262. # Reset menu
  9263. self.ui.recent.clear()
  9264. self.recent = []
  9265. try:
  9266. f = open(self.data_path + '/recent.json', 'w')
  9267. except IOError:
  9268. App.log.error("Failed to open recent items file for writing.")
  9269. return
  9270. json.dump(self.recent, f)
  9271. def reset_recent_projects():
  9272. # Reset menu
  9273. self.ui.recent_projects.clear()
  9274. self.recent_projects = []
  9275. try:
  9276. fp = open(self.data_path + '/recent_projects.json', 'w')
  9277. except IOError:
  9278. App.log.error("Failed to open recent projects items file for writing.")
  9279. return
  9280. json.dump(self.recent, fp)
  9281. # Reset menu
  9282. self.ui.recent.clear()
  9283. self.ui.recent_projects.clear()
  9284. # Create menu items for projects
  9285. for recent in self.recent_projects:
  9286. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9287. if recent['kind'] == 'project':
  9288. try:
  9289. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9290. # Attach callback
  9291. o = make_callback(openers[recent["kind"]], recent['filename'])
  9292. action.triggered.connect(o)
  9293. self.ui.recent_projects.addAction(action)
  9294. except KeyError:
  9295. App.log.error("Unsupported file type: %s" % recent["kind"])
  9296. # Last action in Recent Files menu is one that Clear the content
  9297. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9298. clear_action_proj.triggered.connect(reset_recent_projects)
  9299. self.ui.recent_projects.addSeparator()
  9300. self.ui.recent_projects.addAction(clear_action_proj)
  9301. # Create menu items for files
  9302. for recent in self.recent:
  9303. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9304. if recent['kind'] != 'project':
  9305. try:
  9306. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9307. # Attach callback
  9308. o = make_callback(openers[recent["kind"]], recent['filename'])
  9309. action.triggered.connect(o)
  9310. self.ui.recent.addAction(action)
  9311. except KeyError:
  9312. App.log.error("Unsupported file type: %s" % recent["kind"])
  9313. # Last action in Recent Files menu is one that Clear the content
  9314. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9315. clear_action.triggered.connect(reset_recent_files)
  9316. self.ui.recent.addSeparator()
  9317. self.ui.recent.addAction(clear_action)
  9318. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9319. # self.ui.menufilerecent.set_submenu(recent_menu)
  9320. # recent_menu.show_all()
  9321. # self.ui.recent.show()
  9322. self.log.debug("Recent items list has been populated.")
  9323. def setup_component_editor(self):
  9324. # label = QtWidgets.QLabel("Choose an item from Project")
  9325. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9326. sel_title = QtWidgets.QTextEdit(
  9327. _('<b>Shortcut Key List</b>'))
  9328. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9329. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9330. settings = QSettings("Open Source", "FlatCAM")
  9331. if settings.contains("notebook_font_size"):
  9332. fsize = settings.value('notebook_font_size', type=int)
  9333. else:
  9334. fsize = 12
  9335. tsize = fsize + int(fsize / 2)
  9336. # selected_text = (_('''
  9337. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9338. #
  9339. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9340. # The normal flow when working in FlatCAM is the following:</span></p>
  9341. #
  9342. # <ol>
  9343. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9344. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9345. # even dragging and dropping the files on the GUI.<br />
  9346. # <br />
  9347. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9348. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9349. # &nbsp;</li>
  9350. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9351. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9352. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9353. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9354. # <br />
  9355. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9356. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9357. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9358. # it even if it was out of focus.<br />
  9359. # <br />
  9360. # You can change the parameters in this screen and the flow direction is like this:<br />
  9361. # <br />
  9362. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9363. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9364. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9365. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9366. # </ol>
  9367. #
  9368. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9369. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9370. # <strong>F3</strong>.</span></p>
  9371. #
  9372. # ''').format(fsize=fsize, tsize=tsize))
  9373. selected_text = '''
  9374. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9375. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9376. {s1}</span></p>
  9377. <ol>
  9378. <li><span style="font-size:{fsize}px">{s2}<br />
  9379. <br />
  9380. {s3}</span><br />
  9381. &nbsp;</li>
  9382. <li><span style="font-size:{fsize}px">{s4}<br />
  9383. &nbsp;</li>
  9384. <br />
  9385. <li><span style="font-size:{fsize}px">{s5}<br />
  9386. &nbsp;</li>
  9387. <br />
  9388. <li><span style="font-size:{fsize}px">{s6}<br />
  9389. <br />
  9390. {s7}</span></li>
  9391. </ol>
  9392. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9393. '''.format(
  9394. title=_("Selected Tab - Choose an Item from Project Tab"),
  9395. subtitle=_("Details"),
  9396. s1=_("The normal flow when working in FlatCAM is the following:"),
  9397. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9398. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9399. "files on the GUI."),
  9400. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9401. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9402. "actions offered within the app."),
  9403. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9404. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9405. "SELECTED TAB will be updated with the object properties according to its kind: "
  9406. "Gerber, Excellon, Geometry or CNCJob object."),
  9407. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9408. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9409. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9410. "the SELECTED TAB and populate it even if it was out of focus."),
  9411. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9412. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9413. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9414. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9415. "(again, done in SELECTED TAB) --> Save GCode."),
  9416. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9417. "or through its own key shortcut: <b>F3</b>."),
  9418. tsize=tsize,
  9419. fsize=fsize
  9420. )
  9421. sel_title.setText(selected_text)
  9422. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9423. self.ui.selected_scroll_area.setWidget(sel_title)
  9424. def setup_obj_classes(self):
  9425. """
  9426. Sets up application specifics on the FlatCAMObj class.
  9427. :return: None
  9428. """
  9429. FlatCAMObj.app = self
  9430. ObjectCollection.app = self
  9431. Gerber.app = self
  9432. Excellon.app = self
  9433. Geometry.app = self
  9434. CNCjob.app = self
  9435. FCProcess.app = self
  9436. FCProcessContainer.app = self
  9437. def version_check(self):
  9438. """
  9439. Checks for the latest version of the program. Alerts the
  9440. user if theirs is outdated. This method is meant to be run
  9441. in a separate thread.
  9442. :return: None
  9443. """
  9444. self.log.debug("version_check()")
  9445. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9446. full_url = App.version_url + \
  9447. "?s=" + str(self.defaults['global_serial']) + \
  9448. "&v=" + str(self.version) + \
  9449. "&os=" + str(self.os) + \
  9450. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9451. else:
  9452. # no_stats dict; just so it won't break things on website
  9453. no_ststs_dict = {}
  9454. no_ststs_dict["global_ststs"] = {}
  9455. full_url = App.version_url + \
  9456. "?s=" + str(self.defaults['global_serial']) + \
  9457. "&v=" + str(self.version) + \
  9458. "&os=" + str(self.os) + \
  9459. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9460. App.log.debug("Checking for updates @ %s" % full_url)
  9461. # ## Get the data
  9462. try:
  9463. f = urllib.request.urlopen(full_url)
  9464. except:
  9465. # App.log.warning("Failed checking for latest version. Could not connect.")
  9466. self.log.warning("Failed checking for latest version. Could not connect.")
  9467. self.inform.emit('[WARNING_NOTCL] %s' %
  9468. _("Failed checking for latest version. Could not connect."))
  9469. return
  9470. try:
  9471. data = json.load(f)
  9472. except Exception as e:
  9473. App.log.error("Could not parse information about latest version.")
  9474. self.inform.emit('[ERROR_NOTCL] %s' %
  9475. _("Could not parse information about latest version."))
  9476. App.log.debug("json.load(): %s" % str(e))
  9477. f.close()
  9478. return
  9479. f.close()
  9480. # ## Latest version?
  9481. if self.version >= data["version"]:
  9482. App.log.debug("FlatCAM is up to date!")
  9483. self.inform.emit('[success] %s' %
  9484. _("FlatCAM is up to date!"))
  9485. return
  9486. App.log.debug("Newer version available.")
  9487. self.message.emit(
  9488. _("Newer Version Available"),
  9489. _("There is a newer version of FlatCAM available for download:\n\n") +
  9490. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9491. _("info")
  9492. )
  9493. def on_plotcanvas_setup(self, container=None):
  9494. """
  9495. This is doing the setup for the plot area (VisPy canvas)
  9496. :param container: widget where to install the canvas
  9497. :return: None
  9498. """
  9499. if container:
  9500. plot_container = container
  9501. else:
  9502. plot_container = self.ui.right_layout
  9503. if self.is_legacy is False:
  9504. self.plotcanvas = PlotCanvas(plot_container, self)
  9505. else:
  9506. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9507. # So it can receive key presses
  9508. self.plotcanvas.native.setFocus()
  9509. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9510. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9511. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9512. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_double_click_over_plot)
  9513. # Keys over plot enabled
  9514. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9515. if self.defaults['global_cursor_type'] == 'small':
  9516. self.app_cursor = self.plotcanvas.new_cursor()
  9517. else:
  9518. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9519. if self.ui.grid_snap_btn.isChecked():
  9520. self.app_cursor.enabled = True
  9521. else:
  9522. self.app_cursor.enabled = False
  9523. if self.is_legacy is False:
  9524. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9525. else:
  9526. # will use the default Matplotlib axes
  9527. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9528. def on_zoom_fit(self, event):
  9529. """
  9530. Callback for zoom-out request. This can be either from the corresponding
  9531. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9532. with axes limits from the geometry bounds of all objects.
  9533. :param event: Ignored.
  9534. :return: None
  9535. """
  9536. if self.is_legacy is False:
  9537. self.plotcanvas.fit_view()
  9538. else:
  9539. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9540. width = xmax - xmin
  9541. height = ymax - ymin
  9542. xmin -= 0.05 * width
  9543. xmax += 0.05 * width
  9544. ymin -= 0.05 * height
  9545. ymax += 0.05 * height
  9546. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9547. def on_zoom_in(self):
  9548. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9549. def on_zoom_out(self):
  9550. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9551. def disable_all_plots(self):
  9552. self.report_usage("disable_all_plots()")
  9553. self.disable_plots(self.collection.get_list())
  9554. self.inform.emit('[success] %s' %
  9555. _("All plots disabled."))
  9556. def disable_other_plots(self):
  9557. self.report_usage("disable_other_plots()")
  9558. self.disable_plots(self.collection.get_non_selected())
  9559. self.inform.emit('[success] %s' %
  9560. _("All non selected plots disabled."))
  9561. def enable_all_plots(self):
  9562. self.report_usage("enable_all_plots()")
  9563. self.enable_plots(self.collection.get_list())
  9564. self.inform.emit('[success] %s' %
  9565. _("All plots enabled."))
  9566. def on_enable_sel_plots(self):
  9567. log.debug("App.on_enable_sel_plot()")
  9568. object_list = self.collection.get_selected()
  9569. self.enable_plots(objects=object_list)
  9570. self.inform.emit('[success] %s' %
  9571. _("Selected plots enabled..."))
  9572. def on_disable_sel_plots(self):
  9573. log.debug("App.on_disable_sel_plot()")
  9574. # self.inform.emit(_("Disabling plots ..."))
  9575. object_list = self.collection.get_selected()
  9576. self.disable_plots(objects=object_list)
  9577. self.inform.emit('[success] %s' %
  9578. _("Selected plots disabled..."))
  9579. def enable_plots(self, objects):
  9580. """
  9581. Disables plots
  9582. :param objects: list of Objects to be enabled
  9583. :return:
  9584. """
  9585. log.debug("Enabling plots ...")
  9586. # self.inform.emit(_("Working ..."))
  9587. for obj in objects:
  9588. if obj.options['plot'] is False:
  9589. obj.options.set_change_callback(lambda x: None)
  9590. obj.options['plot'] = True
  9591. obj.options.set_change_callback(obj.on_options_change)
  9592. def worker_task(objects):
  9593. with self.proc_container.new(_("Enabling plots ...")):
  9594. for obj in objects:
  9595. # obj.options['plot'] = True
  9596. if isinstance(obj, FlatCAMCNCjob):
  9597. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9598. else:
  9599. obj.plot(visible=True)
  9600. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9601. # self.plots_updated.emit()
  9602. def disable_plots(self, objects):
  9603. """
  9604. Disables plots
  9605. :param objects: list of Objects to be disabled
  9606. :return:
  9607. """
  9608. # if no objects selected then do nothing
  9609. if not self.collection.get_selected():
  9610. return
  9611. log.debug("Disabling plots ...")
  9612. # self.inform.emit(_("Working ..."))
  9613. for obj in objects:
  9614. if obj.options['plot'] is True:
  9615. obj.options.set_change_callback(lambda x: None)
  9616. obj.options['plot'] = False
  9617. obj.options.set_change_callback(obj.on_options_change)
  9618. try:
  9619. self.delete_selection_shape()
  9620. except Exception as e:
  9621. log.debug("App.disable_plots() --> %s" % str(e))
  9622. # self.plots_updated.emit()
  9623. def worker_task(objects):
  9624. with self.proc_container.new(_("Disabling plots ...")):
  9625. for obj in objects:
  9626. # obj.options['plot'] = True
  9627. if isinstance(obj, FlatCAMCNCjob):
  9628. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9629. else:
  9630. obj.plot(visible=False)
  9631. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9632. def toggle_plots(self, objects):
  9633. """
  9634. Toggle plots visibility
  9635. :param objects: list of Objects for which to be toggled the visibility
  9636. :return:
  9637. """
  9638. # if no objects selected then do nothing
  9639. if not self.collection.get_selected():
  9640. return
  9641. log.debug("Toggling plots ...")
  9642. self.inform.emit(_("Working ..."))
  9643. for obj in objects:
  9644. if obj.options['plot'] is False:
  9645. obj.options['plot'] = True
  9646. else:
  9647. obj.options['plot'] = False
  9648. self.plots_updated.emit()
  9649. def clear_plots(self):
  9650. objects = self.collection.get_list()
  9651. for obj in objects:
  9652. obj.clear(obj == objects[-1])
  9653. # Clear pool to free memory
  9654. self.clear_pool()
  9655. def generate_cnc_job(self, objects):
  9656. self.report_usage("generate_cnc_job()")
  9657. # for obj in objects:
  9658. # obj.generatecncjob()
  9659. for obj in objects:
  9660. obj.on_generatecnc_button_click()
  9661. def save_project(self, filename, quit_action=False, silent=False):
  9662. """
  9663. Saves the current project to the specified file.
  9664. :param filename: Name of the file in which to save.
  9665. :type filename: str
  9666. :param quit_action: if the project saving will be followed by an app quit; boolean
  9667. :param silent: if True will not display status messages
  9668. :return: None
  9669. """
  9670. self.log.debug("save_project()")
  9671. self.save_in_progress = True
  9672. with self.proc_container.new(_("Saving FlatCAM Project")):
  9673. # Capture the latest changes
  9674. # Current object
  9675. try:
  9676. self.collection.get_active().read_form()
  9677. except:
  9678. self.log.debug("There was no active object")
  9679. pass
  9680. # Project options
  9681. self.options_read_form()
  9682. # Serialize the whole project
  9683. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9684. "options": self.options,
  9685. "version": self.version}
  9686. if self.defaults["global_save_compressed"] is True:
  9687. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9688. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9689. # # Write
  9690. f.write(g)
  9691. self.inform.emit('[success] %s: %s' %
  9692. (_("Project saved to"), filename))
  9693. else:
  9694. # Open file
  9695. try:
  9696. f = open(filename, 'w')
  9697. except IOError:
  9698. App.log.error("Failed to open file for saving: %s", filename)
  9699. return
  9700. # Write
  9701. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9702. f.close()
  9703. # verification of the saved project
  9704. # Open and parse
  9705. try:
  9706. saved_f = open(filename, 'r')
  9707. except IOError:
  9708. if silent is False:
  9709. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9710. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9711. )
  9712. return
  9713. try:
  9714. saved_d = json.load(saved_f, object_hook=dict2obj)
  9715. except:
  9716. if silent is False:
  9717. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9718. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9719. )
  9720. f.close()
  9721. return
  9722. saved_f.close()
  9723. if silent is False:
  9724. if 'version' in saved_d:
  9725. self.inform.emit('[success] %s: %s' %
  9726. (_("Project saved to"), filename))
  9727. else:
  9728. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9729. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9730. )
  9731. settings = QSettings("Open Source", "FlatCAM")
  9732. lock_state = self.ui.lock_action.isChecked()
  9733. settings.setValue('toolbar_lock', lock_state)
  9734. # This will write the setting to the platform specific storage.
  9735. del settings
  9736. # if quit:
  9737. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9738. # t.start()
  9739. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9740. def start_delayed_quit(self, delay, filename, should_quit=None):
  9741. """
  9742. :param delay: period of checking if project file size is more than zero; in seconds
  9743. :param filename: the name of the project file to be checked periodically for size more than zero
  9744. :param should_quit: if the task finished will be followed by an app quit; boolean
  9745. :return:
  9746. """
  9747. to_quit = should_quit
  9748. self.save_timer = QtCore.QTimer()
  9749. self.save_timer.setInterval(delay)
  9750. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9751. self.save_timer.start()
  9752. def check_project_file_size(self, filename, should_quit=None):
  9753. """
  9754. :param filename: the name of the project file to be checked periodically for size more than zero
  9755. :param should_quit: will quit the app if True; boolean
  9756. :return:
  9757. """
  9758. try:
  9759. if os.stat(filename).st_size > 0:
  9760. self.save_in_progress = False
  9761. self.save_timer.stop()
  9762. if should_quit:
  9763. self.app_quit.emit()
  9764. except Exception as e:
  9765. traceback.print_exc()
  9766. def on_options_app2project(self):
  9767. """
  9768. Callback for Options->Transfer Options->App=>Project. Copies options
  9769. from application defaults to project defaults.
  9770. :return: None
  9771. """
  9772. self.report_usage("on_options_app2project")
  9773. self.defaults_read_form()
  9774. self.options.update(self.defaults)
  9775. self.options_write_form()
  9776. def on_options_project2app(self):
  9777. """
  9778. Callback for Options->Transfer Options->Project=>App. Copies options
  9779. from project defaults to application defaults.
  9780. :return: None
  9781. """
  9782. self.report_usage("on_options_project2app")
  9783. self.options_read_form()
  9784. self.defaults.update(self.options)
  9785. self.defaults_write_form()
  9786. def on_options_project2object(self):
  9787. """
  9788. Callback for Options->Transfer Options->Project=>Object. Copies options
  9789. from project defaults to the currently selected object.
  9790. :return: None
  9791. """
  9792. self.report_usage("on_options_project2object")
  9793. self.options_read_form()
  9794. obj = self.collection.get_active()
  9795. if obj is None:
  9796. self.inform.emit('[WARNING_NOTCL] %s' %
  9797. _("No object selected."))
  9798. return
  9799. for option in self.options:
  9800. if option.find(obj.kind + "_") == 0:
  9801. oname = option[len(obj.kind) + 1:]
  9802. obj.options[oname] = self.options[option]
  9803. obj.to_form() # Update UI
  9804. def on_options_object2project(self):
  9805. """
  9806. Callback for Options->Transfer Options->Object=>Project. Copies options
  9807. from the currently selected object to project defaults.
  9808. :return: None
  9809. """
  9810. self.report_usage("on_options_object2project")
  9811. obj = self.collection.get_active()
  9812. if obj is None:
  9813. self.inform.emit('[WARNING_NOTCL] %s' %
  9814. _("No object selected."))
  9815. return
  9816. obj.read_form()
  9817. for option in obj.options:
  9818. if option in ['name']: # TODO: Handle this better...
  9819. continue
  9820. self.options[obj.kind + "_" + option] = obj.options[option]
  9821. self.options_write_form()
  9822. def on_options_object2app(self):
  9823. """
  9824. Callback for Options->Transfer Options->Object=>App. Copies options
  9825. from the currently selected object to application defaults.
  9826. :return: None
  9827. """
  9828. self.report_usage("on_options_object2app")
  9829. obj = self.collection.get_active()
  9830. if obj is None:
  9831. self.inform.emit('[WARNING_NOTCL] %s' %
  9832. _("No object selected."))
  9833. return
  9834. obj.read_form()
  9835. for option in obj.options:
  9836. if option in ['name']: # TODO: Handle this better...
  9837. continue
  9838. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9839. self.defaults_write_form()
  9840. def on_options_app2object(self):
  9841. """
  9842. Callback for Options->Transfer Options->App=>Object. Copies options
  9843. from application defaults to the currently selected object.
  9844. :return: None
  9845. """
  9846. self.report_usage("on_options_app2object")
  9847. self.defaults_read_form()
  9848. obj = self.collection.get_active()
  9849. if obj is None:
  9850. self.inform.emit('[WARNING_NOTCL] %s' %
  9851. _("No object selected."))
  9852. return
  9853. for option in self.defaults:
  9854. if option.find(obj.kind + "_") == 0:
  9855. oname = option[len(obj.kind) + 1:]
  9856. obj.options[oname] = self.defaults[option]
  9857. obj.to_form() # Update UI
  9858. class ArgsThread(QtCore.QObject):
  9859. open_signal = pyqtSignal(list)
  9860. start = pyqtSignal()
  9861. if sys.platform == 'win32':
  9862. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9863. else:
  9864. address = ('/tmp/testipc', 'AF_UNIX')
  9865. def __init__(self):
  9866. super(ArgsThread, self).__init__()
  9867. self.start.connect(self.run)
  9868. def my_loop(self, address):
  9869. try:
  9870. listener = Listener(*address)
  9871. while True:
  9872. conn = listener.accept()
  9873. self.serve(conn)
  9874. except socket.error as e:
  9875. conn = Client(*address)
  9876. conn.send(sys.argv)
  9877. conn.send('close')
  9878. # close the current instance only if there are args
  9879. if len(sys.argv) > 1:
  9880. sys.exit()
  9881. def serve(self, conn):
  9882. while True:
  9883. msg = conn.recv()
  9884. if msg == 'close':
  9885. break
  9886. self.open_signal.emit(msg)
  9887. conn.close()
  9888. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9889. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9890. @pyqtSlot()
  9891. def run(self):
  9892. self.my_loop(self.address)
  9893. class GracefulException(Exception):
  9894. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9895. def __init__(self):
  9896. super().__init__()
  9897. def __str__(self):
  9898. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  9899. # end of file