FlatCAMApp.py 547 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174
  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 webbrowser
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import lzma
  16. import threading
  17. import shutil
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import subprocess
  20. import ctypes
  21. import tkinter as tk
  22. from PyQt5 import QtPrintSupport
  23. from contextlib import contextmanager
  24. import gc
  25. from xml.dom.minidom import parseString as parse_xml_string
  26. from multiprocessing.connection import Listener, Client
  27. from multiprocessing import Pool, cpu_count
  28. import socket
  29. from array import array
  30. import vispy.scene as scene
  31. # #######################################
  32. # # Imports part of FlatCAM ##
  33. # #######################################
  34. from ObjectCollection import *
  35. from FlatCAMObj import *
  36. from camlib import to_dict, dict2obj, ET, ParseError
  37. from flatcamGUI.PlotCanvas import *
  38. from flatcamGUI.PlotCanvasLegacy import *
  39. from flatcamGUI.FlatCAMGUI import *
  40. from FlatCAMCommon import LoudDict, BookmarkManager, ToolsDB
  41. from FlatCAMPostProc import load_postprocessors
  42. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  43. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  44. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  45. from flatcamEditors.FlatCAMTextEditor import TextEditor
  46. from FlatCAMProcess import *
  47. from FlatCAMWorkerStack import WorkerStack
  48. # from flatcamGUI.VisPyVisuals import Color
  49. from vispy.gloo.util import _screenshot
  50. from vispy.io import write_png
  51. from flatcamTools import *
  52. import tclCommands
  53. import gettext
  54. import FlatCAMTranslation as fcTranslate
  55. import builtins
  56. if sys.platform == 'win32':
  57. import winreg
  58. fcTranslate.apply_language('strings')
  59. if '_' not in builtins.__dict__:
  60. _ = gettext.gettext
  61. class App(QtCore.QObject):
  62. # ########################################
  63. # # App ###
  64. # ########################################
  65. """
  66. The main application class. The constructor starts the GUI.
  67. """
  68. # Get Cmd Line Options
  69. cmd_line_shellfile = ''
  70. cmd_line_shellvar = ''
  71. cmd_line_headless = None
  72. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  73. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  74. "FlatCam.py --headless=1"
  75. try:
  76. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  77. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  78. "shellvar=",
  79. "headless=",
  80. "multiprocessing-fork="])
  81. except getopt.GetoptError:
  82. print(cmd_line_help)
  83. sys.exit(2)
  84. for opt, arg in cmd_line_options:
  85. if opt == '-h':
  86. print(cmd_line_help)
  87. sys.exit()
  88. elif opt == '--shellfile':
  89. cmd_line_shellfile = arg
  90. elif opt == '--shellvar':
  91. cmd_line_shellvar = arg
  92. elif opt == '--headless':
  93. try:
  94. cmd_line_headless = eval(arg)
  95. except NameError:
  96. pass
  97. # ## Logging ###
  98. log = logging.getLogger('base')
  99. log.setLevel(logging.DEBUG)
  100. # log.setLevel(logging.WARNING)
  101. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  102. handler = logging.StreamHandler()
  103. handler.setFormatter(formatter)
  104. log.addHandler(handler)
  105. # ##########################################################################
  106. # ################## Version and VERSION DATE ##############################
  107. # ##########################################################################
  108. version = 8.99
  109. version_date = "2019/11/16"
  110. beta = True
  111. engine = '3D'
  112. # current date now
  113. date = str(datetime.today()).rpartition('.')[0]
  114. date = ''.join(c for c in date if c not in ':-')
  115. date = date.replace(' ', '_')
  116. # URL for update checks and statistics
  117. version_url = "http://flatcam.org/version"
  118. # App URL
  119. app_url = "http://flatcam.org"
  120. # Manual URL
  121. manual_url = "http://flatcam.org/manual/index.html"
  122. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  123. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  124. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  125. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  126. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  127. # this variable will hold the project status
  128. # if True it will mean that the project was modified and not saved
  129. should_we_save = False
  130. # flag is True if saving action has been triggered
  131. save_in_progress = False
  132. # ###########################################################################
  133. # ############################# Signals ################################
  134. # ###########################################################################
  135. # Inform the user
  136. # Handled by:
  137. # * App.info() --> Print on the status bar
  138. inform = QtCore.pyqtSignal(str)
  139. app_quit = QtCore.pyqtSignal()
  140. # General purpose background task
  141. worker_task = QtCore.pyqtSignal(dict)
  142. # File opened
  143. # Handled by:
  144. # * register_folder()
  145. # * register_recent()
  146. # Note: Setting the parameters to unicode does not seem
  147. # to have an effect. Then are received as Qstring
  148. # anyway.
  149. # File type and filename
  150. file_opened = QtCore.pyqtSignal(str, str)
  151. # File type and filename
  152. file_saved = QtCore.pyqtSignal(str, str)
  153. # Percentage of progress
  154. progress = QtCore.pyqtSignal(int)
  155. plots_updated = QtCore.pyqtSignal()
  156. # Emitted by new_object() and passes the new object as argument, plot flag.
  157. # on_object_created() adds the object to the collection, plots on appropriate flag
  158. # and emits new_object_available.
  159. object_created = QtCore.pyqtSignal(object, bool, bool)
  160. # Emitted when a object has been changed (like scaled, mirrored)
  161. object_changed = QtCore.pyqtSignal(object)
  162. # Emitted after object has been plotted.
  163. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  164. object_plotted = QtCore.pyqtSignal(object)
  165. # Emitted when a new object has been added or deleted from/to the collection
  166. object_status_changed = QtCore.pyqtSignal(object, str, str)
  167. message = QtCore.pyqtSignal(str, str, str)
  168. # Emmited when shell command is finished(one command only)
  169. shell_command_finished = QtCore.pyqtSignal(object)
  170. # Emitted when multiprocess pool has been recreated
  171. pool_recreated = QtCore.pyqtSignal(object)
  172. # Emitted when an unhandled exception happens
  173. # in the worker task.
  174. thread_exception = QtCore.pyqtSignal(object)
  175. # used to signal that there are arguments for the app
  176. args_at_startup = QtCore.pyqtSignal(list)
  177. # a reusable signal to replot a list of objects
  178. # should be disconnected after use so it can be reused
  179. replot_signal = pyqtSignal(list)
  180. def __init__(self, user_defaults=True):
  181. """
  182. Starts the application.
  183. :return: app
  184. :rtype: App
  185. """
  186. App.log.info("FlatCAM Starting...")
  187. self.main_thread = QtWidgets.QApplication.instance().thread()
  188. # ############################################################################
  189. # # ################# OS-specific ############################################
  190. # ############################################################################
  191. portable = False
  192. # Folder for user settings.
  193. if sys.platform == 'win32':
  194. # #########################################################################
  195. # Setup the listening thread for another instance launching with args #####
  196. # #########################################################################
  197. # make sure the thread is stored by using a self. otherwise it's garbage collected
  198. self.th = QtCore.QThread()
  199. self.th.start(priority=QtCore.QThread.LowestPriority)
  200. self.new_launch = ArgsThread()
  201. self.new_launch.open_signal[list].connect(self.on_startup_args)
  202. self.new_launch.moveToThread(self.th)
  203. self.new_launch.start.emit()
  204. from win32com.shell import shell, shellcon
  205. if platform.architecture()[0] == '32bit':
  206. App.log.debug("Win32!")
  207. else:
  208. App.log.debug("Win64!")
  209. # #########################################################################
  210. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  211. # #########################################################################
  212. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  213. try:
  214. with open(config_file, 'r'):
  215. pass
  216. except FileNotFoundError:
  217. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  218. try:
  219. with open(config_file, 'r') as f:
  220. try:
  221. for line in f:
  222. param = str(line).replace('\n', '').rpartition('=')
  223. if param[0] == 'portable':
  224. try:
  225. portable = eval(param[2])
  226. except NameError:
  227. portable = False
  228. if param[0] == 'headless':
  229. if param[2].lower() == 'true':
  230. self.cmd_line_headless = 1
  231. else:
  232. self.cmd_line_headless = None
  233. except Exception as e:
  234. log.debug('App.__init__() -->%s' % str(e))
  235. return
  236. except FileNotFoundError as e:
  237. log.debug(str(e))
  238. pass
  239. if portable is False:
  240. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  241. else:
  242. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  243. self.os = 'windows'
  244. else: # Linux/Unix/MacOS
  245. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  246. self.os = 'unix'
  247. # ##########################################################################
  248. # ################## Setup folders and files ###############################
  249. # ##########################################################################
  250. if not os.path.exists(self.data_path):
  251. os.makedirs(self.data_path)
  252. App.log.debug('Created data folder: ' + self.data_path)
  253. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  254. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  255. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  256. if not os.path.exists(self.postprocessorpaths):
  257. os.makedirs(self.postprocessorpaths)
  258. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  259. # create tools_db.FlatConfig file if there is none
  260. try:
  261. f = open(self.data_path + '/tools_db.FlatConfig')
  262. f.close()
  263. except IOError:
  264. App.log.debug('Creating empty tool_db.FlatConfig')
  265. f = open(self.data_path + '/tools_db.FlatConfig', 'w')
  266. json.dump({}, f)
  267. f.close()
  268. # create current_defaults.FlatConfig file if there is none
  269. try:
  270. f = open(self.data_path + '/current_defaults.FlatConfig')
  271. f.close()
  272. except IOError:
  273. App.log.debug('Creating empty current_defaults.FlatConfig')
  274. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  275. json.dump({}, f)
  276. f.close()
  277. # create factory_defaults.FlatConfig file if there is none
  278. try:
  279. f = open(self.data_path + '/factory_defaults.FlatConfig')
  280. f.close()
  281. except IOError:
  282. App.log.debug('Creating empty factory_defaults.FlatConfig')
  283. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  284. json.dump({}, f)
  285. f.close()
  286. # create a recent files json file if there is none
  287. try:
  288. f = open(self.data_path + '/recent.json')
  289. f.close()
  290. except IOError:
  291. App.log.debug('Creating empty recent.json')
  292. f = open(self.data_path + '/recent.json', 'w')
  293. json.dump([], f)
  294. f.close()
  295. # create a recent projects json file if there is none
  296. try:
  297. fp = open(self.data_path + '/recent_projects.json')
  298. fp.close()
  299. except IOError:
  300. App.log.debug('Creating empty recent_projects.json')
  301. fp = open(self.data_path + '/recent_projects.json', 'w')
  302. json.dump([], fp)
  303. fp.close()
  304. # Application directory. CHDIR to it. Otherwise, trying to load
  305. # GUI icons will fail as their path is relative.
  306. # This will fail under cx_freeze ...
  307. self.app_home = os.path.dirname(os.path.realpath(__file__))
  308. App.log.debug("Application path is " + self.app_home)
  309. App.log.debug("Started in " + os.getcwd())
  310. # cx_freeze workaround
  311. if os.path.isfile(self.app_home):
  312. self.app_home = os.path.dirname(self.app_home)
  313. os.chdir(self.app_home)
  314. # #################################################################################
  315. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  316. # #################################################################################
  317. self.defaults = LoudDict()
  318. self.defaults.update({
  319. # Global APP Preferences
  320. "first_run": True,
  321. "units": "IN",
  322. "global_serial": 0,
  323. "global_stats": {},
  324. "global_tabs_detachable": True,
  325. "global_graphic_engine": '3D',
  326. "global_app_level": 'b',
  327. "global_portable": False,
  328. "global_language": 'English',
  329. "global_version_check": True,
  330. "global_send_stats": True,
  331. "global_pan_button": '2',
  332. "global_mselect_key": 'Control',
  333. "global_project_at_startup": False,
  334. "global_systray_icon": True,
  335. "global_project_autohide": True,
  336. "global_toggle_tooltips": True,
  337. "global_worker_number": 2,
  338. "global_tolerance": 0.0002,
  339. "global_open_style": True,
  340. "global_delete_confirmation": True,
  341. "global_compression_level": 3,
  342. "global_save_compressed": True,
  343. "global_machinist_setting": False,
  344. # Global GUI Preferences
  345. "global_gridx": 0.0393701,
  346. "global_gridy": 0.0393701,
  347. "global_snap_max": 0.001968504,
  348. "global_workspace": False,
  349. "global_workspaceT": "A4P",
  350. "global_grid_context_menu": {
  351. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  352. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  353. },
  354. "global_plot_fill": '#BBF268BF',
  355. "global_plot_line": '#006E20BF',
  356. "global_sel_fill": '#a5a5ffbf',
  357. "global_sel_line": '#0000ffbf',
  358. "global_alt_sel_fill": '#BBF268BF',
  359. "global_alt_sel_line": '#006E20BF',
  360. "global_draw_color": '#FF0000',
  361. "global_sel_draw_color": '#0000FF',
  362. "global_proj_item_color": '#000000',
  363. "global_proj_item_dis_color": '#b7b7cb',
  364. "global_activity_icon": 'Ball green',
  365. "global_toolbar_view": 511,
  366. "global_background_timeout": 300000, # Default value is 5 minutes
  367. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  368. # (python trace only for unknown errors),
  369. # 1 = show trace(show trace always),
  370. # 2 = (For the future).
  371. # Persistence
  372. "global_last_folder": None,
  373. "global_last_save_folder": None,
  374. # Default window geometry
  375. "global_def_win_x": 100,
  376. "global_def_win_y": 100,
  377. "global_def_win_w": 1024,
  378. "global_def_win_h": 650,
  379. "global_def_notebook_width": 1,
  380. # Constants...
  381. "global_defaults_save_period_ms": 20000, # Time between default saves.
  382. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  383. "global_shell_at_startup": False, # Show the shell at startup.
  384. "global_recent_limit": 10, # Max. items in recent list.
  385. "global_bookmarks": dict(),
  386. "global_bookmarks_limit": 10,
  387. "fit_key": 'V',
  388. "zoom_out_key": '-',
  389. "zoom_in_key": '=',
  390. "grid_toggle_key": 'G',
  391. "global_zoom_ratio": 1.5,
  392. "global_point_clipboard_format": "(%.4f, %.4f)",
  393. "global_zdownrate": None,
  394. # General GUI Settings
  395. "global_theme": 'white',
  396. "global_hover": False,
  397. "global_selection_shape": True,
  398. "global_layout": "compact",
  399. "global_cursor_type": "small",
  400. "global_cursor_size": 20,
  401. # Gerber General
  402. "gerber_plot": True,
  403. "gerber_solid": True,
  404. "gerber_multicolored": False,
  405. "gerber_circle_steps": 128,
  406. "gerber_use_buffer_for_union": True,
  407. "gerber_def_units": 'IN',
  408. "gerber_def_zeros": 'L',
  409. # Gerber Options
  410. "gerber_isotooldia": 0.00787402,
  411. "gerber_isopasses": 1,
  412. "gerber_isooverlap": 0.00393701,
  413. "gerber_milling_type": "cl",
  414. "gerber_combine_passes": False,
  415. "gerber_noncoppermargin": 0.00393701,
  416. "gerber_noncopperrounded": False,
  417. "gerber_bboxmargin": 0.00393701,
  418. "gerber_bboxrounded": False,
  419. # Gerber Advanced Options
  420. "gerber_aperture_display": False,
  421. "gerber_aperture_scale_factor": 1.0,
  422. "gerber_aperture_buffer_factor": 0.0,
  423. "gerber_follow": False,
  424. "gerber_tool_type": 'circular',
  425. "gerber_vtipdia": 0.1,
  426. "gerber_vtipangle": 30,
  427. "gerber_vcutz": -0.05,
  428. "gerber_buffering": "full",
  429. "gerber_simplification": False,
  430. "gerber_simp_tolerance": 0.0005,
  431. # Gerber Export
  432. "gerber_exp_units": 'IN',
  433. "gerber_exp_integer": 2,
  434. "gerber_exp_decimals": 4,
  435. "gerber_exp_zeros": 'L',
  436. # Gerber Editor
  437. "gerber_editor_sel_limit": 30,
  438. "gerber_editor_newcode": 10,
  439. "gerber_editor_newsize": 0.031496,
  440. "gerber_editor_newtype": 'C',
  441. "gerber_editor_newdim": "0.5, 0.5",
  442. "gerber_editor_array_size": 5,
  443. "gerber_editor_lin_axis": 'X',
  444. "gerber_editor_lin_pitch": 1,
  445. "gerber_editor_lin_angle": 0.0,
  446. "gerber_editor_circ_dir": 'CW',
  447. "gerber_editor_circ_angle": 0.0,
  448. "gerber_editor_scale_f": 1.0,
  449. "gerber_editor_buff_f": 0.01,
  450. "gerber_editor_ma_low": 0.0,
  451. "gerber_editor_ma_high": 1.0,
  452. # Excellon General
  453. "excellon_plot": True,
  454. "excellon_solid": True,
  455. "excellon_format_upper_in": 2,
  456. "excellon_format_lower_in": 4,
  457. "excellon_format_upper_mm": 3,
  458. "excellon_format_lower_mm": 3,
  459. "excellon_zeros": "L",
  460. "excellon_units": "INCH",
  461. "excellon_update": True,
  462. "excellon_optimization_type": 'B',
  463. "excellon_search_time": 3,
  464. # Excellon Options
  465. "excellon_drillz": -0.0590551,
  466. "excellon_travelz": 0.0787402,
  467. "excellon_endz": 0.5,
  468. "excellon_feedrate": 3.14961,
  469. "excellon_spindlespeed": None,
  470. "excellon_dwell": False,
  471. "excellon_dwelltime": 1,
  472. "excellon_toolchange": False,
  473. "excellon_toolchangez": 0.5,
  474. "excellon_ppname_e": 'default',
  475. "excellon_tooldia": 0.0314961,
  476. "excellon_slot_tooldia": 0.0708661,
  477. "excellon_gcode_type": "drills",
  478. # Excellon Advanced Options
  479. "excellon_offset": 0.0,
  480. "excellon_toolchangexy": "0.0, 0.0",
  481. "excellon_startz": None,
  482. "excellon_feedrate_rapid": 31.4961,
  483. "excellon_z_pdepth": -0.02,
  484. "excellon_feedrate_probe": 3.14961,
  485. "excellon_spindledir": 'CW',
  486. "excellon_f_plunge": False,
  487. "excellon_f_retract": False,
  488. # Excellon Export
  489. "excellon_exp_units": 'INCH',
  490. "excellon_exp_format": 'ndec',
  491. "excellon_exp_integer": 2,
  492. "excellon_exp_decimals": 4,
  493. "excellon_exp_zeros": 'LZ',
  494. "excellon_exp_slot_type": 'routing',
  495. # Excellon Editor
  496. "excellon_editor_sel_limit": 30,
  497. "excellon_editor_newdia": 0.039,
  498. "excellon_editor_array_size": 5,
  499. "excellon_editor_lin_dir": 'X',
  500. "excellon_editor_lin_pitch": 0.1,
  501. "excellon_editor_lin_angle": 0.0,
  502. "excellon_editor_circ_dir": 'CW',
  503. "excellon_editor_circ_angle": 12,
  504. # Excellon Slots
  505. "excellon_editor_slot_direction": 'X',
  506. "excellon_editor_slot_angle": 0.0,
  507. "excellon_editor_slot_length": 5.0,
  508. # Excellon Slot Array
  509. "excellon_editor_slot_array_size": 5,
  510. "excellon_editor_slot_lin_dir": 'X',
  511. "excellon_editor_slot_lin_pitch": 0.1,
  512. "excellon_editor_slot_lin_angle": 0.0,
  513. "excellon_editor_slot_circ_dir": 'CW',
  514. "excellon_editor_slot_circ_angle": 0.0,
  515. # Geometry General
  516. "geometry_plot": True,
  517. "geometry_circle_steps": 128,
  518. "geometry_cnctooldia": "0.0944882",
  519. # Geometry Options
  520. "geometry_cutz": -0.0944882,
  521. "geometry_vtipdia": 0.1,
  522. "geometry_vtipangle": 30,
  523. "geometry_multidepth": False,
  524. "geometry_depthperpass": 0.0314961,
  525. "geometry_travelz": 0.0787402,
  526. "geometry_toolchange": False,
  527. "geometry_toolchangez": 0.5,
  528. "geometry_endz": 0.5,
  529. "geometry_feedrate": 3.14961,
  530. "geometry_feedrate_z": 3.14961,
  531. "geometry_spindlespeed": None,
  532. "geometry_dwell": False,
  533. "geometry_dwelltime": 1,
  534. "geometry_ppname_g": 'default',
  535. # Geometry Advanced Options
  536. "geometry_toolchangexy": "0.0, 0.0",
  537. "geometry_startz": None,
  538. "geometry_feedrate_rapid": 3.14961,
  539. "geometry_extracut": False,
  540. "geometry_z_pdepth": -0.02,
  541. "geometry_f_plunge": False,
  542. "geometry_spindledir": 'CW',
  543. "geometry_feedrate_probe": 3.14961,
  544. "geometry_segx": 0.0,
  545. "geometry_segy": 0.0,
  546. # Geometry Editor
  547. "geometry_editor_sel_limit": 30,
  548. "geometry_editor_milling_type": "cl",
  549. # CNC Job General
  550. "cncjob_plot": True,
  551. "cncjob_plot_kind": 'all',
  552. "cncjob_annotation": True,
  553. "cncjob_tooldia": 0.0393701,
  554. "cncjob_coords_type": "G90",
  555. "cncjob_coords_decimals": 4,
  556. "cncjob_fr_decimals": 2,
  557. "cncjob_steps_per_circle": 128,
  558. "cncjob_footer": False,
  559. "cncjob_line_ending": False,
  560. # CNC Job Options
  561. "cncjob_prepend": "",
  562. "cncjob_append": "",
  563. # CNC Job Advanced Options
  564. "cncjob_toolchange_macro": "",
  565. "cncjob_toolchange_macro_enable": False,
  566. "cncjob_annotation_fontsize": 9,
  567. "cncjob_annotation_fontcolor": '#990000',
  568. # NCC Tool
  569. "tools_ncctools": "0.0393701, 0.019685",
  570. "tools_nccorder": 'rev',
  571. "tools_nccoverlap": 0.015748,
  572. "tools_nccmargin": 0.0393701,
  573. "tools_nccmethod": "seed",
  574. "tools_nccconnect": True,
  575. "tools_ncccontour": True,
  576. "tools_nccrest": False,
  577. "tools_ncc_offset_choice": False,
  578. "tools_ncc_offset_value": 0.0000,
  579. "tools_nccref": 'itself',
  580. "tools_ncc_plotting": 'normal',
  581. "tools_nccmilling_type": 'cl',
  582. "tools_ncctool_type": 'V',
  583. "tools_ncccutz": -0.001968504,
  584. "tools_ncctipdia": 0.00393701,
  585. "tools_ncctipangle": 30,
  586. "tools_nccnewdia": 0.0393701,
  587. # Cutout Tool
  588. "tools_cutouttooldia": 0.0944882,
  589. "tools_cutoutkind": "single",
  590. "tools_cutoutmargin": 0.00393701,
  591. "tools_cutoutgapsize": 0.15748,
  592. "tools_gaps_ff": "4",
  593. "tools_cutout_convexshape": False,
  594. # Paint Tool
  595. "tools_painttooldia": 0.023622,
  596. "tools_paintorder": 'rev',
  597. "tools_paintoverlap": 0.015748,
  598. "tools_paintmargin": 0.0,
  599. "tools_paintmethod": "seed",
  600. "tools_selectmethod": "all",
  601. "tools_pathconnect": True,
  602. "tools_paintcontour": True,
  603. "tools_paint_plotting": 'normal',
  604. # 2-Sided Tool
  605. "tools_2sided_mirror_axis": "X",
  606. "tools_2sided_axis_loc": "point",
  607. "tools_2sided_drilldia": 0.11811,
  608. # Film Tool
  609. "tools_film_type": 'neg',
  610. "tools_film_boundary": 0.0393701,
  611. "tools_film_scale_stroke": 0,
  612. "tools_film_color": '#000000',
  613. "tools_film_scale_cb": False,
  614. "tools_film_scale_x_entry": 1.0,
  615. "tools_film_scale_y_entry": 1.0,
  616. "tools_film_skew_cb": False,
  617. "tools_film_skew_x_entry": 0.0,
  618. "tools_film_skew_y_entry": 0.0,
  619. "tools_film_skew_ref_radio": 'bottomleft',
  620. "tools_film_mirror_cb": False,
  621. "tools_film_mirror_axis_radio": 'none',
  622. # Panel Tool
  623. "tools_panelize_spacing_columns": 0,
  624. "tools_panelize_spacing_rows": 0,
  625. "tools_panelize_columns": 1,
  626. "tools_panelize_rows": 1,
  627. "tools_panelize_constrain": False,
  628. "tools_panelize_constrainx": 200.0,
  629. "tools_panelize_constrainy": 290.0,
  630. "tools_panelize_panel_type": 'gerber',
  631. # Calculators Tool
  632. "tools_calc_vshape_tip_dia": 0.007874,
  633. "tools_calc_vshape_tip_angle": 30,
  634. "tools_calc_vshape_cut_z": 0.000787,
  635. "tools_calc_electro_length": 10.0,
  636. "tools_calc_electro_width": 10.0,
  637. "tools_calc_electro_cdensity": 13.0,
  638. "tools_calc_electro_growth": 10.0,
  639. # Transform Tool
  640. "tools_transform_rotate": 90,
  641. "tools_transform_skew_x": 0.0,
  642. "tools_transform_skew_y": 0.0,
  643. "tools_transform_scale_x": 1.0,
  644. "tools_transform_scale_y": 1.0,
  645. "tools_transform_scale_link": True,
  646. "tools_transform_scale_reference": True,
  647. "tools_transform_offset_x": 0.0,
  648. "tools_transform_offset_y": 0.0,
  649. "tools_transform_mirror_reference": False,
  650. "tools_transform_mirror_point": (0, 0),
  651. # SolderPaste Tool
  652. "tools_solderpaste_tools": "0.0393701, 0.011811",
  653. "tools_solderpaste_new": 0.011811,
  654. "tools_solderpaste_z_start": 0.00019685039,
  655. "tools_solderpaste_z_dispense": 0.00393701,
  656. "tools_solderpaste_z_stop": 0.00019685039,
  657. "tools_solderpaste_z_travel": 0.00393701,
  658. "tools_solderpaste_z_toolchange": 0.0393701,
  659. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  660. "tools_solderpaste_frxy": 3.0,
  661. "tools_solderpaste_frz": 3.0,
  662. "tools_solderpaste_frz_dispense": 0.0393701,
  663. "tools_solderpaste_speedfwd": 20,
  664. "tools_solderpaste_dwellfwd": 1,
  665. "tools_solderpaste_speedrev": 10,
  666. "tools_solderpaste_dwellrev": 1,
  667. "tools_solderpaste_pp": 'Paste_1',
  668. # Subtract Tool
  669. "tools_sub_close_paths": True,
  670. # ###################################################################################
  671. # ################################ TOOLS 2 ##########################################
  672. # ###################################################################################
  673. # Optimal Tool
  674. "tools_opt_precision": 4,
  675. # Check Rules Tool
  676. "tools_cr_trace_size": True,
  677. "tools_cr_trace_size_val": 0.01,
  678. "tools_cr_c2c": True,
  679. "tools_cr_c2c_val": 0.01,
  680. "tools_cr_c2o": True,
  681. "tools_cr_c2o_val": 0.03937,
  682. "tools_cr_s2s": True,
  683. "tools_cr_s2s_val": 0.01,
  684. "tools_cr_s2sm": True,
  685. "tools_cr_s2sm_val": 0.01,
  686. "tools_cr_s2o": True,
  687. "tools_cr_s2o_val": 0.03937,
  688. "tools_cr_sm2sm": True,
  689. "tools_cr_sm2sm_val": 0.01,
  690. "tools_cr_ri": True,
  691. "tools_cr_ri_val": 0.015,
  692. "tools_cr_h2h": True,
  693. "tools_cr_h2h_val": 0.015,
  694. "tools_cr_dh": True,
  695. "tools_cr_dh_val": 0.011811,
  696. # QRCode Tool
  697. "tools_qrcode_version": 1,
  698. "tools_qrcode_error": 'L',
  699. "tools_qrcode_box_size": 3,
  700. "tools_qrcode_border_size": 4,
  701. "tools_qrcode_qrdata": '',
  702. "tools_qrcode_polarity": 'pos',
  703. "tools_qrcode_rounded": 's',
  704. "tools_qrcode_fill_color": '#000000',
  705. "tools_qrcode_back_color": '#FFFFFF',
  706. "tools_qrcode_sel_limit": 330,
  707. # Copper Thieving Tool
  708. "tools_copper_thieving_clearance": 0.01,
  709. "tools_copper_thieving_margin": 0.039,
  710. "tools_copper_thieving_reference": 'itself',
  711. "tools_copper_thieving_box_type": 'rect',
  712. "tools_copper_thieving_circle_steps": 128,
  713. "tools_copper_thieving_fill_type": 'solid',
  714. "tools_copper_thieving_dots_dia": 0.0393701,
  715. "tools_copper_thieving_dots_spacing": 0.0787402,
  716. "tools_copper_thieving_squares_size": 0.0393701,
  717. "tools_copper_thieving_squares_spacing": 0.0787402,
  718. "tools_copper_thieving_lines_size": 0.01,
  719. "tools_copper_thieving_lines_spacing": 0.0787402,
  720. # Utilities
  721. # file associations
  722. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  723. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  724. 'ncg, ncp, ngc, out, plt, ply, rol, sbp, tap, xpi',
  725. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  726. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  727. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  728. # Keyword list
  729. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  730. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  731. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  732. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  733. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  734. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  735. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  736. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  737. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  738. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  739. 'toolchange_xy, tooldia, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  740. 'z_move',
  741. "script_autocompleter": True,
  742. "script_text": "",
  743. "script_plot": True,
  744. "script_source_file": "",
  745. "document_autocompleter": False,
  746. "document_text": "",
  747. "document_plot": True,
  748. "document_source_file": "",
  749. "document_font_color": '#000000',
  750. "document_sel_color": '#0055ff',
  751. "document_font_size": 6,
  752. "document_tab_size": 80,
  753. })
  754. # ############################################################
  755. # ############### Load defaults from file ####################
  756. # ############################################################
  757. if user_defaults:
  758. self.load_defaults(filename='current_defaults')
  759. # #############################################################################
  760. # ##################### CREATE MULTIPROCESSING POOL ###########################
  761. # #############################################################################
  762. self.pool = Pool(processes=cpu_count())
  763. # ##########################################################################
  764. # ################## Setting the Splash Screen #############################
  765. # ##########################################################################
  766. splash_settings = QSettings("Open Source", "FlatCAM")
  767. if splash_settings.contains("splash_screen"):
  768. show_splash = splash_settings.value("splash_screen")
  769. else:
  770. splash_settings.setValue('splash_screen', 1)
  771. # This will write the setting to the platform specific storage.
  772. del splash_settings
  773. show_splash = 1
  774. if show_splash and self.cmd_line_headless != 1:
  775. splash_pix = QtGui.QPixmap('share/splash.png')
  776. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  777. # self.splash.setMask(splash_pix.mask())
  778. # move splashscreen to the current monitor
  779. desktop = QtWidgets.QApplication.desktop()
  780. screen = desktop.screenNumber(QtGui.QCursor.pos())
  781. current_screen_center = desktop.availableGeometry(screen).center()
  782. self.splash.move(current_screen_center - self.splash.rect().center())
  783. self.splash.show()
  784. self.splash.showMessage(_("FlatCAM is initializing ..."),
  785. alignment=Qt.AlignBottom | Qt.AlignLeft,
  786. color=QtGui.QColor("gray"))
  787. else:
  788. show_splash = 0
  789. # #############################################################################
  790. # ##################### Initialize GUI ########################################
  791. # #############################################################################
  792. # FlatCAM colors used in plotting
  793. self.FC_light_green = '#BBF268BF'
  794. self.FC_dark_green = '#006E20BF'
  795. self.FC_light_blue = '#a5a5ffbf'
  796. self.FC_dark_blue = '#0000ffbf'
  797. QtCore.QObject.__init__(self)
  798. self.ui = FlatCAMGUI(self.version, self.beta, self)
  799. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  800. if theme_settings.contains("theme"):
  801. theme = theme_settings.value('theme', type=str)
  802. else:
  803. theme = 'white'
  804. if theme == 'white':
  805. self.cursor_color_3D = 'black'
  806. else:
  807. self.cursor_color_3D = 'gray'
  808. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  809. self.ui.final_save.connect(self.final_save)
  810. # restore the toolbar view
  811. self.restore_toolbar_view()
  812. # restore the GUI geometry
  813. self.restore_main_win_geom()
  814. # set FlatCAM units in the Status bar
  815. self.set_screen_units(self.defaults['units'])
  816. # #############################################################################
  817. # ######################## UPDATE PREFERENCES GUI FORMS #######################
  818. # #############################################################################
  819. # when adding entries here read the comments in the method found bellow named:
  820. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  821. self.defaults_form_fields = {
  822. # General App
  823. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  824. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  825. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  826. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  827. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  828. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  829. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  830. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  831. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  832. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  833. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  834. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  835. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  836. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  837. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_group.bm_limit_spinner,
  838. "global_machinist_setting": self.ui.general_defaults_form.general_app_group.machinist_cb,
  839. # General GUI Preferences
  840. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  841. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  842. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  843. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  844. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  845. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  846. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  847. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  848. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  849. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  850. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  851. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  852. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  853. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  854. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  855. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  856. # General GUI Settings
  857. "global_theme": self.ui.general_defaults_form.general_gui_set_group.theme_radio,
  858. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  859. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  860. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  861. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  862. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  863. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  864. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  865. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  866. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  867. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  868. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  869. # Gerber General
  870. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  871. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  872. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  873. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  874. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  875. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  876. # Gerber Options
  877. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  878. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  879. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  880. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  881. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  882. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  883. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  884. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  885. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  886. # Gerber Advanced Options
  887. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  888. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  889. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  890. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  891. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  892. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  893. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  894. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  895. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  896. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  897. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  898. # Gerber Export
  899. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  900. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  901. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  902. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  903. # Gerber Editor
  904. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  905. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  906. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  907. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  908. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  909. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  910. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  911. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  912. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  913. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  914. "gerber_editor_circ_angle":
  915. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  916. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  917. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  918. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  919. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  920. # Excellon General
  921. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  922. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  923. "excellon_format_upper_in":
  924. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  925. "excellon_format_lower_in":
  926. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  927. "excellon_format_upper_mm":
  928. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  929. "excellon_format_lower_mm":
  930. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  931. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  932. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  933. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  934. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  935. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  936. # Excellon Options
  937. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  938. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  939. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  940. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  941. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  942. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  943. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  944. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  945. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  946. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  947. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  948. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  949. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  950. # Excellon Advanced Options
  951. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  952. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  953. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  954. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  955. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  956. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  957. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  958. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  959. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  960. # Excellon Export
  961. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  962. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  963. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  964. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  965. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  966. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  967. # Excellon Editor
  968. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  969. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  970. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  971. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  972. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  973. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  974. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  975. "excellon_editor_circ_angle":
  976. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  977. # Excellon Slots
  978. "excellon_editor_slot_direction":
  979. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  980. "excellon_editor_slot_angle":
  981. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  982. "excellon_editor_slot_length":
  983. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  984. # Excellon Slots
  985. "excellon_editor_slot_array_size":
  986. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  987. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  988. "excellon_editor_slot_lin_pitch":
  989. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  990. "excellon_editor_slot_lin_angle":
  991. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  992. "excellon_editor_slot_circ_dir":
  993. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  994. "excellon_editor_slot_circ_angle":
  995. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  996. # Geometry General
  997. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  998. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  999. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  1000. # Geometry Options
  1001. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  1002. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  1003. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  1004. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  1005. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  1006. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  1007. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  1008. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  1009. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  1010. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  1011. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  1012. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  1013. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  1014. # Geometry Advanced Options
  1015. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  1016. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  1017. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1018. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  1019. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  1020. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  1021. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  1022. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  1023. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  1024. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  1025. # Geometry Editor
  1026. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  1027. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  1028. # CNCJob General
  1029. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  1030. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  1031. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  1032. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  1033. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  1034. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  1035. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  1036. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  1037. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  1038. # CNC Job Options
  1039. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  1040. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  1041. # CNC Job Advanced Options
  1042. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  1043. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  1044. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  1045. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  1046. # NCC Tool
  1047. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  1048. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  1049. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  1050. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  1051. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  1052. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  1053. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  1054. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  1055. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  1056. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  1057. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  1058. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  1059. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  1060. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  1061. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  1062. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  1063. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  1064. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  1065. # CutOut Tool
  1066. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  1067. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  1068. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  1069. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  1070. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  1071. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  1072. # Paint Area Tool
  1073. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  1074. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  1075. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  1076. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  1077. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  1078. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  1079. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  1080. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  1081. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  1082. # 2-sided Tool
  1083. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  1084. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  1085. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  1086. # Film Tool
  1087. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  1088. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  1089. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  1090. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  1091. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  1092. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  1093. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  1094. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  1095. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  1096. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  1097. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  1098. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  1099. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  1100. # Panelize Tool
  1101. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  1102. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  1103. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  1104. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  1105. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  1106. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  1107. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  1108. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  1109. # Calculators Tool
  1110. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  1111. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  1112. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  1113. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  1114. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  1115. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  1116. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  1117. # Transformations Tool
  1118. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  1119. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  1120. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  1121. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  1122. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  1123. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  1124. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  1125. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  1126. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  1127. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  1128. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  1129. # SolderPaste Dispensing Tool
  1130. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  1131. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  1132. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  1133. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  1134. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  1135. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  1136. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  1137. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  1138. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  1139. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  1140. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  1141. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  1142. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  1143. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  1144. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  1145. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  1146. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  1147. # ###################################################################################
  1148. # ################################ TOOLS 2 ##########################################
  1149. # ###################################################################################
  1150. # Optimal Tool
  1151. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  1152. # Check Rules Tool
  1153. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  1154. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  1155. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  1156. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  1157. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  1158. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  1159. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  1160. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  1161. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  1162. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  1163. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  1164. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  1165. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  1166. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  1167. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  1168. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  1169. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  1170. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  1171. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  1172. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  1173. # QRCode Tool
  1174. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  1175. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  1176. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  1177. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  1178. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  1179. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  1180. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  1181. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  1182. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  1183. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  1184. # Copper Thieving Tool
  1185. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  1186. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  1187. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  1188. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  1189. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  1190. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  1191. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  1192. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  1193. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  1194. "tools_copper_thieving_squares_spacing":
  1195. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  1196. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  1197. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  1198. # Utilities
  1199. # File associations
  1200. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  1201. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  1202. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  1203. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  1204. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  1205. }
  1206. # update the Preferences GUI elements with the values in the self.defaults
  1207. self.defaults_write_form()
  1208. # When the self.defaults dictionary changes will update the Preferences GUI forms
  1209. self.defaults.set_change_callback(self.on_defaults_dict_change)
  1210. # #############################################################################
  1211. # ############################## Data #########################################
  1212. # #############################################################################
  1213. self.recent = []
  1214. self.recent_projects = []
  1215. self.clipboard = QtWidgets.QApplication.clipboard()
  1216. self.project_filename = None
  1217. self.toggle_units_ignore = False
  1218. # #############################################################################
  1219. # ########################## LOAD POSTPROCESSORS ##############################
  1220. # #############################################################################
  1221. # a dictionary that have as keys the name of the postprocessor files and the value is the class from
  1222. # the postprocessor file
  1223. self.postprocessors = load_postprocessors(self)
  1224. # make sure that always the 'default' postprocessor is the first item in the dictionary
  1225. if 'default' in self.postprocessors.keys():
  1226. new_ppp_dict = dict()
  1227. # add the 'default' name first in the dict after removing from the postprocessor's dictionary
  1228. default_pp = self.postprocessors.pop('default')
  1229. new_ppp_dict['default'] = default_pp
  1230. # then add the rest of the keys
  1231. for name, val_class in self.postprocessors.items():
  1232. new_ppp_dict[name] = val_class
  1233. # and now put back the ordered dict with 'default' key first
  1234. self.postprocessors = new_ppp_dict
  1235. for name in list(self.postprocessors.keys()):
  1236. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  1237. if name.partition('_')[0] == 'Paste':
  1238. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  1239. continue
  1240. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1241. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  1242. if name == 'hpgl':
  1243. continue
  1244. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1245. # #############################################################################
  1246. # ########################## LOAD LANGUAGES ##################################
  1247. # #############################################################################
  1248. self.languages = fcTranslate.load_languages()
  1249. for name in sorted(self.languages.values()):
  1250. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  1251. # #############################################################################
  1252. # ############################ APPLY APP LANGUAGE #############################
  1253. # #############################################################################
  1254. ret_val = fcTranslate.apply_language('strings')
  1255. if ret_val == "no language":
  1256. self.inform.emit('[ERROR] %s' %
  1257. _("Could not find the Language files. The App strings are missing."))
  1258. log.debug("Could not find the Language files. The App strings are missing.")
  1259. else:
  1260. # make the current language the current selection on the language combobox
  1261. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1262. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1263. # #############################################################################
  1264. # ########################### CREATE UNIQUE SERIAL NUMBER #####################
  1265. # #############################################################################
  1266. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1267. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1268. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1269. self.save_defaults(silent=True, first_time=True)
  1270. self.propagate_defaults(silent=True)
  1271. # def auto_save_defaults():
  1272. # try:
  1273. # self.save_defaults(silent=True)
  1274. # self.propagate_defaults(silent=True)
  1275. # finally:
  1276. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1277. # the following lines activates automatic defaults save
  1278. # if user_defaults:
  1279. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1280. self.options = LoudDict()
  1281. # ----------------------------------------------------------------------------------------------------
  1282. # Update the self.options from the self.defaults
  1283. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1284. # -----------------------------------------------------------------------------------------------------
  1285. self.options.update(self.defaults) # Copy app defaults to project options
  1286. self.gen_form = None
  1287. self.ger_form = None
  1288. self.exc_form = None
  1289. self.geo_form = None
  1290. self.cnc_form = None
  1291. self.tools_form = None
  1292. self.tools2_form = None
  1293. self.fa_form = None
  1294. # Will show the Preferences GUI
  1295. self.show_preferences_gui()
  1296. # Initialize the color box's color in Preferences -> Global -> Color
  1297. self.init_color_pickers_in_preferences_gui()
  1298. # ### End of Data ####
  1299. # #############################################################################
  1300. # ######################## SETUP OBJECT COLLECTION ############################
  1301. # #############################################################################
  1302. self.collection = ObjectCollection(self)
  1303. self.ui.project_tab_layout.addWidget(self.collection.view)
  1304. # ### Adjust tabs width ## ##
  1305. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1306. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1307. self.collection.view.setMinimumWidth(290)
  1308. self.log.debug("Finished creating Object Collection.")
  1309. # #############################################################################
  1310. # ############################## SETUP Plot Area ##############################
  1311. # #############################################################################
  1312. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1313. if self.defaults["global_graphic_engine"] == '3D':
  1314. self.is_legacy = False
  1315. else:
  1316. self.is_legacy = True
  1317. # Matplotlib axis
  1318. self.axes = None
  1319. if show_splash:
  1320. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1321. "Canvas initialization started."),
  1322. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1323. color=QtGui.QColor("gray"))
  1324. start_plot_time = time.time() # debug
  1325. self.plotcanvas = None
  1326. self.app_cursor = None
  1327. self.hover_shapes = None
  1328. # setup the PlotCanvas
  1329. self.on_plotcanvas_setup()
  1330. end_plot_time = time.time()
  1331. self.used_time = end_plot_time - start_plot_time
  1332. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1333. if show_splash:
  1334. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1335. "Canvas initialization started.\n"
  1336. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1337. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1338. color=QtGui.QColor("gray"))
  1339. self.ui.splitter.setStretchFactor(1, 2)
  1340. # #############################################################################
  1341. # ################################### SYS TRAY ################################
  1342. # #############################################################################
  1343. if self.defaults["global_systray_icon"]:
  1344. self.parent_w = QtWidgets.QWidget()
  1345. if self.cmd_line_headless == 1:
  1346. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1347. headless=True,
  1348. parent=self.parent_w)
  1349. else:
  1350. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1351. parent=self.parent_w)
  1352. # #############################################################################
  1353. # ################################## Worker SETUP #############################
  1354. # #############################################################################
  1355. if self.defaults["global_worker_number"]:
  1356. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1357. else:
  1358. self.workers = WorkerStack(workers_number=2)
  1359. self.worker_task.connect(self.workers.add_task)
  1360. self.log.debug("Finished creating Workers crew.")
  1361. # #############################################################################
  1362. # ################################# Activity Monitor ##########################
  1363. # #############################################################################
  1364. self.activity_view = FlatCAMActivityView(app=self)
  1365. self.ui.infobar.addWidget(self.activity_view)
  1366. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1367. # #############################################################################
  1368. # ################################## Signal handling ##########################
  1369. # #############################################################################
  1370. # ################################# Custom signals ###########################
  1371. # signal for displaying messages in status bar
  1372. self.inform.connect(self.info)
  1373. # signal to be called when the app is quiting
  1374. self.app_quit.connect(self.quit_application)
  1375. self.message.connect(self.message_dialog)
  1376. self.progress.connect(self.set_progress_bar)
  1377. # signals that are emitted when object state changes
  1378. self.object_created.connect(self.on_object_created)
  1379. self.object_changed.connect(self.on_object_changed)
  1380. self.object_plotted.connect(self.on_object_plotted)
  1381. self.plots_updated.connect(self.on_plots_updated)
  1382. # signals emitted when file state change
  1383. self.file_opened.connect(self.register_recent)
  1384. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1385. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1386. # ############# Standard signals ###################
  1387. # ### Menu
  1388. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1389. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1390. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1391. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1392. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1393. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1394. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1395. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1396. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1397. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1398. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1399. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1400. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1401. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1402. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1403. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1404. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1405. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1406. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1407. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1408. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1409. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1410. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1411. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1412. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1413. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1414. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1415. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1416. self.ui.menufile_exit.triggered.connect(self.final_save)
  1417. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1418. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1419. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1420. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1421. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1422. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1423. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1424. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1425. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1426. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1427. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1428. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1429. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1430. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1431. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1432. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1433. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1434. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1435. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1436. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1437. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1438. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1439. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1440. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1441. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1442. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1443. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1444. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1445. self.ui.menuoptions_tools_db.triggered.connect(self.on_tools_database)
  1446. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1447. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1448. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1449. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1450. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1451. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1452. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1453. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1454. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1455. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1456. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1457. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1458. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1459. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1460. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1461. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1462. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1463. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1464. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1465. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1466. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1467. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1468. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1469. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1470. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1471. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1472. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1473. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1474. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1475. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1476. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1477. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1478. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1479. # ToolBar signals
  1480. self.connect_toolbar_signals()
  1481. # Notebook and Plot Tab Area signals
  1482. # make the right click on the notebook tab and plot tab area tab raise a menu
  1483. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1484. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1485. self.on_tab_setup_context_menu()
  1486. # activate initial state
  1487. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1488. # Context Menu
  1489. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1490. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1491. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1492. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1493. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1494. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1495. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1496. self.ui.clearplot.triggered.connect(self.clear_plots)
  1497. self.ui.replot.triggered.connect(self.plot_all)
  1498. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1499. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1500. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1501. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1502. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1503. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1504. # Preferences Plot Area TAB
  1505. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1506. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1507. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1508. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1509. # #############################################################################
  1510. # ######################### GUI PREFERENCES SIGNALS ###########################
  1511. # #############################################################################
  1512. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1513. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1514. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1515. )
  1516. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1517. lambda: self.on_toggle_units(no_pref=False))
  1518. # #############################################################################
  1519. # ############################# GUI COLORS SIGNALS ############################
  1520. # #############################################################################
  1521. # Setting plot colors signals
  1522. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1523. self.on_pf_color_entry)
  1524. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1525. self.on_pf_color_button)
  1526. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1527. self.on_pf_color_spinner)
  1528. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1529. self.on_pf_color_slider)
  1530. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1531. self.on_pl_color_entry)
  1532. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1533. self.on_pl_color_button)
  1534. # Setting selection (left - right) colors signals
  1535. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1536. self.on_sf_color_entry)
  1537. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1538. self.on_sf_color_button)
  1539. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1540. self.on_sf_color_spinner)
  1541. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1542. self.on_sf_color_slider)
  1543. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1544. self.on_sl_color_entry)
  1545. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1546. self.on_sl_color_button)
  1547. # Setting selection (right - left) colors signals
  1548. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1549. self.on_alt_sf_color_entry)
  1550. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1551. self.on_alt_sf_color_button)
  1552. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1553. self.on_alt_sf_color_spinner)
  1554. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1555. self.on_alt_sf_color_slider)
  1556. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1557. self.on_alt_sl_color_entry)
  1558. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1559. self.on_alt_sl_color_button)
  1560. # Setting Editor Draw colors signals
  1561. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1562. self.on_draw_color_entry)
  1563. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1564. self.on_draw_color_button)
  1565. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1566. self.on_sel_draw_color_entry)
  1567. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1568. self.on_sel_draw_color_button)
  1569. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1570. self.on_proj_color_entry)
  1571. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1572. self.on_proj_color_button)
  1573. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1574. self.on_proj_color_dis_entry)
  1575. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1576. self.on_proj_color_dis_button)
  1577. # ############################# workspace setting signals #####################
  1578. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1579. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1580. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1581. # #############################################################################
  1582. # ############################# GUI SETTINGS SIGNALS ##########################
  1583. # #############################################################################
  1584. self.ui.general_defaults_form.general_gui_set_group.theme_radio.activated_custom.connect(self.on_theme_change)
  1585. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1586. # ########## CNC Job related signals #############
  1587. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1588. self.on_cnc_custom_parameters)
  1589. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1590. self.on_annotation_fontcolor_entry)
  1591. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1592. self.on_annotation_fontcolor_button)
  1593. # ########## Tools related signals #############
  1594. # Film Tool
  1595. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1596. self.on_film_color_entry)
  1597. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1598. self.on_film_color_button)
  1599. # QRCode Tool
  1600. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1601. self.on_qrcode_fill_color_entry)
  1602. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1603. self.on_qrcode_fill_color_button)
  1604. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1605. self.on_qrcode_back_color_entry)
  1606. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1607. self.on_qrcode_back_color_button)
  1608. # portability changed signal
  1609. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1610. # Object list
  1611. self.collection.view.activated.connect(self.on_row_activated)
  1612. self.collection.item_selected.connect(self.on_row_selected)
  1613. self.object_status_changed.connect(self.on_collection_updated)
  1614. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1615. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1616. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1617. # Export Excellon parameters.
  1618. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1619. self.on_update_exc_export
  1620. )
  1621. # call it once to make sure it is updated at startup
  1622. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1623. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1624. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1625. self.on_excellon_defaults_button)
  1626. # when there are arguments at application startup this get launched
  1627. self.args_at_startup[list].connect(self.on_startup_args)
  1628. # #############################################################################
  1629. # ########################## FILE ASSOCIATIONS SIGNALS ########################
  1630. # #############################################################################
  1631. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1632. lambda: self.restore_extensions(ext_type='excellon'))
  1633. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1634. lambda: self.restore_extensions(ext_type='gcode'))
  1635. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1636. lambda: self.restore_extensions(ext_type='gerber'))
  1637. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1638. lambda: self.delete_all_extensions(ext_type='excellon'))
  1639. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1640. lambda: self.delete_all_extensions(ext_type='gcode'))
  1641. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1642. lambda: self.delete_all_extensions(ext_type='gerber'))
  1643. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1644. lambda: self.add_extension(ext_type='excellon'))
  1645. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1646. lambda: self.add_extension(ext_type='gcode'))
  1647. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1648. lambda: self.add_extension(ext_type='gerber'))
  1649. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1650. lambda: self.del_extension(ext_type='excellon'))
  1651. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1652. lambda: self.del_extension(ext_type='gcode'))
  1653. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1654. lambda: self.del_extension(ext_type='gerber'))
  1655. # connect the 'Apply' buttons from the Preferences/File Associations
  1656. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1657. lambda: self.on_register_files(obj_type='excellon'))
  1658. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1659. lambda: self.on_register_files(obj_type='gcode'))
  1660. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1661. lambda: self.on_register_files(obj_type='gerber'))
  1662. # #############################################################################
  1663. # ################################ KEYWORDS SIGNALS ###########################
  1664. # #############################################################################
  1665. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1666. lambda: self.restore_extensions(ext_type='keyword'))
  1667. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1668. lambda: self.delete_all_extensions(ext_type='keyword'))
  1669. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1670. lambda: self.add_extension(ext_type='keyword'))
  1671. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1672. lambda: self.del_extension(ext_type='keyword'))
  1673. # splash screen button signal
  1674. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1675. # connect the abort_all_tasks related slots to the related signals
  1676. self.proc_container.idle_flag.connect(self.app_is_idle)
  1677. # signal emitted when a tab is closed in the Plot Area
  1678. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1679. # #####################################################################################
  1680. # ########### FINISHED CONNECTING SIGNALS #############################################
  1681. # #####################################################################################
  1682. self.log.debug("Finished connecting Signals.")
  1683. # #####################################################################################
  1684. # ########################## Other setups #############################################
  1685. # #####################################################################################
  1686. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1687. # depending on from where those tools are called different actions can be done
  1688. self.call_source = 'app'
  1689. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1690. self.tool_tab_locked = False
  1691. # decide if to show or hide the Notebook side of the screen at startup
  1692. if self.defaults["global_project_at_startup"] is True:
  1693. self.ui.splitter.setSizes([1, 1])
  1694. else:
  1695. self.ui.splitter.setSizes([0, 1])
  1696. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1697. self.setup_obj_classes()
  1698. self.setup_recent_items()
  1699. self.setup_component_editor()
  1700. # this does not work in Legacy Mode
  1701. if self.is_legacy is True:
  1702. self.ui.general_defaults_form.general_gui_group.workspace_cb.setDisabled(True)
  1703. self.ui.general_defaults_form.general_gui_group.workspace_type_lbl.setDisabled(True)
  1704. self.ui.general_defaults_form.general_gui_group.wk_cb.setDisabled(True)
  1705. # #####################################################################################
  1706. # ######################### Auto-complete KEYWORDS ####################################
  1707. # #####################################################################################
  1708. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1709. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1710. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1711. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1712. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1713. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1714. 'mirror', 'ncc',
  1715. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1716. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1717. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1718. 'save', 'save_project',
  1719. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1720. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1721. 'version', 'write_gcode'
  1722. ]
  1723. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1724. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1725. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1726. 'axisoffset',
  1727. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1728. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1729. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1730. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1731. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1732. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1733. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1734. 'spacing_columns',
  1735. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'tooldia', 'use_threads', 'value',
  1736. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1737. ]
  1738. self.tcl_keywords = [
  1739. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1740. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1741. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1742. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1743. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1744. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1745. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1746. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1747. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1748. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1749. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1750. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1751. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1752. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1753. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1754. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1755. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1756. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1757. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1758. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1759. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1760. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1761. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1762. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1763. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1764. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1765. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1766. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1767. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1768. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1769. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1770. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1771. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1772. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1773. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1774. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1775. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1776. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1777. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1778. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1779. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1780. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1781. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1782. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1783. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1784. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1785. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1786. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1787. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1788. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1789. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1790. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1791. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1792. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1793. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1794. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1795. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1796. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1797. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1798. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1799. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1800. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1801. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1802. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1803. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1804. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1805. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1806. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1807. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1808. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1809. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1810. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1811. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1812. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1813. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1814. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1815. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1816. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1817. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1818. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1819. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1820. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1821. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1822. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1823. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1824. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1825. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1826. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1827. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1828. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1829. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1830. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1831. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1832. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1833. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1834. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1835. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1836. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1837. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1838. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1839. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1840. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1841. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1842. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1843. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1844. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1845. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1846. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1847. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1848. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1849. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1850. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1851. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1852. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1853. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1854. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1855. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1856. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1857. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1858. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1859. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1860. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1861. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1862. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1863. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1864. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1865. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1866. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1867. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1868. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1869. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1870. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1871. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1872. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1873. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1874. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1875. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1876. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1877. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1878. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1879. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1880. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1881. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1882. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1883. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1884. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1885. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1886. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1887. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1888. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1889. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1890. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1891. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1892. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1893. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1894. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1895. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1896. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1897. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1898. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1899. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1900. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1901. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1902. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1903. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1904. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1905. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1906. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1907. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1908. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1909. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1910. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1911. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1912. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1913. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1914. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1915. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1916. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1917. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1918. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1919. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1920. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1921. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1922. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1923. ]
  1924. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1925. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1926. # ####################################################################################
  1927. # ####################### Shell SETUP ################################################
  1928. # ####################################################################################
  1929. # this will hold the TCL instance
  1930. self.tcl = None
  1931. self.init_tcl()
  1932. self.shell = FCShell(self, version=self.version)
  1933. self.shell._edit.set_model_data(self.myKeywords)
  1934. self.shell.setWindowIcon(self.ui.app_icon)
  1935. self.shell.setWindowTitle("FlatCAM Shell")
  1936. self.shell.resize(*self.defaults["global_shell_shape"])
  1937. self.shell.append_output("FlatCAM %s - " % self.version)
  1938. self.shell.append_output(_("Type >help< to get started\n\n"))
  1939. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1940. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1941. self.ui.shell_dock.setWidget(self.shell)
  1942. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1943. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1944. QtWidgets.QDockWidget.DockWidgetFloatable |
  1945. QtWidgets.QDockWidget.DockWidgetClosable)
  1946. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1947. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1948. if self.defaults["global_shell_at_startup"]:
  1949. self.ui.shell_dock.show()
  1950. else:
  1951. self.ui.shell_dock.hide()
  1952. # ##################################################################################
  1953. # ###################### Tools and Plugins #########################################
  1954. # ##################################################################################
  1955. self.dblsidedtool = None
  1956. self.distance_tool = None
  1957. self.distance_min_tool = None
  1958. self.panelize_tool = None
  1959. self.film_tool = None
  1960. self.paste_tool = None
  1961. self.calculator_tool = None
  1962. self.rules_tool = None
  1963. self.sub_tool = None
  1964. self.move_tool = None
  1965. self.cutout_tool = None
  1966. self.ncclear_tool = None
  1967. self.optimal_tool = None
  1968. self.paint_tool = None
  1969. self.transform_tool = None
  1970. self.properties_tool = None
  1971. self.pdf_tool = None
  1972. self.image_tool = None
  1973. self.pcb_wizard_tool = None
  1974. self.cal_exc_tool = None
  1975. self.qrcode_tool = None
  1976. self.copper_thieving_tool = None
  1977. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1978. self.install_tools()
  1979. # ##################################################################################
  1980. # ########################### BookMarks Manager ####################################
  1981. # ##################################################################################
  1982. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1983. self.install_bookmarks()
  1984. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1985. # ##################################################################################
  1986. # ############################## Tools Database ####################################
  1987. # ##################################################################################
  1988. self.tools_db_tab = None
  1989. # ### System Font Parsing ###
  1990. # self.f_parse = ParseFont(self)
  1991. # self.parse_system_fonts()
  1992. # #####################################################################################
  1993. # ######################## Check for updates ##########################################
  1994. # #####################################################################################
  1995. # Separate thread (Not worker)
  1996. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1997. if (self.beta is False or self.beta is None) and \
  1998. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1999. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2000. self.thr2 = QtCore.QThread()
  2001. self.worker_task.emit({'fcn': self.version_check,
  2002. 'params': []})
  2003. self.thr2.start(QtCore.QThread.LowPriority)
  2004. # #####################################################################################
  2005. # ######################### Register files with FlatCAM; #############################
  2006. # ######################### It works only for Windows for now ########################
  2007. # #####################################################################################
  2008. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2009. self.on_register_files()
  2010. # #####################################################################################
  2011. # ###################### Variables for global usage ###################################
  2012. # #####################################################################################
  2013. # hold the App units
  2014. self.units = 'IN'
  2015. # coordinates for relative position display
  2016. self.rel_point1 = (0, 0)
  2017. self.rel_point2 = (0, 0)
  2018. # variable to store coordinates
  2019. self.pos = (0, 0)
  2020. self.pos_jump = (0, 0)
  2021. # variable to store mouse coordinates
  2022. self.mouse = [0, 0]
  2023. # decide if we have a double click or single click
  2024. self.doubleclick = False
  2025. # variable to store if a command is active (then the var is not None) and which one it is
  2026. self.command_active = None
  2027. # variable to store the status of moving selection action
  2028. # None value means that it's not an selection action
  2029. # True value = a selection from left to right
  2030. # False value = a selection from right to left
  2031. self.selection_type = None
  2032. # List to store the objects that are currently loaded in FlatCAM
  2033. # This list is updated on each object creation or object delete
  2034. self.all_objects_list = list()
  2035. # List to store the objects that are selected
  2036. self.sel_objects_list = list()
  2037. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2038. self.key_modifiers = None
  2039. # Variable to hold the status of the axis
  2040. self.toggle_axis = True
  2041. # Variable to hold the status of the grid lines
  2042. self.toggle_grid_lines = True
  2043. # Variable to store the status of the fullscreen event
  2044. self.toggle_fscreen = False
  2045. # Variable to store the status of the code editor
  2046. self.toggle_codeeditor = False
  2047. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2048. self.click_noproject = False
  2049. self.cursor = None
  2050. # Variable to store the GCODE that was edited
  2051. self.gcode_edited = ""
  2052. self.text_editor_tab = None
  2053. # reference for the self.ui.code_editor
  2054. self.reference_code_editor = None
  2055. self.script_code = ''
  2056. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2057. self.preferences_changed_flag = False
  2058. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  2059. self.tools_db_changed_flag = False
  2060. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2061. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2062. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2063. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2064. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2065. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2066. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'plt', 'ply', 'rol',
  2067. 'sbp', 'tap', 'xpi']
  2068. self.svg_list = ['svg']
  2069. self.dxf_list = ['dxf']
  2070. self.pdf_list = ['pdf']
  2071. self.prj_list = ['flatprj']
  2072. self.conf_list = ['flatconfig']
  2073. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2074. # flag for polygons not cleared
  2075. self.poly_not_cleared = False
  2076. # VisPy visuals
  2077. self.isHovering = False
  2078. self.notHovering = True
  2079. # Window geometry
  2080. self.x_pos = None
  2081. self.y_pos = None
  2082. self.width = None
  2083. self.height = None
  2084. # Event signals disconnect id holders
  2085. self.mp = None
  2086. self.mm = None
  2087. self.mr = None
  2088. self.mp_zc = None
  2089. # when True, the app has to return from any thread
  2090. self.abort_flag = False
  2091. # set the value used in the Windows Title
  2092. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2093. # this holds a widget that is installed in the Plot Area when View Source option is used
  2094. self.source_editor_tab = None
  2095. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  2096. # VisPy visuals
  2097. if self.is_legacy is False:
  2098. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  2099. else:
  2100. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2101. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  2102. # ###############################################################################
  2103. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2104. # ############# It's done only once after install ###############
  2105. # ###############################################################################
  2106. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2107. fac_def_from_file = factory_file.read()
  2108. factory_defaults = json.loads(fac_def_from_file)
  2109. # if the file contain an empty dictionary then save the factory defaults into the file
  2110. if not factory_defaults:
  2111. self.save_factory_defaults(silent_message=False)
  2112. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2113. initial_lay = 'compact'
  2114. self.on_layout(lay=initial_lay)
  2115. # Set the combobox in Preferences to the current layout
  2116. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2117. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2118. factory_file.close()
  2119. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2120. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2121. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2122. # after the first run, this object should be False
  2123. self.defaults["first_run"] = False
  2124. # ###############################################################################
  2125. # ################# ADDING FlatCAM EDITORS section ##############################
  2126. # ###############################################################################
  2127. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2128. # at the first launch of the App , the editors will not be functional.
  2129. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2130. self.exc_editor = FlatCAMExcEditor(self)
  2131. self.grb_editor = FlatCAMGrbEditor(self)
  2132. self.log.debug("Finished adding FlatCAM Editor's.")
  2133. self.set_ui_title(name=_("New Project - Not saved"))
  2134. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2135. current_platform = platform.architecture()[0]
  2136. if current_platform != '64bit':
  2137. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2138. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2139. # ###############################################################################
  2140. # ####################### Finished the CONSTRUCTOR ##############################
  2141. # ###############################################################################
  2142. App.log.debug("END of constructor. Releasing control.")
  2143. # #####################################################################################
  2144. # ########################## SHOW GUI #################################################
  2145. # #####################################################################################
  2146. # if the app is not started as headless, show it
  2147. if self.cmd_line_headless != 1:
  2148. if show_splash:
  2149. # finish the splash
  2150. self.splash.finish(self.ui)
  2151. mgui_settings = QSettings("Open Source", "FlatCAM")
  2152. if mgui_settings.contains("maximized_gui"):
  2153. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  2154. if maximized_ui is True:
  2155. self.ui.showMaximized()
  2156. else:
  2157. self.ui.show()
  2158. else:
  2159. self.ui.show()
  2160. if self.defaults["global_systray_icon"]:
  2161. self.trayIcon.show()
  2162. else:
  2163. log.warning("******************* RUNNING HEADLESS *******************")
  2164. # #####################################################################################
  2165. # ########################## START-UP ARGUMENTS #######################################
  2166. # #####################################################################################
  2167. # test if the program was started with a script as parameter
  2168. if self.cmd_line_shellvar:
  2169. try:
  2170. cnt = 0
  2171. command_tcl = 0
  2172. for i in self.cmd_line_shellvar.split(','):
  2173. if i is not None:
  2174. # noinspection PyBroadException
  2175. try:
  2176. command_tcl = eval(i)
  2177. except Exception:
  2178. command_tcl = i
  2179. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2180. cnt += 1
  2181. # if there are Windows paths then replace the path separator with a Unix like one
  2182. if sys.platform == 'win32':
  2183. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2184. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2185. except Exception as ext:
  2186. print("ERROR: ", ext)
  2187. sys.exit(2)
  2188. if self.cmd_line_shellfile:
  2189. try:
  2190. if self.ui.shell_dock.isHidden():
  2191. self.ui.shell_dock.show()
  2192. with open(self.cmd_line_shellfile, "r") as myfile:
  2193. if show_splash:
  2194. self.splash.showMessage('%s: %ssec\n%s' % (
  2195. _("Canvas initialization started.\n"
  2196. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2197. _("Executing Tcl Script ...")),
  2198. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2199. color=QtGui.QColor("gray"))
  2200. cmd_line_shellfile_text = myfile.read()
  2201. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2202. except Exception as ext:
  2203. print("ERROR: ", ext)
  2204. sys.exit(2)
  2205. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2206. # the path/file_name must be enclosed in quotes if it contain spaces
  2207. if App.args:
  2208. self.args_at_startup.emit(App.args)
  2209. @staticmethod
  2210. def copy_and_overwrite(from_path, to_path):
  2211. """
  2212. From here:
  2213. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2214. :param from_path: source path
  2215. :param to_path: destination path
  2216. :return: None
  2217. """
  2218. if os.path.exists(to_path):
  2219. shutil.rmtree(to_path)
  2220. try:
  2221. shutil.copytree(from_path, to_path)
  2222. except FileNotFoundError:
  2223. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2224. shutil.copytree(from_new_path, to_path)
  2225. def on_startup_args(self, args, silent=False):
  2226. """
  2227. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2228. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  2229. :param args: a list containing the application args at startup
  2230. :return: None
  2231. """
  2232. if args is not None:
  2233. args_to_process = args
  2234. else:
  2235. args_to_process = App.args
  2236. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2237. for argument in args_to_process:
  2238. if '.FlatPrj'.lower() in argument.lower():
  2239. try:
  2240. project_name = str(argument)
  2241. if project_name == "":
  2242. if silent is False:
  2243. self.inform.emit(_("Open cancelled."))
  2244. else:
  2245. # self.open_project(project_name)
  2246. run_from_arg = True
  2247. # self.worker_task.emit({'fcn': self.open_project,
  2248. # 'params': [project_name, run_from_arg]})
  2249. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2250. except Exception as e:
  2251. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2252. elif '.FlatConfig'.lower() in argument.lower():
  2253. try:
  2254. file_name = str(argument)
  2255. if file_name == "":
  2256. if silent is False:
  2257. self.inform.emit(_("Open Config file failed."))
  2258. else:
  2259. run_from_arg = True
  2260. # self.worker_task.emit({'fcn': self.open_config_file,
  2261. # 'params': [file_name, run_from_arg]})
  2262. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2263. except Exception as e:
  2264. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2265. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2266. try:
  2267. file_name = str(argument)
  2268. if file_name == "":
  2269. if silent is False:
  2270. self.inform.emit(_("Open Script file failed."))
  2271. else:
  2272. if silent is False:
  2273. self.on_fileopenscript(name=file_name)
  2274. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2275. self.on_filerunscript(name=file_name)
  2276. except Exception as e:
  2277. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2278. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2279. log.debug("App.on_startup_args() --> Quit event.")
  2280. sys.exit()
  2281. elif 'save'.lower() in argument.lower():
  2282. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2283. self.save_defaults()
  2284. else:
  2285. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2286. proc_arg = argument.lower()
  2287. for ext in exc_list:
  2288. proc_ext = ext.replace(' ', '')
  2289. proc_ext = '.%s' % proc_ext
  2290. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2291. file_name = str(argument)
  2292. if file_name == "":
  2293. if silent is False:
  2294. self.inform.emit(_("Open Excellon file failed."))
  2295. else:
  2296. self.on_fileopenexcellon(name=file_name)
  2297. return
  2298. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2299. for ext in gco_list:
  2300. proc_ext = ext.replace(' ', '')
  2301. proc_ext = '.%s' % proc_ext
  2302. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2303. file_name = str(argument)
  2304. if file_name == "":
  2305. if silent is False:
  2306. self.inform.emit(_("Open GCode file failed."))
  2307. else:
  2308. self.on_fileopengcode(name=file_name)
  2309. return
  2310. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2311. for ext in grb_list:
  2312. proc_ext = ext.replace(' ', '')
  2313. proc_ext = '.%s' % proc_ext
  2314. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2315. file_name = str(argument)
  2316. if file_name == "":
  2317. if silent is False:
  2318. self.inform.emit(_("Open Gerber file failed."))
  2319. else:
  2320. self.on_fileopengerber(name=file_name)
  2321. return
  2322. # if it reached here without already returning then the app was registered with a file that it does not
  2323. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2324. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2325. # for arg in args_to_process:
  2326. # if 'FlatCAM.exe' in arg:
  2327. # continue
  2328. # else:
  2329. # sys.exit(2)
  2330. def set_ui_title(self, name):
  2331. """
  2332. Sets the title of the main window.
  2333. :param name: String that store the project path and project name
  2334. :return: None
  2335. """
  2336. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2337. (self.version,
  2338. ('BETA' if self.beta else ''),
  2339. platform.architecture()[0],
  2340. self.engine,
  2341. name)
  2342. )
  2343. def on_theme_change(self, val):
  2344. t_settings = QSettings("Open Source", "FlatCAM")
  2345. t_settings.setValue('theme', val)
  2346. # This will write the setting to the platform specific storage.
  2347. del t_settings
  2348. self.on_app_restart()
  2349. def on_app_restart(self):
  2350. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2351. # be left in the SySTray
  2352. try:
  2353. self.trayIcon.hide()
  2354. except Exception:
  2355. pass
  2356. fcTranslate.restart_program(app=self)
  2357. def defaults_read_form(self):
  2358. """
  2359. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2360. :return: None
  2361. """
  2362. for option in self.defaults_form_fields:
  2363. try:
  2364. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2365. except Exception as e:
  2366. log.debug("App.defaults_read_form() --> %s" % str(e))
  2367. def defaults_write_form(self, factor=None, fl_units=None):
  2368. """
  2369. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2370. self.defaults dictionary.
  2371. :param factor: will apply a factor to the values that written in the GUI elements
  2372. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2373. :return: None
  2374. """
  2375. for option in self.defaults:
  2376. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2377. # try:
  2378. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2379. # except KeyError:
  2380. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2381. # # TODO: Rethink this?
  2382. # pass
  2383. def defaults_write_form_field(self, field, factor=None, units=None):
  2384. """
  2385. Basically it is the worker in the self.defaults_write_form()
  2386. :param field: the GUI element in Preferences GUI to be updated
  2387. :param factor: factor to be applied to the field parameter
  2388. :param units: current FLatCAM measuring units
  2389. :return: None, it updates GUI elements
  2390. """
  2391. try:
  2392. if factor is None:
  2393. if units is None:
  2394. self.defaults_form_fields[field].set_value(self.defaults[field])
  2395. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2396. self.defaults_form_fields[field].set_value(self.defaults[field])
  2397. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2398. self.defaults_form_fields[field].set_value(self.defaults[field])
  2399. else:
  2400. if units is None:
  2401. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2402. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2403. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2404. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2405. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2406. except KeyError:
  2407. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2408. # TODO: Rethink this?
  2409. pass
  2410. except AttributeError:
  2411. log.debug(field)
  2412. def clear_pool(self):
  2413. """
  2414. Clear the multiprocessing pool and calls garbage collector.
  2415. :return: None
  2416. """
  2417. self.pool.close()
  2418. self.pool = Pool()
  2419. self.pool_recreated.emit(self.pool)
  2420. gc.collect()
  2421. def install_tools(self):
  2422. """
  2423. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2424. Instantiation of the Tools classes.
  2425. The order that the tools are installed is important as they can depend on each other install position.
  2426. :return: None
  2427. """
  2428. self.dblsidedtool = DblSidedTool(self)
  2429. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2430. self.cal_exc_tool = ToolCalibrateExcellon(self)
  2431. self.cal_exc_tool.install(icon=QtGui.QIcon('share/drill16.png'), pos=self.ui.menutool,
  2432. before=self.dblsidedtool.menuAction,
  2433. separator=False)
  2434. self.distance_tool = Distance(self)
  2435. self.distance_tool.install(icon=QtGui.QIcon('share/distance16.png'), pos=self.ui.menuedit,
  2436. before=self.ui.menueditorigin,
  2437. separator=False)
  2438. self.distance_min_tool = DistanceMin(self)
  2439. self.distance_min_tool.install(icon=QtGui.QIcon('share/distance_min16.png'), pos=self.ui.menuedit,
  2440. before=self.ui.menueditorigin,
  2441. separator=True)
  2442. self.panelize_tool = Panelize(self)
  2443. self.panelize_tool.install(icon=QtGui.QIcon('share/panelize16.png'))
  2444. self.film_tool = Film(self)
  2445. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2446. self.paste_tool = SolderPaste(self)
  2447. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2448. self.calculator_tool = ToolCalculator(self)
  2449. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator16.png'), separator=True)
  2450. self.sub_tool = ToolSub(self)
  2451. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2452. self.rules_tool = RulesCheck(self)
  2453. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2454. self.optimal_tool = ToolOptimal(self)
  2455. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2456. self.move_tool = ToolMove(self)
  2457. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2458. before=self.ui.menueditorigin, separator=True)
  2459. self.cutout_tool = CutOut(self)
  2460. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2461. before=self.sub_tool.menuAction)
  2462. self.ncclear_tool = NonCopperClear(self)
  2463. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2464. before=self.sub_tool.menuAction, separator=True)
  2465. self.paint_tool = ToolPaint(self)
  2466. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2467. before=self.sub_tool.menuAction, separator=True)
  2468. self.copper_thieving_tool = ToolCopperThieving(self)
  2469. self.copper_thieving_tool.install(icon=QtGui.QIcon('share/copperfill32.png'), pos=self.ui.menutool)
  2470. self.qrcode_tool = QRCode(self)
  2471. self.qrcode_tool.install(icon=QtGui.QIcon('share/qrcode32.png'), pos=self.ui.menutool)
  2472. self.transform_tool = ToolTransform(self)
  2473. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2474. self.properties_tool = Properties(self)
  2475. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2476. self.pdf_tool = ToolPDF(self)
  2477. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2478. separator=True)
  2479. self.image_tool = ToolImage(self)
  2480. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2481. separator=True)
  2482. self.pcb_wizard_tool = PcbWizard(self)
  2483. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2484. self.log.debug("Tools are installed.")
  2485. def remove_tools(self):
  2486. """
  2487. Will remove all the actions in the Tool menu.
  2488. :return: None
  2489. """
  2490. for act in self.ui.menutool.actions():
  2491. self.ui.menutool.removeAction(act)
  2492. def init_tools(self):
  2493. """
  2494. Initialize the Tool tab in the notebook side of the central widget.
  2495. Remove the actions in the Tools menu.
  2496. Instantiate again the FlatCAM tools (plugins).
  2497. All this is required when changing the layout: standard, compact etc.
  2498. :return: None
  2499. """
  2500. log.debug("init_tools()")
  2501. # delete the data currently in the Tools Tab and the Tab itself
  2502. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2503. if widget is not None:
  2504. widget.deleteLater()
  2505. self.ui.notebook.removeTab(2)
  2506. # rebuild the Tools Tab
  2507. self.ui.tool_tab = QtWidgets.QWidget()
  2508. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2509. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2510. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2511. self.ui.tool_scroll_area = VerticalScrollArea()
  2512. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2513. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2514. # first remove all of them
  2515. self.remove_tools()
  2516. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2517. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2518. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2519. # third install all of them
  2520. self.install_tools()
  2521. self.log.debug("Tools are initialized.")
  2522. # def parse_system_fonts(self):
  2523. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2524. # 'params': []})
  2525. def connect_toolbar_signals(self):
  2526. """
  2527. Reconnect the signals to the actions in the toolbar.
  2528. This has to be done each time after the FlatCAM tools are removed/installed.
  2529. :return: None
  2530. """
  2531. # Toolbar
  2532. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2533. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2534. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2535. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2536. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2537. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2538. self.ui.replot_btn.triggered.connect(self.plot_all)
  2539. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2540. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2541. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2542. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2543. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2544. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2545. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2546. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2547. self.ui.copy_btn.triggered.connect(self.on_copy_object)
  2548. self.ui.delete_btn.triggered.connect(self.on_delete)
  2549. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2550. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2551. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2552. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2553. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2554. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2555. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2556. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2557. # Tools Toolbar Signals
  2558. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2559. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2560. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2561. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2562. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2563. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2564. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2565. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2566. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2567. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2568. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2569. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2570. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2571. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2572. def object2editor(self):
  2573. """
  2574. Send the current Geometry or Excellon object (if any) into the it's editor.
  2575. :return: None
  2576. """
  2577. self.report_usage("object2editor()")
  2578. # disable the objects menu as it may interfere with the Editors
  2579. self.ui.menuobjects.setDisabled(True)
  2580. edited_object = self.collection.get_active()
  2581. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2582. isinstance(edited_object, FlatCAMExcellon):
  2583. pass
  2584. else:
  2585. self.inform.emit('[WARNING_NOTCL] %s' %
  2586. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2587. return
  2588. if isinstance(edited_object, FlatCAMGeometry):
  2589. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2590. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2591. # we set the notebook to hidden
  2592. self.ui.splitter.setSizes([0, 1])
  2593. if edited_object.multigeo is True:
  2594. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2595. if len(sel_rows) > 1:
  2596. self.inform.emit('[WARNING_NOTCL] %s' %
  2597. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2598. "is not possible.\n"
  2599. "Edit only one geometry at a time."))
  2600. # determine the tool dia of the selected tool
  2601. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2602. # now find the key in the edited_object.tools that has this tooldia
  2603. multi_tool = 1
  2604. for tool in edited_object.tools:
  2605. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2606. multi_tool = tool
  2607. break
  2608. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2609. else:
  2610. self.geo_editor.edit_fcgeometry(edited_object)
  2611. # set call source to the Editor we go into
  2612. self.call_source = 'geo_editor'
  2613. elif isinstance(edited_object, FlatCAMExcellon):
  2614. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2615. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2616. if self.ui.splitter.sizes()[0] == 0:
  2617. self.ui.splitter.setSizes([1, 1])
  2618. self.exc_editor.edit_fcexcellon(edited_object)
  2619. # set call source to the Editor we go into
  2620. self.call_source = 'exc_editor'
  2621. elif isinstance(edited_object, FlatCAMGerber):
  2622. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2623. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2624. if self.ui.splitter.sizes()[0] == 0:
  2625. self.ui.splitter.setSizes([1, 1])
  2626. self.grb_editor.edit_fcgerber(edited_object)
  2627. # set call source to the Editor we go into
  2628. self.call_source = 'grb_editor'
  2629. # make sure that we can't select another object while in Editor Mode:
  2630. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2631. self.ui.project_frame.setDisabled(True)
  2632. # delete any selection shape that might be active as they are not relevant in Editor
  2633. self.delete_selection_shape()
  2634. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2635. self.ui.plot_tab_area.protectTab(0)
  2636. self.inform.emit('[WARNING_NOTCL] %s' %
  2637. _("Editor is activated ..."))
  2638. self.should_we_save = True
  2639. def editor2object(self, cleanup=None):
  2640. """
  2641. Transfers the Geometry or Excellon from it's editor to the current object.
  2642. :return: None
  2643. """
  2644. self.report_usage("editor2object()")
  2645. # re-enable the objects menu that was disabled on entry in Editor mode
  2646. self.ui.menuobjects.setDisabled(False)
  2647. # do not update a geometry or excellon object unless it comes out of an editor
  2648. if self.call_source != 'app':
  2649. edited_obj = self.collection.get_active()
  2650. if cleanup is None:
  2651. msgbox = QtWidgets.QMessageBox()
  2652. msgbox.setText(_("Do you want to save the edited object?"))
  2653. msgbox.setWindowTitle(_("Close Editor"))
  2654. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2655. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2656. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2657. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2658. msgbox.setDefaultButton(bt_yes)
  2659. msgbox.exec_()
  2660. response = msgbox.clickedButton()
  2661. if response == bt_yes:
  2662. # clean the Tools Tab
  2663. self.ui.tool_scroll_area.takeWidget()
  2664. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2665. self.ui.notebook.setTabText(2, "Tool")
  2666. if isinstance(edited_obj, FlatCAMGeometry):
  2667. obj_type = "Geometry"
  2668. if cleanup is None:
  2669. self.geo_editor.update_fcgeometry(edited_obj)
  2670. self.geo_editor.update_options(edited_obj)
  2671. self.geo_editor.deactivate()
  2672. # update the geo object options so it is including the bounding box values
  2673. try:
  2674. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2675. edited_obj.options['xmin'] = xmin
  2676. edited_obj.options['ymin'] = ymin
  2677. edited_obj.options['xmax'] = xmax
  2678. edited_obj.options['ymax'] = ymax
  2679. except AttributeError as e:
  2680. self.inform.emit('[WARNING] %s' %
  2681. _("Object empty after edit."))
  2682. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2683. elif isinstance(edited_obj, FlatCAMGerber):
  2684. obj_type = "Gerber"
  2685. if cleanup is None:
  2686. self.grb_editor.update_fcgerber()
  2687. self.grb_editor.update_options(edited_obj)
  2688. self.grb_editor.deactivate_grb_editor()
  2689. # delete the old object (the source object) if it was an empty one
  2690. try:
  2691. if len(edited_obj.solid_geometry) == 0:
  2692. old_name = edited_obj.options['name']
  2693. self.collection.set_active(old_name)
  2694. self.collection.delete_active()
  2695. except TypeError:
  2696. # if the solid_geometry is a single Polygon the len() will not work
  2697. # in any case, falling here means that we have something in the solid_geometry, even if only
  2698. # a single Polygon, therefore we pass this
  2699. pass
  2700. # restore GUI to the Selected TAB
  2701. # Remove anything else in the GUI
  2702. self.ui.selected_scroll_area.takeWidget()
  2703. # Switch notebook to Selected page
  2704. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2705. elif isinstance(edited_obj, FlatCAMExcellon):
  2706. obj_type = "Excellon"
  2707. if cleanup is None:
  2708. self.exc_editor.update_fcexcellon(edited_obj)
  2709. self.exc_editor.update_options(edited_obj)
  2710. self.exc_editor.deactivate()
  2711. # delete the old object (the source object) if it was an empty one
  2712. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2713. old_name = edited_obj.options['name']
  2714. self.collection.set_active(old_name)
  2715. self.collection.delete_active()
  2716. # restore GUI to the Selected TAB
  2717. # Remove anything else in the GUI
  2718. self.ui.tool_scroll_area.takeWidget()
  2719. # Switch notebook to Selected page
  2720. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2721. else:
  2722. self.inform.emit('[WARNING_NOTCL] %s' %
  2723. _("Select a Gerber, Geometry or Excellon Object to update."))
  2724. return
  2725. self.inform.emit('[selected] %s %s' %
  2726. (obj_type, _("is updated, returning to App...")))
  2727. elif response == bt_no:
  2728. # clean the Tools Tab
  2729. self.ui.tool_scroll_area.takeWidget()
  2730. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2731. self.ui.notebook.setTabText(2, "Tool")
  2732. if isinstance(edited_obj, FlatCAMGeometry):
  2733. self.geo_editor.deactivate()
  2734. elif isinstance(edited_obj, FlatCAMGerber):
  2735. self.grb_editor.deactivate_grb_editor()
  2736. elif isinstance(edited_obj, FlatCAMExcellon):
  2737. self.exc_editor.deactivate()
  2738. # set focus on the project tab
  2739. else:
  2740. self.inform.emit('[WARNING_NOTCL] %s' %
  2741. _("Select a Gerber, Geometry or Excellon Object to update."))
  2742. return
  2743. edited_obj.set_ui(edited_obj.ui_type())
  2744. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2745. elif response == bt_cancel:
  2746. return
  2747. else:
  2748. if isinstance(edited_obj, FlatCAMGeometry):
  2749. self.geo_editor.deactivate()
  2750. elif isinstance(edited_obj, FlatCAMGerber):
  2751. self.grb_editor.deactivate_grb_editor()
  2752. elif isinstance(edited_obj, FlatCAMExcellon):
  2753. self.exc_editor.deactivate()
  2754. else:
  2755. self.inform.emit('[WARNING_NOTCL] %s' %
  2756. _("Select a Gerber, Geometry or Excellon Object to update."))
  2757. return
  2758. # if notebook is hidden we show it
  2759. if self.ui.splitter.sizes()[0] == 0:
  2760. self.ui.splitter.setSizes([1, 1])
  2761. # restore the call_source to app
  2762. self.call_source = 'app'
  2763. edited_obj.plot()
  2764. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2765. self.ui.plot_tab_area.protectTab(0)
  2766. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2767. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2768. self.ui.project_frame.setDisabled(False)
  2769. def get_last_folder(self):
  2770. """
  2771. Get the folder path from where the last file was opened.
  2772. :return: String, last opened folder path
  2773. """
  2774. return self.defaults["global_last_folder"]
  2775. def get_last_save_folder(self):
  2776. """
  2777. Get the folder path from where the last file was saved.
  2778. :return: String, last saved folder path
  2779. """
  2780. loc = self.defaults["global_last_save_folder"]
  2781. if loc is None:
  2782. loc = self.defaults["global_last_folder"]
  2783. if loc is None:
  2784. loc = os.path.dirname(__file__)
  2785. return loc
  2786. def report_usage(self, resource):
  2787. """
  2788. Increments usage counter for the given resource
  2789. in self.defaults['global_stats'].
  2790. :param resource: Name of the resource.
  2791. :return: None
  2792. """
  2793. if resource in self.defaults['global_stats']:
  2794. self.defaults['global_stats'][resource] += 1
  2795. else:
  2796. self.defaults['global_stats'][resource] = 1
  2797. def init_tcl(self):
  2798. """
  2799. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2800. :return: None
  2801. """
  2802. if hasattr(self, 'tcl') and self.tcl is not None:
  2803. # self.tcl = None
  2804. # TODO we need to clean non default variables and procedures here
  2805. # new object cannot be used here as it will not remember values created for next passes,
  2806. # because tcl was execudted in old instance of TCL
  2807. pass
  2808. else:
  2809. self.tcl = tk.Tcl()
  2810. self.setup_shell()
  2811. self.log.debug("TCL Shell has been initialized.")
  2812. # TODO: This shouldn't be here.
  2813. class TclErrorException(Exception):
  2814. """
  2815. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2816. """
  2817. pass
  2818. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2819. """
  2820. Shows a message on the FlatCAM Shell
  2821. :param msg: Message to display.
  2822. :param show: Opens the shell.
  2823. :param error: Shows the message as an error.
  2824. :param warning: Shows the message as an warning.
  2825. :param success: Shows the message as an success.
  2826. :param selected: Indicate that something was selected on canvas
  2827. :return: None
  2828. """
  2829. if show:
  2830. self.ui.shell_dock.show()
  2831. try:
  2832. if error:
  2833. self.shell.append_error(msg + "\n")
  2834. elif warning:
  2835. self.shell.append_warning(msg + "\n")
  2836. elif success:
  2837. self.shell.append_success(msg + "\n")
  2838. elif selected:
  2839. self.shell.append_selected(msg + "\n")
  2840. else:
  2841. self.shell.append_output(msg + "\n")
  2842. except AttributeError:
  2843. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2844. def raise_tcl_unknown_error(self, unknownException):
  2845. """
  2846. Raise exception if is different type than TclErrorException
  2847. this is here mainly to show unknown errors inside TCL shell console.
  2848. :param unknownException:
  2849. :return:
  2850. """
  2851. if not isinstance(unknownException, self.TclErrorException):
  2852. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2853. else:
  2854. raise unknownException
  2855. def display_tcl_error(self, error, error_info=None):
  2856. """
  2857. Escape bracket [ with '\' otherwise there is error
  2858. "ERROR: missing close-bracket" instead of real error
  2859. :param error: it may be text or exception
  2860. :param error_info: Some informations about the error
  2861. :return: None
  2862. """
  2863. if isinstance(error, Exception):
  2864. exc_type, exc_value, exc_traceback = error_info
  2865. if not isinstance(error, self.TclErrorException):
  2866. show_trace = 1
  2867. else:
  2868. show_trace = int(self.defaults['global_verbose_error_level'])
  2869. if show_trace > 0:
  2870. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2871. trc_formated = []
  2872. for a in reversed(trc):
  2873. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2874. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2875. else:
  2876. text = "%s" % error
  2877. else:
  2878. text = error
  2879. text = text.replace('[', '\\[').replace('"', '\\"')
  2880. self.tcl.eval('return -code error "%s"' % text)
  2881. def raise_tcl_error(self, text):
  2882. """
  2883. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2884. :param text: text of error
  2885. :return: raise exception
  2886. """
  2887. self.display_tcl_error(text)
  2888. raise self.TclErrorException(text)
  2889. def exec_command(self, text, no_echo=False):
  2890. """
  2891. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2892. Also handles execution in separated threads
  2893. :param text: FlatCAM TclCommand with parameters
  2894. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2895. will create crashes of the _Expandable_Edit widget
  2896. :return: output if there was any
  2897. """
  2898. self.report_usage('exec_command')
  2899. result = self.exec_command_test(text, False, no_echo=no_echo)
  2900. # MS: added this method call so the geometry is updated once the TCL command is executed
  2901. # if no_plot is None:
  2902. # self.plot_all()
  2903. return result
  2904. def exec_command_test(self, text, reraise=True, no_echo=False):
  2905. """
  2906. Same as exec_command(...) with additional control over exceptions.
  2907. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2908. :param text: Input command
  2909. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2910. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2911. will create crashes of the _Expandable_Edit widget
  2912. :return: Output from the command
  2913. """
  2914. tcl_command_string = str(text)
  2915. try:
  2916. if no_echo is False:
  2917. self.shell.open_proccessing() # Disables input box.
  2918. result = self.tcl.eval(str(tcl_command_string))
  2919. if result != 'None' and no_echo is False:
  2920. self.shell.append_output(result + '\n')
  2921. except tk.TclError as e:
  2922. # This will display more precise answer if something in TCL shell fails
  2923. result = self.tcl.eval("set errorInfo")
  2924. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2925. if no_echo is False:
  2926. self.shell.append_error('ERROR: ' + result + '\n')
  2927. # Show error in console and just return or in test raise exception
  2928. if reraise:
  2929. raise e
  2930. finally:
  2931. if no_echo is False:
  2932. self.shell.close_proccessing()
  2933. pass
  2934. return result
  2935. # """
  2936. # Code below is unsused. Saved for later.
  2937. # """
  2938. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2939. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2940. # self.log.debug(parts)
  2941. # try:
  2942. # if parts[0] not in commands:
  2943. # self.shell.append_error("Unknown command\n")
  2944. # return
  2945. #
  2946. # #import inspect
  2947. # #inspect.getargspec(someMethod)
  2948. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2949. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2950. # self.shell.append_error(
  2951. # "Command %s takes %d arguments. %d given.\n" %
  2952. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2953. # )
  2954. # return
  2955. #
  2956. # cmdfcn = commands[parts[0]]["fcn"]
  2957. # cmdconv = commands[parts[0]]["converters"]
  2958. # if len(parts) - 1 > 0:
  2959. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2960. # else:
  2961. # retval = cmdfcn()
  2962. # retfcn = commands[parts[0]]["retfcn"]
  2963. # if retval and retfcn(retval):
  2964. # self.shell.append_output(retfcn(retval) + "\n")
  2965. #
  2966. # except Exception as e:
  2967. # #self.shell.append_error(''.join(traceback.format_exc()))
  2968. # #self.shell.append_error("?\n")
  2969. # self.shell.append_error(str(e) + "\n")
  2970. def info(self, msg):
  2971. """
  2972. Informs the user. Normally on the status bar, optionally
  2973. also on the shell.
  2974. :param msg: Text to write.
  2975. :return: None
  2976. """
  2977. # Type of message in brackets at the beginning of the message.
  2978. match = re.search("\[([^\]]+)\](.*)", msg)
  2979. if match:
  2980. level = match.group(1)
  2981. msg_ = match.group(2)
  2982. self.ui.fcinfo.set_status(str(msg_), level=level)
  2983. if level.lower() == "error":
  2984. self.shell_message(msg, error=True, show=True)
  2985. elif level.lower() == "warning":
  2986. self.shell_message(msg, warning=True, show=True)
  2987. elif level.lower() == "error_notcl":
  2988. self.shell_message(msg, error=True, show=False)
  2989. elif level.lower() == "warning_notcl":
  2990. self.shell_message(msg, warning=True, show=False)
  2991. elif level.lower() == "success":
  2992. self.shell_message(msg, success=True, show=False)
  2993. elif level.lower() == "selected":
  2994. self.shell_message(msg, selected=True, show=False)
  2995. else:
  2996. self.shell_message(msg, show=False)
  2997. else:
  2998. self.ui.fcinfo.set_status(str(msg), level="info")
  2999. # make sure that if the message is to clear the infobar with a space
  3000. # is not printed over and over on the shell
  3001. if msg != '':
  3002. self.shell_message(msg)
  3003. def restore_toolbar_view(self):
  3004. """
  3005. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3006. was saved in the defaults dictionary.
  3007. :return: None
  3008. """
  3009. tb = self.defaults["global_toolbar_view"]
  3010. if tb & 1:
  3011. self.ui.toolbarfile.setVisible(True)
  3012. else:
  3013. self.ui.toolbarfile.setVisible(False)
  3014. if tb & 2:
  3015. self.ui.toolbargeo.setVisible(True)
  3016. else:
  3017. self.ui.toolbargeo.setVisible(False)
  3018. if tb & 4:
  3019. self.ui.toolbarview.setVisible(True)
  3020. else:
  3021. self.ui.toolbarview.setVisible(False)
  3022. if tb & 8:
  3023. self.ui.toolbartools.setVisible(True)
  3024. else:
  3025. self.ui.toolbartools.setVisible(False)
  3026. if tb & 16:
  3027. self.ui.exc_edit_toolbar.setVisible(True)
  3028. else:
  3029. self.ui.exc_edit_toolbar.setVisible(False)
  3030. if tb & 32:
  3031. self.ui.geo_edit_toolbar.setVisible(True)
  3032. else:
  3033. self.ui.geo_edit_toolbar.setVisible(False)
  3034. if tb & 64:
  3035. self.ui.grb_edit_toolbar.setVisible(True)
  3036. else:
  3037. self.ui.grb_edit_toolbar.setVisible(False)
  3038. if tb & 128:
  3039. self.ui.snap_toolbar.setVisible(True)
  3040. else:
  3041. self.ui.snap_toolbar.setVisible(False)
  3042. if tb & 256:
  3043. self.ui.toolbarshell.setVisible(True)
  3044. else:
  3045. self.ui.toolbarshell.setVisible(False)
  3046. def load_defaults(self, filename):
  3047. """
  3048. Loads the aplication's default settings from current_defaults.FlatConfig into
  3049. ``self.defaults``.
  3050. :return: None
  3051. """
  3052. try:
  3053. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3054. options = f.read()
  3055. f.close()
  3056. except IOError:
  3057. self.log.error("Could not load defaults file.")
  3058. self.inform.emit('[ERROR] %s' %
  3059. _("Could not load defaults file."))
  3060. # in case the defaults file can't be loaded, show all toolbars
  3061. self.defaults["global_toolbar_view"] = 511
  3062. return
  3063. try:
  3064. defaults = json.loads(options)
  3065. except Exception:
  3066. # in case the defaults file can't be loaded, show all toolbars
  3067. self.defaults["global_toolbar_view"] = 511
  3068. e = sys.exc_info()[0]
  3069. App.log.error(str(e))
  3070. self.inform.emit('[ERROR] %s' % _("Failed to parse defaults file."))
  3071. return
  3072. self.defaults.update(defaults)
  3073. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3074. def on_import_preferences(self):
  3075. """
  3076. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3077. ``self.defaults``.
  3078. :return: None
  3079. """
  3080. self.report_usage("on_import_preferences")
  3081. App.log.debug("on_import_preferences()")
  3082. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3083. try:
  3084. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3085. directory=self.data_path,
  3086. filter=filter_)
  3087. except TypeError:
  3088. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3089. filter=filter_)
  3090. filename = str(filename)
  3091. if filename == "":
  3092. self.inform.emit('[WARNING_NOTCL] %s' %
  3093. _("FlatCAM preferences import cancelled."))
  3094. else:
  3095. try:
  3096. f = open(filename)
  3097. options = f.read()
  3098. f.close()
  3099. except IOError:
  3100. self.log.error("Could not load defaults file.")
  3101. self.inform.emit('[ERROR_NOTCL] %s' %
  3102. _("Could not load defaults file."))
  3103. return
  3104. try:
  3105. defaults_from_file = json.loads(options)
  3106. except Exception:
  3107. e = sys.exc_info()[0]
  3108. App.log.error(str(e))
  3109. self.inform.emit('[ERROR_NOTCL] %s' %
  3110. _("Failed to parse defaults file."))
  3111. return
  3112. self.defaults.update(defaults_from_file)
  3113. self.on_preferences_edited()
  3114. self.inform.emit('[success] %s: %s' %
  3115. (_("Imported Defaults from"), filename))
  3116. def on_export_preferences(self):
  3117. """
  3118. Save the defaults dictionary to a file.
  3119. :return: None
  3120. """
  3121. self.report_usage("on_export_preferences")
  3122. App.log.debug("on_export_preferences()")
  3123. defaults_file_content = None
  3124. self.date = str(datetime.today()).rpartition('.')[0]
  3125. self.date = ''.join(c for c in self.date if c not in ':-')
  3126. self.date = self.date.replace(' ', '_')
  3127. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3128. try:
  3129. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3130. caption=_("Export FlatCAM Preferences"),
  3131. directory=self.data_path + '/preferences_' + self.date,
  3132. filter=filter__
  3133. )
  3134. except TypeError:
  3135. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3136. filter=filter__)
  3137. filename = str(filename)
  3138. defaults_from_file = {}
  3139. if filename == "":
  3140. self.inform.emit('[WARNING_NOTCL] %s' %
  3141. _("FlatCAM preferences export cancelled."))
  3142. return
  3143. else:
  3144. try:
  3145. f = open(filename, 'w')
  3146. defaults_file_content = f.read()
  3147. f.close()
  3148. except PermissionError:
  3149. self.inform.emit('[WARNING] %s' %
  3150. _("Permission denied, saving not possible.\n"
  3151. "Most likely another app is holding the file open and not accessible."))
  3152. return
  3153. except IOError:
  3154. App.log.debug('Creating a new preferences file ...')
  3155. f = open(filename, 'w')
  3156. json.dump({}, f)
  3157. f.close()
  3158. except Exception:
  3159. e = sys.exc_info()[0]
  3160. App.log.error("Could not load defaults file.")
  3161. App.log.error(str(e))
  3162. self.inform.emit('[ERROR_NOTCL] %s' %
  3163. _("Could not load preferences file."))
  3164. return
  3165. try:
  3166. defaults_from_file = json.loads(defaults_file_content)
  3167. except Exception:
  3168. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3169. # Update options
  3170. self.defaults_read_form()
  3171. defaults_from_file.update(self.defaults)
  3172. self.propagate_defaults(silent=True)
  3173. # Save update options
  3174. try:
  3175. f = open(filename, "w")
  3176. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3177. f.close()
  3178. except Exception:
  3179. self.inform.emit('[ERROR_NOTCL] %s' %
  3180. _("Failed to write defaults to file."))
  3181. return
  3182. if self.defaults["global_open_style"] is False:
  3183. self.file_opened.emit("preferences", filename)
  3184. self.file_saved.emit("preferences", filename)
  3185. self.inform.emit('[success] %s: %s' %
  3186. (_("Exported preferences to"), filename))
  3187. def on_preferences_open_folder(self):
  3188. """
  3189. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3190. :return: None
  3191. """
  3192. self.report_usage("on_preferences_open_folder()")
  3193. if sys.platform == 'win32':
  3194. subprocess.Popen('explorer %s' % self.data_path)
  3195. elif sys.platform == 'darwin':
  3196. os.system('open "%s"' % self.data_path)
  3197. else:
  3198. subprocess.Popen(['xdg-open', self.data_path])
  3199. self.inform.emit('[success] %s' %
  3200. _("FlatCAM Preferences Folder opened."))
  3201. def save_geometry(self, x, y, width, height, notebook_width):
  3202. """
  3203. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3204. launch of the application.
  3205. :param x: X position of the main window
  3206. :param y: Y position of the main window
  3207. :param width: width of the main window
  3208. :param height: height of the main window
  3209. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3210. :return: None
  3211. """
  3212. self.defaults["global_def_win_x"] = x
  3213. self.defaults["global_def_win_y"] = y
  3214. self.defaults["global_def_win_w"] = width
  3215. self.defaults["global_def_win_h"] = height
  3216. self.defaults["global_def_notebook_width"] = notebook_width
  3217. self.save_defaults()
  3218. def restore_main_win_geom(self):
  3219. try:
  3220. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3221. self.defaults["global_def_win_y"],
  3222. self.defaults["global_def_win_w"],
  3223. self.defaults["global_def_win_h"])
  3224. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3225. except KeyError as e:
  3226. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3227. def message_dialog(self, title, message, kind="info"):
  3228. """
  3229. Builds and show a custom QMessageBox to be used in FlatCAM.
  3230. :param title: title of the QMessageBox
  3231. :param message: message to be displayed
  3232. :param kind: type of QMessageBox; will display a specific icon.
  3233. :return:
  3234. """
  3235. icon = {"info": QtWidgets.QMessageBox.Information,
  3236. "warning": QtWidgets.QMessageBox.Warning,
  3237. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3238. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3239. dlg.setText(message)
  3240. dlg.exec_()
  3241. def register_recent(self, kind, filename):
  3242. """
  3243. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3244. dictionary.
  3245. :param kind: type of file that was opened
  3246. :param filename: the path and file name for the file that was opened
  3247. :return:
  3248. """
  3249. self.log.debug("register_recent()")
  3250. self.log.debug(" %s" % kind)
  3251. self.log.debug(" %s" % filename)
  3252. record = {'kind': str(kind), 'filename': str(filename)}
  3253. if record in self.recent:
  3254. return
  3255. if record in self.recent_projects:
  3256. return
  3257. if record['kind'] == 'project':
  3258. self.recent_projects.insert(0, record)
  3259. else:
  3260. self.recent.insert(0, record)
  3261. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3262. self.recent.pop()
  3263. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3264. self.recent_projects.pop()
  3265. try:
  3266. f = open(self.data_path + '/recent.json', 'w')
  3267. except IOError:
  3268. App.log.error("Failed to open recent items file for writing.")
  3269. self.inform.emit('[ERROR_NOTCL] %s' %
  3270. _('Failed to open recent files file for writing.'))
  3271. return
  3272. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3273. f.close()
  3274. try:
  3275. fp = open(self.data_path + '/recent_projects.json', 'w')
  3276. except IOError:
  3277. App.log.error("Failed to open recent items file for writing.")
  3278. self.inform.emit('[ERROR_NOTCL] %s' %
  3279. _('Failed to open recent projects file for writing.'))
  3280. return
  3281. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3282. fp.close()
  3283. # Re-build the recent items menu
  3284. self.setup_recent_items()
  3285. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3286. """
  3287. Creates a new specialized FlatCAMObj and attaches it to the application,
  3288. this is, updates the GUI accordingly, any other records and plots it.
  3289. This method is thread-safe.
  3290. Notes:
  3291. * If the name is in use, the self.collection will modify it
  3292. when appending it to the collection. There is no need to handle
  3293. name conflicts here.
  3294. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3295. :type kind: str
  3296. :param name: Name for the object.
  3297. :type name: str
  3298. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3299. The function is called with 2 parameters: the new object and the App instance.
  3300. :type initialize: function
  3301. :param active:
  3302. :param fit:
  3303. :param plot: If to plot the resulting object
  3304. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3305. self.colleaction
  3306. :return: None
  3307. :rtype: None
  3308. """
  3309. App.log.debug("new_object()")
  3310. obj_plot = plot
  3311. obj_autoselected = autoselected
  3312. t0 = time.time() # Debug
  3313. # ## Create object
  3314. classdict = {
  3315. "gerber": FlatCAMGerber,
  3316. "excellon": FlatCAMExcellon,
  3317. "cncjob": FlatCAMCNCjob,
  3318. "geometry": FlatCAMGeometry,
  3319. "script": FlatCAMScript,
  3320. "document": FlatCAMDocument
  3321. }
  3322. App.log.debug("Calling object constructor...")
  3323. # Object creation/instantiation
  3324. obj = classdict[kind](name)
  3325. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3326. # IMPORTANT
  3327. # The key names in defaults and options dictionary's are not random:
  3328. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3329. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  3330. # copied to self.options. After that, below, depending on the type of
  3331. # object that is created, it will strip the name of the object and the underline (if the original key was
  3332. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3333. # "toolchange"
  3334. for option in self.options:
  3335. if option.find(kind + "_") == 0:
  3336. oname = option[len(kind) + 1:]
  3337. obj.options[oname] = self.options[option]
  3338. obj.isHovering = False
  3339. obj.notHovering = True
  3340. # Initialize as per user request
  3341. # User must take care to implement initialize
  3342. # in a thread-safe way as is is likely that we
  3343. # have been invoked in a separate thread.
  3344. t1 = time.time()
  3345. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3346. try:
  3347. return_value = initialize(obj, self)
  3348. except Exception as e:
  3349. msg = '[ERROR_NOTCL] %s' % \
  3350. _("An internal error has ocurred. See shell.\n")
  3351. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3352. msg += traceback.format_exc()
  3353. self.inform.emit(msg)
  3354. # if str(e) == "Empty Geometry":
  3355. # self.inform.emit("[ERROR_NOTCL] )
  3356. # else:
  3357. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3358. return "fail"
  3359. t2 = time.time()
  3360. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3361. if return_value == 'fail':
  3362. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3363. return "fail"
  3364. # Check units and convert if necessary
  3365. # This condition CAN be true because initialize() can change obj.units
  3366. if self.options["units"].upper() != obj.units.upper():
  3367. self.inform.emit('%s: %s' %
  3368. (_("Converting units to "), self.options["units"]))
  3369. obj.convert_units(self.options["units"])
  3370. t3 = time.time()
  3371. self.log.debug("%f seconds converting units." % (t3 - t2))
  3372. # Create the bounding box for the object and then add the results to the obj.options
  3373. # But not for Scripts or for Documents
  3374. if kind != 'document' and kind != 'script':
  3375. try:
  3376. xmin, ymin, xmax, ymax = obj.bounds()
  3377. obj.options['xmin'] = xmin
  3378. obj.options['ymin'] = ymin
  3379. obj.options['xmax'] = xmax
  3380. obj.options['ymax'] = ymax
  3381. except Exception as e:
  3382. log.warning("The object has no bounds properties. %s" % str(e))
  3383. return "fail"
  3384. # update the KeyWords list with the name of the file
  3385. self.myKeywords.append(obj.options['name'])
  3386. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3387. # Move the object to the main thread and let the app know that it is available.
  3388. obj.moveToThread(self.main_thread)
  3389. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3390. return obj
  3391. def new_excellon_object(self):
  3392. """
  3393. Creates a new, blank Excellon object.
  3394. :return: None
  3395. """
  3396. self.report_usage("new_excellon_object()")
  3397. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3398. def new_geometry_object(self):
  3399. """
  3400. Creates a new, blank and single-tool Geometry object.
  3401. :return: None
  3402. """
  3403. self.report_usage("new_geometry_object()")
  3404. def initialize(obj, app):
  3405. obj.multitool = False
  3406. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3407. def new_gerber_object(self):
  3408. """
  3409. Creates a new, blank Gerber object.
  3410. :return: None
  3411. """
  3412. self.report_usage("new_gerber_object()")
  3413. def initialize(grb_obj, app):
  3414. grb_obj.multitool = False
  3415. grb_obj.source_file = []
  3416. grb_obj.multigeo = False
  3417. grb_obj.follow = False
  3418. grb_obj.apertures = {}
  3419. grb_obj.solid_geometry = []
  3420. try:
  3421. grb_obj.options['xmin'] = 0
  3422. grb_obj.options['ymin'] = 0
  3423. grb_obj.options['xmax'] = 0
  3424. grb_obj.options['ymax'] = 0
  3425. except KeyError:
  3426. pass
  3427. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3428. def new_script_object(self, name=None, text=None):
  3429. """
  3430. Creates a new, blank TCL Script object.
  3431. :param name: a name for the new object
  3432. :param text: pass a source file to the newly created script to be loaded in it
  3433. :return: None
  3434. """
  3435. self.report_usage("new_script_object()")
  3436. if text is not None:
  3437. new_source_file = text
  3438. else:
  3439. new_source_file = _(
  3440. "#\n"
  3441. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  3442. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  3443. "#\n\n"
  3444. "# FlatCAM commands list:\n"
  3445. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, "
  3446. "ClearCopper,\n"
  3447. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, "
  3448. "GetNames,\n"
  3449. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  3450. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  3451. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, "
  3452. "SubtractPoly,\n"
  3453. "# SubtractRectangle, Version, WriteGCode\n"
  3454. "#\n\n"
  3455. )
  3456. def initialize(obj, app):
  3457. obj.source_file = deepcopy(new_source_file)
  3458. if name is None:
  3459. outname = 'new_script'
  3460. else:
  3461. outname = name
  3462. self.new_object('script', outname, initialize, plot=False)
  3463. def new_document_object(self):
  3464. """
  3465. Creates a new, blank Document object.
  3466. :return: None
  3467. """
  3468. self.report_usage("new_document_object()")
  3469. def initialize(obj, app):
  3470. obj.source_file = ""
  3471. self.new_object('document', 'new_document', initialize, plot=False)
  3472. def on_object_created(self, obj, plot, auto_select):
  3473. """
  3474. Event callback for object creation.
  3475. It will add the new object to the collection. After that it will plot the object in a threaded way
  3476. :param obj: The newly created FlatCAM object.
  3477. :param plot: if the newly create object t obe plotted
  3478. :param auto_select: if the newly created object to be autoselected after creation
  3479. :return: None
  3480. """
  3481. t0 = time.time() # DEBUG
  3482. self.log.debug("on_object_created()")
  3483. # The Collection might change the name if there is a collision
  3484. self.collection.append(obj)
  3485. # after adding the object to the collection always update the list of objects that are in the collection
  3486. self.all_objects_list = self.collection.get_list()
  3487. # self.inform.emit('[selected] %s created & selected: %s' %
  3488. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3489. if obj.kind == 'gerber':
  3490. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3491. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3492. elif obj.kind == 'excellon':
  3493. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3494. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3495. elif obj.kind == 'cncjob':
  3496. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3497. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3498. elif obj.kind == 'geometry':
  3499. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3500. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3501. elif obj.kind == 'script':
  3502. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3503. kind=obj.kind.capitalize(), color='orange', name=str(obj.options['name'])))
  3504. elif obj.kind == 'document':
  3505. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3506. kind=obj.kind.capitalize(), color='darkCyan', name=str(obj.options['name'])))
  3507. # update the SHELL auto-completer model with the name of the new object
  3508. self.shell._edit.set_model_data(self.myKeywords)
  3509. if auto_select:
  3510. # select the just opened object but deselect the previous ones
  3511. self.collection.set_all_inactive()
  3512. self.collection.set_active(obj.options["name"])
  3513. else:
  3514. self.collection.set_all_inactive()
  3515. # here it is done the object plotting
  3516. def worker_task(t_obj):
  3517. with self.proc_container.new(_("Plotting")):
  3518. if isinstance(t_obj, FlatCAMCNCjob):
  3519. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3520. else:
  3521. t_obj.plot()
  3522. t1 = time.time() # DEBUG
  3523. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3524. self.object_plotted.emit(t_obj)
  3525. # Send to worker
  3526. # self.worker.add_task(worker_task, [self])
  3527. if plot is True:
  3528. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3529. def on_object_changed(self, obj):
  3530. """
  3531. Called whenever the geometry of the object was changed in some way.
  3532. This require the update of it's bounding values so it can be the selected on canvas.
  3533. Update the bounding box data from obj.options
  3534. :param obj: the object that was changed
  3535. :return: None
  3536. """
  3537. xmin, ymin, xmax, ymax = obj.bounds()
  3538. obj.options['xmin'] = xmin
  3539. obj.options['ymin'] = ymin
  3540. obj.options['xmax'] = xmax
  3541. obj.options['ymax'] = ymax
  3542. log.debug("Object changed, updating the bounding box data on self.options")
  3543. # delete the old selection shape
  3544. self.delete_selection_shape()
  3545. self.should_we_save = True
  3546. def on_object_plotted(self):
  3547. """
  3548. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3549. :return: None
  3550. """
  3551. self.on_zoom_fit(None)
  3552. def on_about(self):
  3553. """
  3554. Displays the "about" dialog found in the Menu --> Help.
  3555. :return: None
  3556. """
  3557. self.report_usage("on_about")
  3558. version = self.version
  3559. version_date = self.version_date
  3560. beta = self.beta
  3561. class AboutDialog(QtWidgets.QDialog):
  3562. def __init__(self, parent=None):
  3563. QtWidgets.QDialog.__init__(self, parent)
  3564. # Icon and title
  3565. self.setWindowIcon(parent.app_icon)
  3566. self.setWindowTitle(_("About FlatCAM"))
  3567. self.resize(600, 200)
  3568. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3569. # self.setStyleSheet(
  3570. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3571. # "background-attachment: fixed"
  3572. # )
  3573. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3574. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3575. # palette = QtGui.QPalette()
  3576. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3577. # self.setPalette(palette)
  3578. logo = QtWidgets.QLabel()
  3579. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3580. title = QtWidgets.QLabel(
  3581. "<font size=8><B>FlatCAM</B></font><BR>"
  3582. "{title}<BR>"
  3583. "<BR>"
  3584. "<BR>"
  3585. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3586. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3587. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3588. "<B>{issue}</B></a><BR>".format(
  3589. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3590. devel=_("Development"),
  3591. down=_("DOWNLOAD"),
  3592. issue=_("Issue tracker"))
  3593. )
  3594. title.setOpenExternalLinks(True)
  3595. closebtn = QtWidgets.QPushButton(_("Close"))
  3596. tab_widget = QtWidgets.QTabWidget()
  3597. description_label = QtWidgets.QLabel(
  3598. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3599. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3600. version=version,
  3601. beta=('BETA' if beta else ''),
  3602. date=version_date,
  3603. arch=platform.architecture()[0])
  3604. )
  3605. description_label.setOpenExternalLinks(True)
  3606. lic_lbl_header = QtWidgets.QLabel(
  3607. '%s:<br>%s<br>' % (
  3608. _('Licensed under the MIT license'),
  3609. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3610. "http://www.opensource.org/licenses/mit-license.php</a>"
  3611. )
  3612. )
  3613. lic_lbl_header.setOpenExternalLinks(True)
  3614. lic_lbl_body = QtWidgets.QLabel(
  3615. _(
  3616. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3617. 'of this software and associated documentation files (the "Software"), to deal\n'
  3618. 'in the Software without restriction, including without limitation the rights\n'
  3619. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3620. 'copies of the Software, and to permit persons to whom the Software is\n'
  3621. 'furnished to do so, subject to the following conditions:\n\n'
  3622. 'The above copyright notice and this permission notice shall be included in\n'
  3623. 'all copies or substantial portions of the Software.\n\n'
  3624. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3625. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3626. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3627. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3628. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3629. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3630. 'THE SOFTWARE.'
  3631. )
  3632. )
  3633. attributions_label = QtWidgets.QLabel(
  3634. _(
  3635. 'Some of the icons used are from the following sources:<br>'
  3636. '<div>Icons made by <a href="https://www.flaticon.com/authors/freepik" '
  3637. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3638. 'title="Flaticon">www.flaticon.com</a></div>'
  3639. 'Icons by <a target="_blank" href="https://icons8.com">Icons8</a>'
  3640. )
  3641. )
  3642. # layouts
  3643. layout1 = QtWidgets.QVBoxLayout()
  3644. layout1_1 = QtWidgets.QHBoxLayout()
  3645. layout1_2 = QtWidgets.QHBoxLayout()
  3646. layout2 = QtWidgets.QHBoxLayout()
  3647. layout3 = QtWidgets.QHBoxLayout()
  3648. self.setLayout(layout1)
  3649. layout1.addLayout(layout1_1)
  3650. layout1.addLayout(layout1_2)
  3651. layout1.addLayout(layout2)
  3652. layout1.addLayout(layout3)
  3653. layout1_1.addStretch()
  3654. layout1_1.addWidget(description_label)
  3655. layout1_2.addWidget(tab_widget)
  3656. self.splash_tab = QtWidgets.QWidget()
  3657. self.splash_tab.setObjectName("splash_about")
  3658. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3659. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3660. tab_widget.addTab(self.splash_tab, _("Splash"))
  3661. self.programmmers_tab = QtWidgets.QWidget()
  3662. self.programmmers_tab.setObjectName("programmers_about")
  3663. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3664. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3665. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3666. self.translators_tab = QtWidgets.QWidget()
  3667. self.translators_tab.setObjectName("translators_about")
  3668. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3669. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3670. tab_widget.addTab(self.translators_tab, _("Translators"))
  3671. self.license_tab = QtWidgets.QWidget()
  3672. self.license_tab.setObjectName("license_about")
  3673. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3674. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3675. tab_widget.addTab(self.license_tab, _("License"))
  3676. self.attributions_tab = QtWidgets.QWidget()
  3677. self.attributions_tab.setObjectName("attributions_about")
  3678. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3679. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3680. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3681. self.splash_tab_layout.addWidget(logo, stretch=0)
  3682. self.splash_tab_layout.addWidget(title, stretch=1)
  3683. pal = QtGui.QPalette()
  3684. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3685. self.prog_grid_lay = QtWidgets.QGridLayout()
  3686. self.prog_grid_lay.setHorizontalSpacing(20)
  3687. self.prog_grid_lay.setColumnStretch(0, 0)
  3688. self.prog_grid_lay.setColumnStretch(2, 1)
  3689. prog_widget = QtWidgets.QWidget()
  3690. prog_widget.setLayout(self.prog_grid_lay)
  3691. prog_scroll = QtWidgets.QScrollArea()
  3692. prog_scroll.setWidget(prog_widget)
  3693. prog_scroll.setWidgetResizable(True)
  3694. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3695. prog_scroll.setPalette(pal)
  3696. self.programmmers_tab_layout.addWidget(prog_scroll)
  3697. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3698. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3702. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3703. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3704. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3705. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3706. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3707. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3708. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3709. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3710. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3711. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3712. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  3713. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  3714. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  3715. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  3716. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  3717. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  3718. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  3719. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  3720. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  3721. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  3722. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  3723. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  3724. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  3725. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  3726. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  3727. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  3728. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  3729. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  3730. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  3731. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  3732. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 28, 0)
  3733. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 29, 0)
  3734. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 30, 0)
  3735. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 31, 0)
  3736. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 32, 0)
  3737. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 33, 0)
  3738. self.translator_grid_lay = QtWidgets.QGridLayout()
  3739. self.translator_grid_lay.setColumnStretch(0, 0)
  3740. self.translator_grid_lay.setColumnStretch(1, 0)
  3741. self.translator_grid_lay.setColumnStretch(2, 1)
  3742. self.translator_grid_lay.setColumnStretch(3, 0)
  3743. # trans_widget = QtWidgets.QWidget()
  3744. # trans_widget.setLayout(self.translator_grid_lay)
  3745. # self.translators_tab_layout.addWidget(trans_widget)
  3746. # self.translators_tab_layout.addStretch()
  3747. trans_widget = QtWidgets.QWidget()
  3748. trans_widget.setLayout(self.translator_grid_lay)
  3749. trans_scroll = QtWidgets.QScrollArea()
  3750. trans_scroll.setWidget(trans_widget)
  3751. trans_scroll.setWidgetResizable(True)
  3752. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3753. trans_scroll.setPalette(pal)
  3754. self.translators_tab_layout.addWidget(trans_scroll)
  3755. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3756. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3757. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  3758. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  3759. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  3760. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3761. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  3762. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3763. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 2, 1)
  3764. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 2, 2)
  3765. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  3766. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3767. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3768. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt"), 3, 2)
  3769. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  3770. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3771. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3772. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  3773. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3774. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3775. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  3776. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3777. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  3778. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 6, 2)
  3779. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  3780. self.translator_grid_lay.setColumnStretch(0, 0)
  3781. self.translators_tab_layout.addStretch()
  3782. self.license_tab_layout.addWidget(lic_lbl_header)
  3783. self.license_tab_layout.addWidget(lic_lbl_body)
  3784. self.license_tab_layout.addStretch()
  3785. self.attributions_tab_layout.addWidget(attributions_label)
  3786. self.attributions_tab_layout.addStretch()
  3787. layout3.addStretch()
  3788. layout3.addWidget(closebtn)
  3789. closebtn.clicked.connect(self.accept)
  3790. AboutDialog(self.ui).exec_()
  3791. def install_bookmarks(self, book_dict=None):
  3792. """
  3793. Install the bookmarks actions in the Help menu -> Bookmarks
  3794. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  3795. :return: None
  3796. """
  3797. if book_dict is None:
  3798. self.defaults["global_bookmarks"].update(
  3799. {
  3800. '1': ['FlatCAM', "http://flatcam.org"],
  3801. '2': ['Backup Site', ""]
  3802. }
  3803. )
  3804. else:
  3805. self.defaults["global_bookmarks"].clear()
  3806. self.defaults["global_bookmarks"].update(book_dict)
  3807. # first try to disconnect if somehow they get connected from elsewhere
  3808. for act in self.ui.menuhelp_bookmarks.actions():
  3809. try:
  3810. act.triggered.disconnect()
  3811. except TypeError:
  3812. pass
  3813. # clear all actions except the last one who is the Bookmark manager
  3814. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  3815. pass
  3816. else:
  3817. self.ui.menuhelp_bookmarks.removeAction(act)
  3818. bm_limit = int(self.defaults["global_bookmarks_limit"])
  3819. if self.defaults["global_bookmarks"]:
  3820. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  3821. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  3822. # the JSON is first making the keys as strings (therefore I have to use strings too
  3823. # or do the conversion :(
  3824. # )
  3825. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  3826. # the '10' entry jsut after '1' therefore ordering as strings
  3827. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  3828. key=lambda x: int(x[0]))
  3829. for entry, bookmark in sorted_bookmarks:
  3830. title = bookmark[0]
  3831. weblink = bookmark[1]
  3832. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  3833. act.setText(title)
  3834. act.setIcon(QtGui.QIcon('share/link16.png'))
  3835. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  3836. if title == 'Backup Site' and weblink == "":
  3837. act.triggered.connect(self.on_backup_site)
  3838. else:
  3839. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  3840. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  3841. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  3842. def on_bookmarks_manager(self):
  3843. """
  3844. Adds the bookmark manager in a Tab in Plot Area
  3845. :return:
  3846. """
  3847. for idx in range(self.ui.plot_tab_area.count()):
  3848. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  3849. # there can be only one instance of Bookmark Manager at one time
  3850. return
  3851. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  3852. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  3853. # add the tab if it was closed
  3854. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  3855. # delete the absolute and relative position and messages in the infobar
  3856. self.ui.position_label.setText("")
  3857. self.ui.rel_position_label.setText("")
  3858. # Switch plot_area to preferences page
  3859. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  3860. @staticmethod
  3861. def on_backup_site():
  3862. msgbox = QtWidgets.QMessageBox()
  3863. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  3864. "1. FlatCAM.org website is down\n"
  3865. "2. Someone forked FlatCAM project and wants to point\n"
  3866. "to his own website\n\n"
  3867. "If you can't get any informations about FlatCAM beta\n"
  3868. "use the YouTube channel link from the Help menu."))
  3869. msgbox.setWindowTitle(_("Alternative website"))
  3870. msgbox.setWindowIcon(QtGui.QIcon('share/globe16.png'))
  3871. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  3872. msgbox.setDefaultButton(bt_yes)
  3873. msgbox.exec_()
  3874. # response = msgbox.clickedButton()
  3875. def on_file_savedefaults(self):
  3876. """
  3877. Callback for menu item File->Save Defaults. Saves application default options
  3878. ``self.defaults`` to current_defaults.FlatConfig.
  3879. :return: None
  3880. """
  3881. self.save_defaults()
  3882. # def on_app_exit(self):
  3883. # self.report_usage("on_app_exit()")
  3884. #
  3885. # if self.collection.get_list():
  3886. # msgbox = QtWidgets.QMessageBox()
  3887. # # msgbox.setText("<B>Save changes ...</B>")
  3888. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3889. # "\n"
  3890. # "Do you want to Save the project?")
  3891. # msgbox.setWindowTitle("Save changes")
  3892. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3893. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3894. # QtWidgets.QMessageBox.Cancel)
  3895. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3896. #
  3897. # response = msgbox.exec_()
  3898. #
  3899. # if response == QtWidgets.QMessageBox.Yes:
  3900. # self.on_file_saveprojectas(thread=False)
  3901. # elif response == QtWidgets.QMessageBox.Cancel:
  3902. # return
  3903. # self.save_defaults()
  3904. # else:
  3905. # self.save_defaults()
  3906. # log.debug("Application defaults saved ... Exit event.")
  3907. # QtWidgets.qApp.quit()
  3908. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3909. """
  3910. Saves application default options
  3911. ``self.defaults`` to current_defaults.FlatConfig file.
  3912. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3913. used at the next launch of the application.
  3914. :param silent: whether to display a message in status bar or not; boolean
  3915. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3916. When the application is portable it should be a mobile location.
  3917. :return: None
  3918. """
  3919. self.report_usage("save_defaults")
  3920. if data_path is None:
  3921. data_path = self.data_path
  3922. # Read options from file
  3923. try:
  3924. f = open(data_path + "/current_defaults.FlatConfig")
  3925. defaults_file_content = f.read()
  3926. f.close()
  3927. except Exception:
  3928. e = sys.exc_info()[0]
  3929. App.log.error("Could not load defaults file.")
  3930. App.log.error(str(e))
  3931. self.inform.emit('[ERROR_NOTCL] %s' %
  3932. _("Could not load defaults file."))
  3933. return
  3934. try:
  3935. defaults = json.loads(defaults_file_content)
  3936. except Exception:
  3937. e = sys.exc_info()[0]
  3938. App.log.error("Failed to parse defaults file.")
  3939. App.log.error(str(e))
  3940. self.inform.emit('[ERROR_NOTCL] %s' %
  3941. _("Failed to parse defaults file."))
  3942. return
  3943. # Update options
  3944. self.defaults_read_form()
  3945. defaults.update(self.defaults)
  3946. self.propagate_defaults(silent=True)
  3947. # Save the toolbar view
  3948. tb_status = 0
  3949. if self.ui.toolbarfile.isVisible():
  3950. tb_status += 1
  3951. if self.ui.toolbargeo.isVisible():
  3952. tb_status += 2
  3953. if self.ui.toolbarview.isVisible():
  3954. tb_status += 4
  3955. if self.ui.toolbartools.isVisible():
  3956. tb_status += 8
  3957. if self.ui.exc_edit_toolbar.isVisible():
  3958. tb_status += 16
  3959. if self.ui.geo_edit_toolbar.isVisible():
  3960. tb_status += 32
  3961. if self.ui.grb_edit_toolbar.isVisible():
  3962. tb_status += 64
  3963. if self.ui.snap_toolbar.isVisible():
  3964. tb_status += 128
  3965. if self.ui.toolbarshell.isVisible():
  3966. tb_status += 256
  3967. if first_time is False:
  3968. self.defaults["global_toolbar_view"] = tb_status
  3969. # Save update options
  3970. try:
  3971. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3972. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3973. f.close()
  3974. except Exception as e:
  3975. log.debug("App.save_defaults() --> %s" % str(e))
  3976. self.inform.emit(f'[ERROR_NOTCL] {_("Failed to write defaults to file.")}')
  3977. return
  3978. if not silent:
  3979. self.inform.emit(f'[success] {_("Preferences saved.")}')
  3980. def save_factory_defaults(self, silent_message=False, data_path=None):
  3981. """
  3982. Saves application factory default options
  3983. ``self.defaults`` to factory_defaults.FlatConfig.
  3984. It's a one time job done just after the first install.
  3985. :param silent_message: whether to display a message in status bar or not; boolean
  3986. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3987. When the application is portable it should be a mobile location.
  3988. :return: None
  3989. """
  3990. self.report_usage("save_factory_defaults")
  3991. if data_path is None:
  3992. data_path = self.data_path
  3993. # Read options from file
  3994. try:
  3995. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3996. factory_defaults_file_content = f_f_def.read()
  3997. f_f_def.close()
  3998. except Exception:
  3999. e = sys.exc_info()[0]
  4000. App.log.error("Could not load factory defaults file.")
  4001. App.log.error(str(e))
  4002. self.inform.emit(f'[ERROR_NOTCL] {_("Could not load factory defaults file.")}')
  4003. return
  4004. try:
  4005. factory_defaults = json.loads(factory_defaults_file_content)
  4006. except Exception:
  4007. e = sys.exc_info()[0]
  4008. App.log.error("Failed to parse factory defaults file.")
  4009. App.log.error(str(e))
  4010. self.inform.emit(f'[ERROR_NOTCL] {_("Failed to parse factory defaults file.")}')
  4011. return
  4012. # Update options
  4013. self.defaults_read_form()
  4014. factory_defaults.update(self.defaults)
  4015. self.propagate_defaults(silent=True)
  4016. # Save update options
  4017. try:
  4018. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4019. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4020. f_f_def_s.close()
  4021. except Exception as e:
  4022. log.debug(f"App.save_factory_default() save update --> {str(e)}")
  4023. self.inform.emit(f'[ERROR_NOTCL] {_("Failed to write factory defaults to file.")}')
  4024. return
  4025. if silent_message is False:
  4026. self.inform.emit(f'{_("Factory defaults saved.")}')
  4027. def final_save(self):
  4028. """
  4029. Callback for doing a preferences save to file whenever the application is about to quit.
  4030. If the project has changes, it will ask the user to save the project.
  4031. :return: None
  4032. """
  4033. if self.save_in_progress:
  4034. self.inform.emit(f'[WARNING_NOTCL] {_("Application is saving the project. Please wait ...")}')
  4035. return
  4036. if self.should_we_save and self.collection.get_list():
  4037. msgbox = QtWidgets.QMessageBox()
  4038. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4039. "\n"
  4040. "Do you want to Save the project?"))
  4041. msgbox.setWindowTitle(_("Save changes"))
  4042. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4043. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4044. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4045. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4046. msgbox.setDefaultButton(bt_yes)
  4047. msgbox.exec_()
  4048. response = msgbox.clickedButton()
  4049. if response == bt_yes:
  4050. try:
  4051. self.trayIcon.hide()
  4052. except Exception:
  4053. pass
  4054. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4055. elif response == bt_no:
  4056. try:
  4057. self.trayIcon.hide()
  4058. except Exception:
  4059. pass
  4060. self.quit_application()
  4061. elif response == bt_cancel:
  4062. return
  4063. else:
  4064. try:
  4065. self.trayIcon.hide()
  4066. except Exception:
  4067. pass
  4068. self.quit_application()
  4069. def quit_application(self):
  4070. """
  4071. Called (as a pyslot or not) when the application is quit.
  4072. :return: None
  4073. """
  4074. self.save_defaults()
  4075. log.debug("App.final_save() --> App Defaults saved.")
  4076. if self.cmd_line_headless != 1:
  4077. # save app state to file
  4078. stgs = QSettings("Open Source", "FlatCAM")
  4079. stgs.setValue('saved_gui_state', self.ui.saveState())
  4080. stgs.setValue('maximized_gui', self.ui.isMaximized())
  4081. stgs.setValue(
  4082. 'language',
  4083. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  4084. )
  4085. stgs.setValue(
  4086. 'notebook_font_size',
  4087. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4088. )
  4089. stgs.setValue(
  4090. 'axis_font_size',
  4091. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4092. )
  4093. stgs.setValue(
  4094. 'textbox_font_size',
  4095. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4096. )
  4097. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4098. stgs.setValue(
  4099. 'machinist',
  4100. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  4101. )
  4102. # This will write the setting to the platform specific storage.
  4103. del stgs
  4104. log.debug("App.final_save() --> App UI state saved.")
  4105. QtWidgets.qApp.quit()
  4106. def on_portable_checked(self, state):
  4107. """
  4108. Callback called when the checkbox in Preferences GUI is checked.
  4109. It will set the application as portable by creating the preferences and recent files in the
  4110. 'config' folder found in the FlatCAM installation folder.
  4111. :param state: boolean, the state of the checkbox when clicked/checked
  4112. :return:
  4113. """
  4114. line_no = 0
  4115. data = None
  4116. if sys.platform != 'win32':
  4117. # this won't work in Linux or MacOS
  4118. return
  4119. # test if the app was frozen and choose the path for the configuration file
  4120. if getattr(sys, "frozen", False) is True:
  4121. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4122. else:
  4123. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4124. config_file = current_data_path + '\\configuration.txt'
  4125. try:
  4126. with open(config_file, 'r') as f:
  4127. try:
  4128. data = f.readlines()
  4129. except Exception as e:
  4130. log.debug('App.__init__() -->%s' % str(e))
  4131. return
  4132. except FileNotFoundError:
  4133. pass
  4134. for line in data:
  4135. line = line.strip('\n')
  4136. param = str(line).rpartition('=')
  4137. if param[0] == 'portable':
  4138. break
  4139. line_no += 1
  4140. if state:
  4141. data[line_no] = 'portable=True\n'
  4142. # create the new defauults files
  4143. # create current_defaults.FlatConfig file if there is none
  4144. try:
  4145. f = open(current_data_path + '/current_defaults.FlatConfig')
  4146. f.close()
  4147. except IOError:
  4148. App.log.debug('Creating empty current_defaults.FlatConfig')
  4149. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4150. json.dump({}, f)
  4151. f.close()
  4152. # create factory_defaults.FlatConfig file if there is none
  4153. try:
  4154. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4155. f.close()
  4156. except IOError:
  4157. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4158. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4159. json.dump({}, f)
  4160. f.close()
  4161. try:
  4162. f = open(current_data_path + '/recent.json')
  4163. f.close()
  4164. except IOError:
  4165. App.log.debug('Creating empty recent.json')
  4166. f = open(current_data_path + '/recent.json', 'w')
  4167. json.dump([], f)
  4168. f.close()
  4169. try:
  4170. fp = open(current_data_path + '/recent_projects.json')
  4171. fp.close()
  4172. except IOError:
  4173. App.log.debug('Creating empty recent_projects.json')
  4174. fp = open(current_data_path + '/recent_projects.json', 'w')
  4175. json.dump([], fp)
  4176. fp.close()
  4177. # save the current defaults to the new defaults file
  4178. self.save_defaults(silent=True, data_path=current_data_path)
  4179. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4180. else:
  4181. data[line_no] = 'portable=False\n'
  4182. with open(config_file, 'w') as f:
  4183. f.writelines(data)
  4184. def on_toggle_shell(self):
  4185. """
  4186. Toggle shell: if is visible close it, if it is closed then open it
  4187. :return: None
  4188. """
  4189. self.report_usage("on_toggle_shell()")
  4190. if self.ui.shell_dock.isVisible():
  4191. self.ui.shell_dock.hide()
  4192. else:
  4193. self.ui.shell_dock.show()
  4194. def on_register_files(self, obj_type=None):
  4195. """
  4196. Called whenever there is a need to register file extensions with FlatCAM.
  4197. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4198. :param obj_type: the type of object to be register for.
  4199. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4200. :return: None
  4201. """
  4202. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4203. new_reg_path = 'Software\\Classes\\'
  4204. # find if the current user is admin
  4205. try:
  4206. is_admin = os.getuid() == 0
  4207. except AttributeError:
  4208. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4209. if is_admin is True:
  4210. root_path = winreg.HKEY_LOCAL_MACHINE
  4211. else:
  4212. root_path = winreg.HKEY_CURRENT_USER
  4213. # create the keys
  4214. def set_reg(name, root_path, new_reg_path, value):
  4215. try:
  4216. winreg.CreateKey(root_path, new_reg_path)
  4217. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4218. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4219. return True
  4220. except WindowsError:
  4221. return False
  4222. # delete key in registry
  4223. def delete_reg(root_path, reg_path, key_to_del):
  4224. key_to_del_path = reg_path + key_to_del
  4225. try:
  4226. winreg.DeleteKey(root_path, key_to_del_path)
  4227. return True
  4228. except WindowsError:
  4229. return False
  4230. if obj_type is None or obj_type == 'excellon':
  4231. exc_list = \
  4232. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4233. exc_list = [x for x in exc_list if x != '']
  4234. # register all keys in the Preferences window
  4235. for ext in exc_list:
  4236. new_k = new_reg_path + '.%s' % ext
  4237. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4238. # and unregister those that are no longer in the Preferences windows but are in the file
  4239. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4240. if ext not in exc_list:
  4241. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4242. # now write the updated extensions to the self.defaults
  4243. # new_ext = ''
  4244. # for ext in exc_list:
  4245. # new_ext = new_ext + ext + ', '
  4246. # self.defaults["fa_excellon"] = new_ext
  4247. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4248. if obj_type is None or obj_type == 'gcode':
  4249. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4250. gco_list = [x for x in gco_list if x != '']
  4251. # register all keys in the Preferences window
  4252. for ext in gco_list:
  4253. new_k = new_reg_path + '.%s' % ext
  4254. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4255. # and unregister those that are no longer in the Preferences windows but are in the file
  4256. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4257. if ext not in gco_list:
  4258. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4259. # now write the updated extensions to the self.defaults
  4260. # new_ext = ''
  4261. # for ext in gco_list:
  4262. # new_ext = new_ext + ext + ', '
  4263. # self.defaults["fa_gcode"] = new_ext
  4264. self.inform.emit('[success] %s' %
  4265. _("Selected GCode file extensions registered with FlatCAM."))
  4266. if obj_type is None or obj_type == 'gerber':
  4267. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4268. grb_list = [x for x in grb_list if x != '']
  4269. # register all keys in the Preferences window
  4270. for ext in grb_list:
  4271. new_k = new_reg_path + '.%s' % ext
  4272. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4273. # and unregister those that are no longer in the Preferences windows but are in the file
  4274. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4275. if ext not in grb_list:
  4276. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4277. # now write the updated extensions to the self.defaults
  4278. # new_ext = ''
  4279. # for ext in grb_list:
  4280. # new_ext = new_ext + ext + ', '
  4281. # self.defaults["fa_gerber"] = new_ext
  4282. self.inform.emit('[success] %s' %
  4283. _("Selected Gerber file extensions registered with FlatCAM."))
  4284. def add_extension(self, ext_type):
  4285. """
  4286. Add a file extension to the list for a specific object
  4287. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4288. :return:
  4289. """
  4290. if ext_type == 'excellon':
  4291. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4292. if new_ext == '':
  4293. return
  4294. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4295. if new_ext in old_val:
  4296. return
  4297. old_val.append(new_ext)
  4298. old_val.sort()
  4299. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4300. if ext_type == 'gcode':
  4301. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4302. if new_ext == '':
  4303. return
  4304. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4305. if new_ext in old_val:
  4306. return
  4307. old_val.append(new_ext)
  4308. old_val.sort()
  4309. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4310. if ext_type == 'gerber':
  4311. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4312. if new_ext == '':
  4313. return
  4314. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4315. if new_ext in old_val:
  4316. return
  4317. old_val.append(new_ext)
  4318. old_val.sort()
  4319. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4320. if ext_type == 'keyword':
  4321. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4322. if new_kw == '':
  4323. return
  4324. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4325. if new_kw in old_val:
  4326. return
  4327. old_val.append(new_kw)
  4328. old_val.sort()
  4329. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4330. # update the self.myKeywords so the model is updated
  4331. self.autocomplete_kw_list = \
  4332. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4333. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4334. self.shell._edit.set_model_data(self.myKeywords)
  4335. def del_extension(self, ext_type):
  4336. """
  4337. Remove a file extension from the list for a specific object
  4338. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4339. :return:
  4340. """
  4341. if ext_type == 'excellon':
  4342. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4343. if new_ext == '':
  4344. return
  4345. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4346. if new_ext not in old_val:
  4347. return
  4348. old_val.remove(new_ext)
  4349. old_val.sort()
  4350. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4351. if ext_type == 'gcode':
  4352. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4353. if new_ext == '':
  4354. return
  4355. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4356. if new_ext not in old_val:
  4357. return
  4358. old_val.remove(new_ext)
  4359. old_val.sort()
  4360. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4361. if ext_type == 'gerber':
  4362. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4363. if new_ext == '':
  4364. return
  4365. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4366. if new_ext not in old_val:
  4367. return
  4368. old_val.remove(new_ext)
  4369. old_val.sort()
  4370. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4371. if ext_type == 'keyword':
  4372. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4373. if new_kw == '':
  4374. return
  4375. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4376. if new_kw not in old_val:
  4377. return
  4378. old_val.remove(new_kw)
  4379. old_val.sort()
  4380. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4381. # update the self.myKeywords so the model is updated
  4382. self.autocomplete_kw_list = \
  4383. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4384. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4385. self.shell._edit.set_model_data(self.myKeywords)
  4386. def restore_extensions(self, ext_type):
  4387. """
  4388. Restore all file extensions associations with FlatCAM, for a specific object
  4389. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4390. :return:
  4391. """
  4392. if ext_type == 'excellon':
  4393. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4394. # for the ability to open Excellon files with .txt extension
  4395. new_exc_list = deepcopy(self.exc_list)
  4396. try:
  4397. new_exc_list.remove('txt')
  4398. except ValueError:
  4399. pass
  4400. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4401. if ext_type == 'gcode':
  4402. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4403. if ext_type == 'gerber':
  4404. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4405. if ext_type == 'keyword':
  4406. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4407. # update the self.myKeywords so the model is updated
  4408. self.autocomplete_kw_list = self.default_keywords
  4409. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4410. self.shell._edit.set_model_data(self.myKeywords)
  4411. def delete_all_extensions(self, ext_type):
  4412. """
  4413. Delete all file extensions associations with FlatCAM, for a specific object
  4414. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4415. :return:
  4416. """
  4417. if ext_type == 'excellon':
  4418. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4419. if ext_type == 'gcode':
  4420. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4421. if ext_type == 'gerber':
  4422. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4423. if ext_type == 'keyword':
  4424. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4425. # update the self.myKeywords so the model is updated
  4426. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4427. self.shell._edit.set_model_data(self.myKeywords)
  4428. def on_edit_join(self, name=None):
  4429. """
  4430. Callback for Edit->Join. Joins the selected geometry objects into
  4431. a new one.
  4432. :return: None
  4433. """
  4434. self.report_usage("on_edit_join()")
  4435. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4436. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4437. geo_type_set = set()
  4438. objs = self.collection.get_selected()
  4439. if len(objs) < 2:
  4440. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4441. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4442. return 'fail'
  4443. for obj in objs:
  4444. geo_type_set.add(obj.multigeo)
  4445. # if len(geo_type_list) == 1 means that all list elements are the same
  4446. if len(geo_type_set) != 1:
  4447. self.inform.emit('[ERROR] %s' %
  4448. _("Failed join. The Geometry objects are of different types.\n"
  4449. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4450. "convert from one to another and retry joining \n"
  4451. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4452. "the result may not be what was expected. \n"
  4453. "Check the generated GCODE."))
  4454. return
  4455. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4456. if True in geo_type_set:
  4457. def initialize(geo_obj, app):
  4458. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4459. app.inform.emit('[success] %s.' % _("Multigeo. Geometry merging finished"))
  4460. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4461. for v in obj.tools.values():
  4462. v['data']['name'] = obj_name_multi
  4463. self.new_object("geometry", obj_name_multi, initialize)
  4464. else:
  4465. def initialize(geo_obj, app):
  4466. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4467. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4468. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4469. for v in obj.tools.values():
  4470. v['data']['name'] = obj_name_single
  4471. self.new_object("geometry", obj_name_single, initialize)
  4472. self.should_we_save = True
  4473. def on_edit_join_exc(self):
  4474. """
  4475. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4476. a new Excellon.
  4477. :return: None
  4478. """
  4479. self.report_usage("on_edit_join_exc()")
  4480. objs = self.collection.get_selected()
  4481. for obj in objs:
  4482. if not isinstance(obj, FlatCAMExcellon):
  4483. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4484. return
  4485. if len(objs) < 2:
  4486. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4487. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4488. return 'fail'
  4489. def initialize(exc_obj, app):
  4490. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=exc_obj)
  4491. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4492. self.new_object("excellon", 'Combo_Excellon', initialize)
  4493. self.should_we_save = True
  4494. def on_edit_join_grb(self):
  4495. """
  4496. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4497. a new Gerber object.
  4498. :return: None
  4499. """
  4500. self.report_usage("on_edit_join_grb()")
  4501. objs = self.collection.get_selected()
  4502. for obj in objs:
  4503. if not isinstance(obj, FlatCAMGerber):
  4504. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4505. return
  4506. if len(objs) < 2:
  4507. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4508. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4509. return 'fail'
  4510. def initialize(grb_obj, app):
  4511. FlatCAMGerber.merge(self, grb_list=objs, grb_final=grb_obj)
  4512. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4513. self.new_object("gerber", 'Combo_Gerber', initialize)
  4514. self.should_we_save = True
  4515. def on_convert_singlegeo_to_multigeo(self):
  4516. """
  4517. Called for converting a Geometry object from single-geo to multi-geo.
  4518. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4519. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4520. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4521. the solid-geometry of that tool.
  4522. :return: None
  4523. """
  4524. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4525. obj = self.collection.get_active()
  4526. if obj is None:
  4527. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4528. return
  4529. if not isinstance(obj, FlatCAMGeometry):
  4530. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4531. return
  4532. obj.multigeo = True
  4533. for tooluid, dict_value in obj.tools.items():
  4534. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4535. if not isinstance(obj.solid_geometry, list):
  4536. obj.solid_geometry = [obj.solid_geometry]
  4537. obj.solid_geometry[:] = []
  4538. obj.plot()
  4539. self.should_we_save = True
  4540. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4541. def on_convert_multigeo_to_singlegeo(self):
  4542. """
  4543. Called for converting a Geometry object from multi-geo to single-geo.
  4544. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4545. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4546. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4547. the solid-geometry of that tool.
  4548. :return: None
  4549. """
  4550. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4551. obj = self.collection.get_active()
  4552. if obj is None:
  4553. self.inform.emit('[ERROR_NOTCL] %s' %
  4554. _("Failed. Select a Geometry Object and try again."))
  4555. return
  4556. if not isinstance(obj, FlatCAMGeometry):
  4557. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4558. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4559. return
  4560. obj.multigeo = False
  4561. total_solid_geometry = []
  4562. for tooluid, dict_value in obj.tools.items():
  4563. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4564. # clear the original geometry
  4565. dict_value['solid_geometry'][:] = []
  4566. obj.solid_geometry = deepcopy(total_solid_geometry)
  4567. obj.plot()
  4568. self.should_we_save = True
  4569. self.inform.emit('[success] %s' %
  4570. _("A Geometry object was converted to SingleGeo type."))
  4571. def on_defaults_dict_change(self, field):
  4572. """
  4573. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4574. Edit -> Preferences tab window.
  4575. :param field: the key of the self.defaults dictionary that was changed.
  4576. :return: None
  4577. """
  4578. self.defaults_write_form_field(field)
  4579. if field == "units":
  4580. self.set_screen_units(self.defaults['units'])
  4581. def set_screen_units(self, units):
  4582. """
  4583. Set the FlatCAM units on the status bar.
  4584. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4585. :return: None
  4586. """
  4587. self.ui.units_label.setText("[" + units.lower() + "]")
  4588. def on_toggle_units(self, no_pref=False):
  4589. """
  4590. Callback for the Units radio-button change in the Preferences tab.
  4591. Changes the application's default units adn for the project too.
  4592. If changing the project's units, the change propagates to all of
  4593. the objects in the project.
  4594. :return: None
  4595. """
  4596. self.report_usage("on_toggle_units")
  4597. if self.toggle_units_ignore:
  4598. return
  4599. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4600. # If option is the same, then ignore
  4601. if new_units == self.defaults["units"].upper():
  4602. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4603. return
  4604. # Options to scale
  4605. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4606. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4607. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4608. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4609. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4610. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4611. "excellon_editor_slot_lin_pitch",
  4612. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4613. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4614. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4615. "geometry_feedrate_probe", "geometry_startz",
  4616. 'cncjob_tooldia',
  4617. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4618. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4619. "tools_nccnewdia",
  4620. "tools_2sided_drilldia", "tools_film_boundary",
  4621. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4622. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4623. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4624. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4625. "tools_transform_offset_y",
  4626. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4627. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4628. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4629. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4630. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4631. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4632. "tools_cr_h2h_val", "tools_cr_dh_val",
  4633. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4634. def scale_defaults(sfactor):
  4635. for dim in dimensions:
  4636. if dim == 'excellon_toolchangexy':
  4637. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4638. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4639. coords_xy[0] *= sfactor
  4640. coords_xy[1] *= sfactor
  4641. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4642. elif dim == 'geometry_toolchangexy':
  4643. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4644. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4645. coords_xy[0] *= sfactor
  4646. coords_xy[1] *= sfactor
  4647. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4648. elif dim == 'geometry_cnctooldia':
  4649. tools_diameters = []
  4650. try:
  4651. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4652. tools_diameters = [eval(a) for a in tools_string if a != '']
  4653. except Exception as e:
  4654. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4655. self.defaults['geometry_cnctooldia'] = ''
  4656. for t in range(len(tools_diameters)):
  4657. tools_diameters[t] *= sfactor
  4658. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4659. elif dim == 'tools_ncctools':
  4660. ncctools = []
  4661. try:
  4662. tools_string = self.defaults["tools_ncctools"].split(",")
  4663. ncctools = [eval(a) for a in tools_string if a != '']
  4664. except Exception as e:
  4665. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4666. self.defaults['tools_ncctools'] = ''
  4667. for t in range(len(ncctools)):
  4668. ncctools[t] *= sfactor
  4669. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4670. elif dim == 'tools_solderpaste_tools':
  4671. sptools = []
  4672. try:
  4673. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4674. sptools = [eval(a) for a in tools_string if a != '']
  4675. except Exception as e:
  4676. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4677. self.defaults['tools_solderpaste_tools'] = ""
  4678. for t in range(len(sptools)):
  4679. sptools[t] *= sfactor
  4680. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4681. elif dim == 'tools_solderpaste_xy_toolchange':
  4682. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4683. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4684. sp_coords[0] *= sfactor
  4685. sp_coords[1] *= sfactor
  4686. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4687. elif dim == 'global_gridx' or dim == 'global_gridy':
  4688. if new_units == 'IN':
  4689. val = 0.1
  4690. try:
  4691. val = float(self.defaults[dim]) * sfactor
  4692. except Exception as e:
  4693. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4694. self.defaults[dim] = float('%.6f' % val)
  4695. else:
  4696. val = 0.1
  4697. try:
  4698. val = float(self.defaults[dim]) * sfactor
  4699. except Exception as e:
  4700. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4701. self.defaults[dim] = float('%.4f' % val)
  4702. else:
  4703. val = 0.1
  4704. if self.defaults[dim]:
  4705. try:
  4706. val = float(self.defaults[dim]) * sfactor
  4707. except Exception as e:
  4708. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4709. self.defaults[dim] = val
  4710. # The scaling factor depending on choice of units.
  4711. factor = 1/25.4
  4712. if new_units == 'MM':
  4713. factor = 25.4
  4714. # Changing project units. Warn user.
  4715. msgbox = QtWidgets.QMessageBox()
  4716. msgbox.setWindowTitle(_("Toggle Units"))
  4717. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4718. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4719. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4720. "properties of all objects to be scaled accordingly.\nContinue?"))
  4721. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4722. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4723. msgbox.setDefaultButton(bt_ok)
  4724. msgbox.exec_()
  4725. response = msgbox.clickedButton()
  4726. if response == bt_ok:
  4727. if no_pref is False:
  4728. self.defaults_read_form()
  4729. scale_defaults(factor)
  4730. self.defaults_write_form(fl_units=new_units)
  4731. self.defaults["units"] = new_units
  4732. # save the defaults to file, some may assume that the conversion is enough and it's not
  4733. self.on_save_button()
  4734. self.should_we_save = True
  4735. # change this only if the workspace is active
  4736. if self.defaults['global_workspace'] is True:
  4737. self.plotcanvas.draw_workspace()
  4738. # adjust the grid values on the main toolbar
  4739. dec = 6 if new_units == 'IN'else 4
  4740. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4741. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4742. if not self.ui.grid_gap_link_cb.isChecked():
  4743. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4744. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4745. for obj in self.collection.get_list():
  4746. obj.convert_units(new_units)
  4747. # make that the properties stored in the object are also updated
  4748. self.object_changed.emit(obj)
  4749. obj.build_ui()
  4750. current = self.collection.get_active()
  4751. if current is not None:
  4752. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4753. if not isinstance(current, FlatCAMGeometry):
  4754. current.to_form()
  4755. self.plot_all()
  4756. self.inform.emit('[success] %s: %s' %
  4757. (_("Converted units to"), new_units))
  4758. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4759. self.set_screen_units(new_units)
  4760. else:
  4761. # Undo toggling
  4762. self.toggle_units_ignore = True
  4763. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4764. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4765. else:
  4766. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4767. self.toggle_units_ignore = False
  4768. self.inform.emit('[WARNING_NOTCL]%s' %
  4769. _(" Units conversion cancelled."))
  4770. self.defaults_read_form()
  4771. def on_toggle_units_click(self):
  4772. try:
  4773. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4774. except (TypeError, AttributeError):
  4775. pass
  4776. if self.defaults["units"] == 'MM':
  4777. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4778. else:
  4779. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4780. self.on_toggle_units(no_pref=True)
  4781. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4782. lambda: self.on_toggle_units(no_pref=False))
  4783. def on_fullscreen(self, disable=False):
  4784. self.report_usage("on_fullscreen()")
  4785. if self.toggle_fscreen is False and disable is False:
  4786. # self.ui.showFullScreen()
  4787. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4788. a = self.ui.geometry()
  4789. self.x_pos = a.x()
  4790. self.y_pos = a.y()
  4791. self.width = a.width()
  4792. self.height = a.height()
  4793. # set new geometry to full desktop rect
  4794. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4795. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4796. # everything else will not work without this hack. This happen in Windows.
  4797. # https://bugreports.qt.io/browse/QTBUG-41309
  4798. desktop = QtWidgets.QApplication.desktop()
  4799. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4800. rec = desktop.screenGeometry(screen)
  4801. x = rec.x() - 1
  4802. y = rec.y() - 1
  4803. h = rec.height() + 2
  4804. w = rec.width() + 2
  4805. self.ui.setGeometry(x, y, w, h)
  4806. self.ui.show()
  4807. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4808. tb.setVisible(False)
  4809. self.ui.splitter_left.setVisible(False)
  4810. self.toggle_fscreen = True
  4811. elif self.toggle_fscreen is True or disable is True:
  4812. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4813. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4814. self.ui.showNormal()
  4815. self.restore_toolbar_view()
  4816. self.ui.splitter_left.setVisible(True)
  4817. self.toggle_fscreen = False
  4818. def on_toggle_plotarea(self):
  4819. self.report_usage("on_toggle_plotarea()")
  4820. try:
  4821. name = self.ui.plot_tab_area.widget(0).objectName()
  4822. except AttributeError:
  4823. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4824. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4825. self.ui.plot_tab_area.protectTab(0)
  4826. return
  4827. if name != 'plotarea':
  4828. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4829. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4830. self.ui.plot_tab_area.protectTab(0)
  4831. else:
  4832. self.ui.plot_tab_area.closeTab(0)
  4833. def on_toggle_notebook(self):
  4834. if self.ui.splitter.sizes()[0] == 0:
  4835. self.ui.splitter.setSizes([1, 1])
  4836. self.ui.menu_toggle_nb.setChecked(True)
  4837. else:
  4838. self.ui.splitter.setSizes([0, 1])
  4839. self.ui.menu_toggle_nb.setChecked(False)
  4840. def on_toggle_axis(self):
  4841. self.report_usage("on_toggle_axis()")
  4842. if self.toggle_axis is False:
  4843. if self.is_legacy is False:
  4844. # self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4845. # self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4846. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4847. parent=self.plotcanvas.view.scene)
  4848. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4849. parent=self.plotcanvas.view.scene)
  4850. # self.plotcanvas.redraw()
  4851. else:
  4852. self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4853. self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4854. self.plotcanvas.canvas.draw()
  4855. pass
  4856. self.toggle_axis = True
  4857. else:
  4858. if self.is_legacy is False:
  4859. # self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4860. # self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4861. # self.plotcanvas.redraw()
  4862. self.plotcanvas.v_line.parent = None
  4863. self.plotcanvas.h_line.parent = None
  4864. else:
  4865. self.plotcanvas.axes.lines[:] = []
  4866. self.plotcanvas.canvas.draw()
  4867. self.toggle_axis = False
  4868. def on_toggle_grid(self):
  4869. self.report_usage("on_toggle_grid()")
  4870. self.ui.grid_snap_btn.trigger()
  4871. def on_toggle_grid_lines(self):
  4872. self.report_usage("on_toggle_grd_lines()")
  4873. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  4874. if tt_settings.contains("theme"):
  4875. theme = tt_settings.value('theme', type=str)
  4876. else:
  4877. theme = 'white'
  4878. if self.toggle_grid_lines is False:
  4879. if self.is_legacy is False:
  4880. if theme == 'white':
  4881. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  4882. else:
  4883. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  4884. else:
  4885. self.plotcanvas.axes.grid(True)
  4886. try:
  4887. self.plotcanvas.canvas.draw()
  4888. except IndexError:
  4889. pass
  4890. pass
  4891. self.toggle_grid_lines = True
  4892. else:
  4893. if self.is_legacy is False:
  4894. if theme == 'white':
  4895. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  4896. else:
  4897. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  4898. else:
  4899. self.plotcanvas.axes.grid(False)
  4900. try:
  4901. self.plotcanvas.canvas.draw()
  4902. except IndexError:
  4903. pass
  4904. self.toggle_grid_lines = False
  4905. def show_preferences_gui(self):
  4906. """
  4907. Called to initialize and show the Preferences GUI
  4908. :return: None
  4909. """
  4910. self.gen_form = self.ui.general_defaults_form
  4911. self.ger_form = self.ui.gerber_defaults_form
  4912. self.exc_form = self.ui.excellon_defaults_form
  4913. self.geo_form = self.ui.geometry_defaults_form
  4914. self.cnc_form = self.ui.cncjob_defaults_form
  4915. self.tools_form = self.ui.tools_defaults_form
  4916. self.tools2_form = self.ui.tools2_defaults_form
  4917. self.fa_form = self.ui.util_defaults_form
  4918. try:
  4919. self.ui.general_scroll_area.takeWidget()
  4920. except Exception:
  4921. self.log.debug("Nothing to remove")
  4922. self.ui.general_scroll_area.setWidget(self.gen_form)
  4923. self.gen_form.show()
  4924. try:
  4925. self.ui.gerber_scroll_area.takeWidget()
  4926. except Exception:
  4927. self.log.debug("Nothing to remove")
  4928. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4929. self.ger_form.show()
  4930. try:
  4931. self.ui.excellon_scroll_area.takeWidget()
  4932. except Exception:
  4933. self.log.debug("Nothing to remove")
  4934. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4935. self.exc_form.show()
  4936. try:
  4937. self.ui.geometry_scroll_area.takeWidget()
  4938. except Exception:
  4939. self.log.debug("Nothing to remove")
  4940. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4941. self.geo_form.show()
  4942. try:
  4943. self.ui.cncjob_scroll_area.takeWidget()
  4944. except Exception:
  4945. self.log.debug("Nothing to remove")
  4946. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4947. self.cnc_form.show()
  4948. try:
  4949. self.ui.tools_scroll_area.takeWidget()
  4950. except Exception:
  4951. self.log.debug("Nothing to remove")
  4952. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4953. self.tools_form.show()
  4954. try:
  4955. self.ui.tools2_scroll_area.takeWidget()
  4956. except Exception:
  4957. self.log.debug("Nothing to remove")
  4958. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  4959. self.tools2_form.show()
  4960. try:
  4961. self.ui.fa_scroll_area.takeWidget()
  4962. except Exception:
  4963. self.log.debug("Nothing to remove")
  4964. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4965. self.fa_form.show()
  4966. self.log.debug("Finished Preferences GUI form initialization.")
  4967. # self.options2form()
  4968. def init_color_pickers_in_preferences_gui(self):
  4969. # Init Plot Colors
  4970. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  4971. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4972. "background-color:%s;"
  4973. "border-color: dimgray" % str(self.defaults['global_plot_fill'])[:7])
  4974. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  4975. int(self.defaults['global_plot_fill'][7:9], 16))
  4976. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  4977. int(self.defaults['global_plot_fill'][7:9], 16))
  4978. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  4979. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4980. "background-color:%s;"
  4981. "border-color: dimgray" % str(self.defaults['global_plot_line'])[:7])
  4982. # Init Left-Right Selection colors
  4983. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  4984. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4985. "background-color:%s;"
  4986. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  4987. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  4988. int(self.defaults['global_sel_fill'][7:9], 16))
  4989. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  4990. int(self.defaults['global_sel_fill'][7:9], 16))
  4991. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  4992. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4993. "background-color:%s;"
  4994. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  4995. # Init Right-Left Selection colors
  4996. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  4997. self.defaults['global_alt_sel_fill'])
  4998. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4999. "background-color:%s;"
  5000. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  5001. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  5002. int(self.defaults['global_sel_fill'][7:9], 16))
  5003. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  5004. int(self.defaults['global_sel_fill'][7:9], 16))
  5005. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  5006. self.defaults['global_alt_sel_line'])
  5007. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5008. "background-color:%s;"
  5009. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  5010. # Init Draw color and Selection Draw Color
  5011. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  5012. self.defaults['global_draw_color'])
  5013. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5014. "background-color:%s;"
  5015. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  5016. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  5017. self.defaults['global_sel_draw_color'])
  5018. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5019. "background-color:%s;"
  5020. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  5021. # Init Project Items color
  5022. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  5023. self.defaults['global_proj_item_color'])
  5024. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5025. "background-color:%s;"
  5026. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  5027. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  5028. self.defaults['global_proj_item_dis_color'])
  5029. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5030. "background-color:%s;"
  5031. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  5032. # Init the Annotation CNC Job color
  5033. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  5034. self.defaults['cncjob_annotation_fontcolor'])
  5035. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5036. "background-color:%s;"
  5037. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  5038. # Init the Tool Film color
  5039. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  5040. self.defaults['tools_film_color'])
  5041. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5042. "background-color:%s;"
  5043. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  5044. )
  5045. # Init the Tool QRCode colors
  5046. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  5047. self.defaults['tools_qrcode_fill_color'])
  5048. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5049. "background-color:%s;"
  5050. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  5051. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  5052. self.defaults['tools_qrcode_back_color'])
  5053. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5054. "background-color:%s;"
  5055. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  5056. def on_excellon_defaults_button(self):
  5057. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  5058. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  5059. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  5060. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  5061. self.defaults_form_fields["excellon_zeros"].set_value('L')
  5062. self.defaults_form_fields["excellon_units"].set_value('INCH')
  5063. log.debug("Excellon app defaults loaded ...")
  5064. def on_update_exc_export(self, state):
  5065. """
  5066. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5067. if the update_excellon_cb checkbox is checked
  5068. :param state: state of the checkbox whose signals is tied to his slot
  5069. :return:
  5070. """
  5071. if state:
  5072. # first try to disconnect
  5073. try:
  5074. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.\
  5075. disconnect(self.on_excellon_format_changed)
  5076. except TypeError:
  5077. pass
  5078. try:
  5079. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.\
  5080. disconnect(self.on_excellon_format_changed)
  5081. except TypeError:
  5082. pass
  5083. try:
  5084. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.\
  5085. disconnect(self.on_excellon_format_changed)
  5086. except TypeError:
  5087. pass
  5088. try:
  5089. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.\
  5090. disconnect(self.on_excellon_format_changed)
  5091. except TypeError:
  5092. pass
  5093. try:
  5094. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5095. disconnect(self.on_excellon_zeros_changed)
  5096. except TypeError:
  5097. pass
  5098. try:
  5099. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5100. disconnect(self.on_excellon_zeros_changed)
  5101. except TypeError:
  5102. pass
  5103. # the connect them
  5104. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5105. self.on_excellon_format_changed)
  5106. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5107. self.on_excellon_format_changed)
  5108. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5109. self.on_excellon_format_changed)
  5110. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5111. self.on_excellon_format_changed)
  5112. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5113. self.on_excellon_zeros_changed)
  5114. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5115. self.on_excellon_units_changed)
  5116. else:
  5117. # disconnect the signals
  5118. try:
  5119. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5120. disconnect(self.on_excellon_format_changed)
  5121. except TypeError:
  5122. pass
  5123. try:
  5124. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5125. disconnect(self.on_excellon_format_changed)
  5126. except TypeError:
  5127. pass
  5128. try:
  5129. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5130. disconnect(self.on_excellon_format_changed)
  5131. except TypeError:
  5132. pass
  5133. try:
  5134. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5135. disconnect(self.on_excellon_format_changed)
  5136. except TypeError:
  5137. pass
  5138. try:
  5139. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5140. disconnect(self.on_excellon_zeros_changed)
  5141. except TypeError:
  5142. pass
  5143. try:
  5144. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5145. disconnect(self.on_excellon_zeros_changed)
  5146. except TypeError:
  5147. pass
  5148. def on_excellon_format_changed(self):
  5149. """
  5150. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5151. :return: None
  5152. """
  5153. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5154. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5155. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5156. )
  5157. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5158. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5159. )
  5160. else:
  5161. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5162. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5163. )
  5164. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5165. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5166. )
  5167. def on_excellon_zeros_changed(self):
  5168. """
  5169. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5170. :return: None
  5171. """
  5172. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5173. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5174. )
  5175. def on_excellon_units_changed(self):
  5176. """
  5177. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5178. :return: None
  5179. """
  5180. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5181. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5182. )
  5183. self.on_excellon_format_changed()
  5184. # Setting plot colors handlers
  5185. def on_pf_color_entry(self):
  5186. self.defaults['global_plot_fill'] = \
  5187. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5188. self.defaults['global_plot_fill'][7:9]
  5189. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5190. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5191. def on_pf_color_button(self):
  5192. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5193. c_dialog = QtWidgets.QColorDialog()
  5194. plot_fill_color = c_dialog.getColor(initial=current_color)
  5195. if plot_fill_color.isValid() is False:
  5196. return
  5197. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5198. "background-color:%s" % str(plot_fill_color.name()))
  5199. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5200. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5201. self.defaults['global_plot_fill'] = new_val
  5202. def on_pf_color_spinner(self):
  5203. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5204. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5205. self.defaults['global_plot_fill'] = \
  5206. self.defaults['global_plot_fill'][:7] + \
  5207. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5208. self.defaults['global_plot_line'] = \
  5209. self.defaults['global_plot_line'][:7] + \
  5210. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5211. def on_pf_color_slider(self):
  5212. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5213. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5214. def on_pl_color_entry(self):
  5215. self.defaults['global_plot_line'] = \
  5216. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5217. self.defaults['global_plot_line'][7:9]
  5218. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5219. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5220. def on_pl_color_button(self):
  5221. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5222. # print(current_color)
  5223. c_dialog = QtWidgets.QColorDialog()
  5224. plot_line_color = c_dialog.getColor(initial=current_color)
  5225. if plot_line_color.isValid() is False:
  5226. return
  5227. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5228. "background-color:%s" % str(plot_line_color.name()))
  5229. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5230. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5231. self.defaults['global_plot_line'] = new_val_line
  5232. # Setting selection colors (left - right) handlers
  5233. def on_sf_color_entry(self):
  5234. self.defaults['global_sel_fill'] = \
  5235. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5236. self.defaults['global_sel_fill'][7:9]
  5237. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5238. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5239. def on_sf_color_button(self):
  5240. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5241. c_dialog = QtWidgets.QColorDialog()
  5242. plot_fill_color = c_dialog.getColor(initial=current_color)
  5243. if plot_fill_color.isValid() is False:
  5244. return
  5245. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5246. "background-color:%s" % str(plot_fill_color.name()))
  5247. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5248. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5249. self.defaults['global_sel_fill'] = new_val
  5250. def on_sf_color_spinner(self):
  5251. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5252. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5253. self.defaults['global_sel_fill'] = \
  5254. self.defaults['global_sel_fill'][:7] + \
  5255. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5256. self.defaults['global_sel_line'] = \
  5257. self.defaults['global_sel_line'][:7] + \
  5258. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5259. def on_sf_color_slider(self):
  5260. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5261. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5262. def on_sl_color_entry(self):
  5263. self.defaults['global_sel_line'] = \
  5264. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5265. self.defaults['global_sel_line'][7:9]
  5266. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5267. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5268. def on_sl_color_button(self):
  5269. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5270. c_dialog = QtWidgets.QColorDialog()
  5271. plot_line_color = c_dialog.getColor(initial=current_color)
  5272. if plot_line_color.isValid() is False:
  5273. return
  5274. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5275. "background-color:%s" % str(plot_line_color.name()))
  5276. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5277. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5278. self.defaults['global_sel_line'] = new_val_line
  5279. # Setting selection colors (right - left) handlers
  5280. def on_alt_sf_color_entry(self):
  5281. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5282. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5283. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5284. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5285. def on_alt_sf_color_button(self):
  5286. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5287. c_dialog = QtWidgets.QColorDialog()
  5288. plot_fill_color = c_dialog.getColor(initial=current_color)
  5289. if plot_fill_color.isValid() is False:
  5290. return
  5291. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5292. "background-color:%s" % str(plot_fill_color.name()))
  5293. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5294. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5295. self.defaults['global_alt_sel_fill'] = new_val
  5296. def on_alt_sf_color_spinner(self):
  5297. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5298. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5299. self.defaults['global_alt_sel_fill'] = \
  5300. self.defaults['global_alt_sel_fill'][:7] + \
  5301. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5302. self.defaults['global_alt_sel_line'] = \
  5303. self.defaults['global_alt_sel_line'][:7] + \
  5304. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5305. def on_alt_sf_color_slider(self):
  5306. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5307. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5308. def on_alt_sl_color_entry(self):
  5309. self.defaults['global_alt_sel_line'] = \
  5310. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5311. self.defaults['global_alt_sel_line'][7:9]
  5312. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5313. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5314. def on_alt_sl_color_button(self):
  5315. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5316. c_dialog = QtWidgets.QColorDialog()
  5317. plot_line_color = c_dialog.getColor(initial=current_color)
  5318. if plot_line_color.isValid() is False:
  5319. return
  5320. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5321. "background-color:%s" % str(plot_line_color.name()))
  5322. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5323. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5324. self.defaults['global_alt_sel_line'] = new_val_line
  5325. # Setting Editor colors
  5326. def on_draw_color_entry(self):
  5327. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5328. .draw_color_entry.get_value()
  5329. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5330. "background-color:%s" % str(self.defaults['global_draw_color']))
  5331. def on_draw_color_button(self):
  5332. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5333. c_dialog = QtWidgets.QColorDialog()
  5334. draw_color = c_dialog.getColor(initial=current_color)
  5335. if draw_color.isValid() is False:
  5336. return
  5337. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5338. "background-color:%s" % str(draw_color.name()))
  5339. new_val = str(draw_color.name())
  5340. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5341. self.defaults['global_draw_color'] = new_val
  5342. def on_sel_draw_color_entry(self):
  5343. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5344. .sel_draw_color_entry.get_value()
  5345. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5346. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5347. def on_sel_draw_color_button(self):
  5348. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5349. c_dialog = QtWidgets.QColorDialog()
  5350. sel_draw_color = c_dialog.getColor(initial=current_color)
  5351. if sel_draw_color.isValid() is False:
  5352. return
  5353. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5354. "background-color:%s" % str(sel_draw_color.name()))
  5355. new_val_sel = str(sel_draw_color.name())
  5356. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5357. self.defaults['global_sel_draw_color'] = new_val_sel
  5358. def on_proj_color_entry(self):
  5359. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5360. .proj_color_entry.get_value()
  5361. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5362. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5363. def on_proj_color_button(self):
  5364. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5365. c_dialog = QtWidgets.QColorDialog()
  5366. proj_color = c_dialog.getColor(initial=current_color)
  5367. if proj_color.isValid() is False:
  5368. return
  5369. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5370. "background-color:%s" % str(proj_color.name()))
  5371. new_val_sel = str(proj_color.name())
  5372. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5373. self.defaults['global_proj_item_color'] = new_val_sel
  5374. def on_proj_color_dis_entry(self):
  5375. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5376. .proj_color_dis_entry.get_value()
  5377. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5378. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5379. def on_proj_color_dis_button(self):
  5380. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5381. c_dialog = QtWidgets.QColorDialog()
  5382. proj_color = c_dialog.getColor(initial=current_color)
  5383. if proj_color.isValid() is False:
  5384. return
  5385. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5386. "background-color:%s" % str(proj_color.name()))
  5387. new_val_sel = str(proj_color.name())
  5388. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5389. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5390. def on_annotation_fontcolor_entry(self):
  5391. self.defaults['cncjob_annotation_fontcolor'] = \
  5392. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5393. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5394. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5395. def on_annotation_fontcolor_button(self):
  5396. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5397. c_dialog = QtWidgets.QColorDialog()
  5398. annotation_color = c_dialog.getColor(initial=current_color)
  5399. if annotation_color.isValid() is False:
  5400. return
  5401. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5402. "background-color:%s" % str(annotation_color.name()))
  5403. new_val_sel = str(annotation_color.name())
  5404. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5405. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5406. def on_film_color_entry(self):
  5407. self.defaults['tools_film_color'] = \
  5408. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5409. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5410. "background-color:%s;"
  5411. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  5412. )
  5413. def on_film_color_button(self):
  5414. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5415. c_dialog = QtWidgets.QColorDialog()
  5416. film_color = c_dialog.getColor(initial=current_color)
  5417. if film_color.isValid() is False:
  5418. return
  5419. # if new color is different then mark that the Preferences are changed
  5420. if film_color != current_color:
  5421. self.on_preferences_edited()
  5422. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5423. "background-color:%s;"
  5424. "border-color: dimgray" % str(film_color.name())
  5425. )
  5426. new_val_sel = str(film_color.name())
  5427. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5428. self.defaults['tools_film_color'] = new_val_sel
  5429. def on_qrcode_fill_color_entry(self):
  5430. self.defaults['tools_qrcode_fill_color'] = \
  5431. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5432. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5433. "background-color:%s;"
  5434. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  5435. )
  5436. def on_qrcode_fill_color_button(self):
  5437. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5438. c_dialog = QtWidgets.QColorDialog()
  5439. fill_color = c_dialog.getColor(initial=current_color)
  5440. if fill_color.isValid() is False:
  5441. return
  5442. # if new color is different then mark that the Preferences are changed
  5443. if fill_color != current_color:
  5444. self.on_preferences_edited()
  5445. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5446. "background-color:%s;"
  5447. "border-color: dimgray" % str(fill_color.name())
  5448. )
  5449. new_val_sel = str(fill_color.name())
  5450. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5451. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5452. def on_qrcode_back_color_entry(self):
  5453. self.defaults['tools_qrcode_back_color'] = \
  5454. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5455. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5456. "background-color:%s;"
  5457. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  5458. )
  5459. def on_qrcode_back_color_button(self):
  5460. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5461. c_dialog = QtWidgets.QColorDialog()
  5462. back_color = c_dialog.getColor(initial=current_color)
  5463. if back_color.isValid() is False:
  5464. return
  5465. # if new color is different then mark that the Preferences are changed
  5466. if back_color != current_color:
  5467. self.on_preferences_edited()
  5468. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5469. "background-color:%s;"
  5470. "border-color: dimgray" % str(back_color.name())
  5471. )
  5472. new_val_sel = str(back_color.name())
  5473. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5474. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5475. def on_splash_changed(self, state):
  5476. settings = QSettings("Open Source", "FlatCAM")
  5477. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5478. # This will write the setting to the platform specific storage.
  5479. del settings
  5480. def on_tab_rmb_click(self, checked):
  5481. self.ui.notebook.set_detachable(val=checked)
  5482. self.defaults["global_tabs_detachable"] = checked
  5483. self.ui.plot_tab_area.set_detachable(val=checked)
  5484. self.defaults["global_tabs_detachable"] = checked
  5485. def on_tab_setup_context_menu(self):
  5486. initial_checked = self.defaults["global_tabs_detachable"]
  5487. action_name = str(_("Detachable Tabs"))
  5488. action = QtWidgets.QAction(self)
  5489. action.setCheckable(True)
  5490. action.setText(action_name)
  5491. action.setChecked(initial_checked)
  5492. self.ui.notebook.tabBar.addAction(action)
  5493. self.ui.plot_tab_area.tabBar.addAction(action)
  5494. try:
  5495. action.triggered.disconnect()
  5496. except TypeError:
  5497. pass
  5498. action.triggered.connect(self.on_tab_rmb_click)
  5499. def on_deselect_all(self):
  5500. self.collection.set_all_inactive()
  5501. self.delete_selection_shape()
  5502. def on_workspace_modified(self):
  5503. self.save_defaults(silent=True)
  5504. self.plotcanvas.draw_workspace()
  5505. def on_workspace(self):
  5506. self.report_usage("on_workspace()")
  5507. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5508. self.plotcanvas.restore_workspace()
  5509. else:
  5510. self.plotcanvas.delete_workspace()
  5511. self.save_defaults(silent=True)
  5512. def on_workspace_menu(self):
  5513. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5514. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5515. else:
  5516. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5517. self.on_workspace()
  5518. def on_layout(self, index=None, lay=None):
  5519. """
  5520. Set the toolbars layout (location)
  5521. :param index:
  5522. :param lay: type of layout to be set on the toolbard
  5523. :return: None
  5524. """
  5525. self.report_usage("on_layout()")
  5526. if lay:
  5527. current_layout = lay
  5528. else:
  5529. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5530. lay_settings = QSettings("Open Source", "FlatCAM")
  5531. lay_settings.setValue('layout', current_layout)
  5532. # This will write the setting to the platform specific storage.
  5533. del lay_settings
  5534. # first remove the toolbars:
  5535. try:
  5536. self.ui.removeToolBar(self.ui.toolbarfile)
  5537. self.ui.removeToolBar(self.ui.toolbargeo)
  5538. self.ui.removeToolBar(self.ui.toolbarview)
  5539. self.ui.removeToolBar(self.ui.toolbarshell)
  5540. self.ui.removeToolBar(self.ui.toolbartools)
  5541. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5542. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5543. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5544. self.ui.removeToolBar(self.ui.snap_toolbar)
  5545. self.ui.removeToolBar(self.ui.toolbarshell)
  5546. except Exception:
  5547. pass
  5548. if current_layout == 'standard':
  5549. # ## TOOLBAR INSTALLATION # ##
  5550. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5551. self.ui.toolbarfile.setObjectName('File_TB')
  5552. self.ui.addToolBar(self.ui.toolbarfile)
  5553. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5554. self.ui.toolbargeo.setObjectName('Edit_TB')
  5555. self.ui.addToolBar(self.ui.toolbargeo)
  5556. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5557. self.ui.toolbarview.setObjectName('View_TB')
  5558. self.ui.addToolBar(self.ui.toolbarview)
  5559. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5560. self.ui.toolbarshell.setObjectName('Shell_TB')
  5561. self.ui.addToolBar(self.ui.toolbarshell)
  5562. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5563. self.ui.toolbartools.setObjectName('Tools_TB')
  5564. self.ui.addToolBar(self.ui.toolbartools)
  5565. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5566. # self.ui.exc_edit_toolbar.setVisible(False)
  5567. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5568. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5569. self.ui.addToolBarBreak()
  5570. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5571. # self.ui.geo_edit_toolbar.setVisible(False)
  5572. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5573. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5574. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5575. # self.ui.grb_edit_toolbar.setVisible(False)
  5576. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5577. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5578. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5579. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5580. # self.ui.snap_toolbar.setMaximumHeight(30)
  5581. self.ui.addToolBar(self.ui.snap_toolbar)
  5582. self.ui.corner_snap_btn.setVisible(False)
  5583. self.ui.snap_magnet.setVisible(False)
  5584. elif current_layout == 'compact':
  5585. # ## TOOLBAR INSTALLATION # ##
  5586. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5587. self.ui.toolbarfile.setObjectName('File_TB')
  5588. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5589. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5590. self.ui.toolbargeo.setObjectName('Edit_TB')
  5591. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5592. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5593. self.ui.toolbarshell.setObjectName('Shell_TB')
  5594. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5595. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5596. self.ui.toolbartools.setObjectName('Tools_TB')
  5597. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5598. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5599. # self.ui.geo_edit_toolbar.setVisible(False)
  5600. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5601. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5602. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5603. self.ui.toolbarview.setObjectName('View_TB')
  5604. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5605. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5606. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5607. # self.ui.grb_edit_toolbar.setVisible(False)
  5608. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5609. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5610. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5611. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5612. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5613. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5614. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5615. self.ui.snap_toolbar.setMaximumHeight(30)
  5616. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5617. self.ui.corner_snap_btn.setVisible(True)
  5618. self.ui.snap_magnet.setVisible(True)
  5619. # add all the actions to the toolbars
  5620. self.ui.populate_toolbars()
  5621. # reconnect all the signals to the toolbar actions
  5622. self.connect_toolbar_signals()
  5623. self.ui.grid_snap_btn.setChecked(True)
  5624. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5625. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5626. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5627. self.ui.grid_gap_link_cb.setChecked(True)
  5628. def on_cursor_type(self, val):
  5629. """
  5630. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5631. :return: None
  5632. """
  5633. self.app_cursor.enabled = False
  5634. if val == 'small':
  5635. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5636. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5637. self.app_cursor = self.plotcanvas.new_cursor()
  5638. else:
  5639. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5640. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5641. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5642. if self.ui.grid_snap_btn.isChecked():
  5643. self.app_cursor.enabled = True
  5644. else:
  5645. self.app_cursor.enabled = False
  5646. def on_cnc_custom_parameters(self, signal_text):
  5647. if signal_text == 'Parameters':
  5648. return
  5649. else:
  5650. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5651. def on_save_button(self):
  5652. log.debug("App.on_save_button() --> Saving preferences to file.")
  5653. # Preferences saved, update flag
  5654. self.preferences_changed_flag = False
  5655. # Preferences save, update the color of the Preferences Tab text
  5656. for idx in range(self.ui.plot_tab_area.count()):
  5657. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5658. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5659. self.save_defaults(silent=False)
  5660. # load the defaults so they are updated into the app
  5661. self.load_defaults(filename='current_defaults')
  5662. # Re-fresh project options
  5663. self.on_options_app2project()
  5664. settgs = QSettings("Open Source", "FlatCAM")
  5665. # save the notebook font size
  5666. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5667. settgs.setValue('notebook_font_size', fsize)
  5668. # save the axis font size
  5669. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5670. settgs.setValue('axis_font_size', g_fsize)
  5671. # save the textbox font size
  5672. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5673. settgs.setValue('textbox_font_size', tb_fsize)
  5674. settgs.setValue(
  5675. 'machinist',
  5676. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  5677. )
  5678. # This will write the setting to the platform specific storage.
  5679. del settgs
  5680. def on_tool_add_keypress(self):
  5681. # ## Current application units in Upper Case
  5682. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5683. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5684. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5685. if notebook_widget_name == 'selected_tab':
  5686. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5687. # Tool add works for Geometry only if Advanced is True in Preferences
  5688. if self.defaults["global_app_level"] == 'a':
  5689. tool_add_popup = FCInputDialog(title="New Tool ...",
  5690. text='Enter a Tool Diameter:',
  5691. min=0.0000, max=99.9999, decimals=4)
  5692. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5693. val, ok = tool_add_popup.get_value()
  5694. if ok:
  5695. if float(val) == 0:
  5696. self.inform.emit('[WARNING_NOTCL] %s' %
  5697. _("Please enter a tool diameter with non-zero value, in Float format."))
  5698. return
  5699. self.collection.get_active().on_tool_add(dia=float(val))
  5700. else:
  5701. self.inform.emit('[WARNING_NOTCL] %s...' %
  5702. _("Adding Tool cancelled"))
  5703. else:
  5704. msgbox = QtWidgets.QMessageBox()
  5705. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5706. "Go to Preferences -> General - Show Advanced Options."))
  5707. msgbox.setWindowTitle("Tool adding ...")
  5708. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5709. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5710. msgbox.setDefaultButton(bt_ok)
  5711. msgbox.exec_()
  5712. # work only if the notebook tab on focus is the Tools_Tab
  5713. if notebook_widget_name == 'tool_tab':
  5714. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5715. # and only if the tool is NCC Tool
  5716. if tool_widget == self.ncclear_tool.toolName:
  5717. self.ncclear_tool.on_add_tool_by_key()
  5718. # and only if the tool is Paint Area Tool
  5719. elif tool_widget == self.paint_tool.toolName:
  5720. self.paint_tool.on_add_tool_by_key()
  5721. # and only if the tool is Solder Paste Dispensing Tool
  5722. elif tool_widget == self.paste_tool.toolName:
  5723. self.paste_tool.on_add_tool_by_key()
  5724. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5725. # See description bellow.
  5726. def on_delete_keypress(self):
  5727. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5728. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5729. if notebook_widget_name == 'selected_tab':
  5730. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5731. self.collection.get_active().on_tool_delete()
  5732. # work only if the notebook tab on focus is the Tools_Tab
  5733. elif notebook_widget_name == 'tool_tab':
  5734. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5735. # and only if the tool is NCC Tool
  5736. if tool_widget == self.ncclear_tool.toolName:
  5737. self.ncclear_tool.on_tool_delete()
  5738. # and only if the tool is Paint Tool
  5739. elif tool_widget == self.paint_tool.toolName:
  5740. self.paint_tool.on_tool_delete()
  5741. # and only if the tool is Solder Paste Dispensing Tool
  5742. elif tool_widget == self.paste_tool.toolName:
  5743. self.paste_tool.on_tool_delete()
  5744. else:
  5745. self.on_delete()
  5746. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5747. # some screens you have to be careful where you hover with your mouse.
  5748. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5749. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5750. # Complicated, I know :)
  5751. def on_delete(self):
  5752. """
  5753. Delete the currently selected FlatCAMObjs.
  5754. :return: None
  5755. """
  5756. self.report_usage("on_delete()")
  5757. response = None
  5758. bt_ok = None
  5759. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5760. # a geometry object before we update it.
  5761. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5762. and self.grb_editor.editor_active is False:
  5763. if self.defaults["global_delete_confirmation"] is True:
  5764. msgbox = QtWidgets.QMessageBox()
  5765. msgbox.setWindowTitle(_("Delete objects"))
  5766. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5767. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5768. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5769. "the selected objects?"))
  5770. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5771. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5772. msgbox.setDefaultButton(bt_ok)
  5773. msgbox.exec_()
  5774. response = msgbox.clickedButton()
  5775. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5776. if self.collection.get_active():
  5777. self.log.debug("App.on_delete()")
  5778. while self.collection.get_active():
  5779. obj_active = self.collection.get_active()
  5780. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5781. if isinstance(obj_active, FlatCAMGerber):
  5782. for el in obj_active.mark_shapes:
  5783. obj_active.mark_shapes[el].clear(update=True)
  5784. obj_active.mark_shapes[el].enabled = False
  5785. # obj_active.mark_shapes[el] = None
  5786. del el
  5787. elif isinstance(obj_active, FlatCAMCNCjob):
  5788. try:
  5789. obj_active.annotation.clear(update=True)
  5790. obj_active.annotation.enabled = False
  5791. except AttributeError:
  5792. pass
  5793. self.delete_first_selected()
  5794. self.inform.emit('%s...' %
  5795. _("Object(s) deleted"))
  5796. # make sure that the selection shape is deleted, too
  5797. self.delete_selection_shape()
  5798. else:
  5799. self.inform.emit(_("Failed. No object(s) selected..."))
  5800. else:
  5801. self.inform.emit(_("Save the work in Editor and try again ..."))
  5802. def delete_first_selected(self):
  5803. # Keep this for later
  5804. try:
  5805. sel_obj = self.collection.get_active()
  5806. name = sel_obj.options["name"]
  5807. isPlotted = sel_obj.options["plot"]
  5808. except AttributeError:
  5809. self.log.debug("Nothing selected for deletion")
  5810. return
  5811. if self.is_legacy is True:
  5812. # Remove plot only if the object was plotted otherwise delaxes will fail
  5813. if isPlotted:
  5814. try:
  5815. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5816. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5817. except Exception as e:
  5818. log.debug("App.delete_first_selected() --> %s" % str(e))
  5819. self.plotcanvas.auto_adjust_axes()
  5820. # Remove from dictionary
  5821. self.collection.delete_active()
  5822. # Clear form
  5823. self.setup_component_editor()
  5824. self.inform.emit('%s: %s' %
  5825. (_("Object deleted"), name))
  5826. def on_set_origin(self):
  5827. """
  5828. Set the origin to the left mouse click position
  5829. :return: None
  5830. """
  5831. # display the message for the user
  5832. # and ask him to click on the desired position
  5833. self.report_usage("on_set_origin()")
  5834. def origin_replot():
  5835. def worker_task():
  5836. with self.proc_container.new('%s...' % _("Plotting")):
  5837. for obj in self.collection.get_list():
  5838. obj.plot()
  5839. self.plotcanvas.fit_view()
  5840. if self.is_legacy:
  5841. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5842. else:
  5843. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5844. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5845. self.inform.emit(_('Click to set the origin ...'))
  5846. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5847. # first disconnect it as it may have been used by something else
  5848. try:
  5849. self.replot_signal.disconnect()
  5850. except TypeError:
  5851. pass
  5852. self.replot_signal[list].connect(origin_replot)
  5853. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  5854. """
  5855. :param event:
  5856. :param location:
  5857. :param noplot:
  5858. :param use_thread:
  5859. :return:
  5860. """
  5861. noplot_sig = noplot
  5862. def worker_task():
  5863. with self.proc_container.new(_("Setting Origin...")):
  5864. for obj in self.collection.get_list():
  5865. obj.offset((x, y))
  5866. self.object_changed.emit(obj)
  5867. # Update the object bounding box options
  5868. a, b, c, d = obj.bounds()
  5869. obj.options['xmin'] = a
  5870. obj.options['ymin'] = b
  5871. obj.options['xmax'] = c
  5872. obj.options['ymax'] = d
  5873. self.inform.emit('[success] %s...' %
  5874. _('Origin set'))
  5875. if noplot_sig is False:
  5876. self.replot_signal.emit([])
  5877. if location is not None:
  5878. if len(location) != 2:
  5879. self.inform.emit('[ERROR_NOTCL] %s...' %
  5880. _("Origin coordinates specified but incomplete."))
  5881. return 'fail'
  5882. x, y = location
  5883. if use_thread is True:
  5884. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5885. else:
  5886. worker_task()
  5887. self.should_we_save = True
  5888. return
  5889. if event.button == 1:
  5890. if self.is_legacy is False:
  5891. event_pos = event.pos
  5892. else:
  5893. event_pos = (event.xdata, event.ydata)
  5894. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5895. if self.grid_status() == True:
  5896. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5897. else:
  5898. pos = pos_canvas
  5899. x = 0 - pos[0]
  5900. y = 0 - pos[1]
  5901. if use_thread is True:
  5902. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5903. else:
  5904. worker_task()
  5905. self.should_we_save = True
  5906. def on_jump_to(self, custom_location=None, fit_center=True):
  5907. """
  5908. Jump to a location by setting the mouse cursor location
  5909. :return:
  5910. """
  5911. self.report_usage("on_jump_to()")
  5912. # if self.is_legacy is True:
  5913. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  5914. # return
  5915. if not custom_location:
  5916. dia_box_location = None
  5917. try:
  5918. dia_box_location = eval(self.clipboard.text())
  5919. except Exception:
  5920. pass
  5921. if type(dia_box_location) == tuple:
  5922. dia_box_location = str(dia_box_location)
  5923. else:
  5924. dia_box_location = None
  5925. dia_box = Dialog_box(title=_("Jump to ..."),
  5926. label=_("Enter the coordinates in format X,Y:"),
  5927. icon=QtGui.QIcon('share/jump_to16.png'),
  5928. initial_text=dia_box_location)
  5929. if dia_box.ok is True:
  5930. try:
  5931. location = eval(dia_box.location)
  5932. if not isinstance(location, tuple):
  5933. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5934. return
  5935. except Exception:
  5936. return
  5937. else:
  5938. return
  5939. else:
  5940. location = custom_location
  5941. if fit_center:
  5942. self.plotcanvas.fit_center(loc=location)
  5943. cursor = QtGui.QCursor()
  5944. if self.is_legacy is False:
  5945. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5946. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5947. j_pos = (canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5948. cursor.setPos(j_pos[0], j_pos[1])
  5949. else:
  5950. # find the canvas origin which is in the top left corner
  5951. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5952. # determine the coordinates for the lowest left point of the canvas
  5953. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5954. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  5955. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  5956. # canvas) and the point (width, height) is in the top-right location
  5957. loc = self.plotcanvas.axes.transData.transform_point(location)
  5958. j_pos = (x0 + loc[0], y0 - loc[1])
  5959. cursor.setPos(j_pos[0], j_pos[1])
  5960. if self.grid_status() == True:
  5961. # Update cursor
  5962. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  5963. symbol='++', edge_color=self.cursor_color_3D,
  5964. size=self.defaults["global_cursor_size"])
  5965. # Set the position label
  5966. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5967. "<b>Y</b>: %.4f" % (location[0], location[1]))
  5968. # Set the relative position label
  5969. dx = location[0] - float(self.rel_point1[0])
  5970. dy = location[1] - float(self.rel_point1[1])
  5971. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5972. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5973. self.inform.emit('[success] %s' %
  5974. _("Done."))
  5975. return location
  5976. def on_copy_object(self):
  5977. self.report_usage("on_copy_object()")
  5978. def initialize(obj_init, app):
  5979. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5980. try:
  5981. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5982. except AttributeError:
  5983. pass
  5984. try:
  5985. obj_init.apertures = deepcopy(obj.apertures)
  5986. except AttributeError:
  5987. pass
  5988. try:
  5989. if obj.tools:
  5990. obj_init.tools = deepcopy(obj.tools)
  5991. except Exception as e:
  5992. log.debug("App.on_copy_object() --> %s" % str(e))
  5993. def initialize_excellon(obj_init, app):
  5994. obj_init.tools = deepcopy(obj.tools)
  5995. # drills are offset, so they need to be deep copied
  5996. obj_init.drills = deepcopy(obj.drills)
  5997. # slots are offset, so they need to be deep copied
  5998. obj_init.slots = deepcopy(obj.slots)
  5999. obj_init.create_geometry()
  6000. def initialize_script(obj_init, app_obj):
  6001. obj_init.source_file = deepcopy(obj.source_file)
  6002. def initialize_document(obj_init, app_obj):
  6003. obj_init.source_file = deepcopy(obj.source_file)
  6004. for obj in self.collection.get_selected():
  6005. obj_name = obj.options["name"]
  6006. try:
  6007. if isinstance(obj, FlatCAMExcellon):
  6008. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6009. elif isinstance(obj, FlatCAMGerber):
  6010. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6011. elif isinstance(obj, FlatCAMGeometry):
  6012. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6013. elif isinstance(obj, FlatCAMScript):
  6014. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6015. elif isinstance(obj, FlatCAMDocument):
  6016. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6017. except Exception as e:
  6018. return "Operation failed: %s" % str(e)
  6019. def on_copy_object2(self, custom_name):
  6020. def initialize_geometry(obj_init, app):
  6021. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6022. try:
  6023. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6024. except AttributeError:
  6025. pass
  6026. try:
  6027. obj_init.apertures = deepcopy(obj.apertures)
  6028. except AttributeError:
  6029. pass
  6030. try:
  6031. if obj.tools:
  6032. obj_init.tools = deepcopy(obj.tools)
  6033. except Exception as ee:
  6034. log.debug("on_copy_object2() --> %s" % str(ee))
  6035. def initialize_gerber(obj_init, app):
  6036. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6037. obj_init.apertures = deepcopy(obj.apertures)
  6038. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6039. def initialize_excellon(obj_init, app):
  6040. obj_init.tools = deepcopy(obj.tools)
  6041. # drills are offset, so they need to be deep copied
  6042. obj_init.drills = deepcopy(obj.drills)
  6043. # slots are offset, so they need to be deep copied
  6044. obj_init.slots = deepcopy(obj.slots)
  6045. obj_init.create_geometry()
  6046. for obj in self.collection.get_selected():
  6047. obj_name = obj.options["name"]
  6048. try:
  6049. if isinstance(obj, FlatCAMExcellon):
  6050. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6051. elif isinstance(obj, FlatCAMGerber):
  6052. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6053. elif isinstance(obj, FlatCAMGeometry):
  6054. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6055. except Exception as e:
  6056. return "Operation failed: %s" % str(e)
  6057. def on_rename_object(self, text):
  6058. self.report_usage("on_rename_object()")
  6059. named_obj = self.collection.get_active()
  6060. for obj in named_obj:
  6061. if obj is list:
  6062. self.on_rename_object(text)
  6063. else:
  6064. try:
  6065. obj.options['name'] = text
  6066. except Exception as e:
  6067. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6068. def convert_any2geo(self):
  6069. self.report_usage("convert_any2geo()")
  6070. def initialize(obj_init, app):
  6071. obj_init.solid_geometry = obj.solid_geometry
  6072. try:
  6073. obj_init.follow_geometry = obj.follow_geometry
  6074. except AttributeError:
  6075. pass
  6076. try:
  6077. obj_init.apertures = obj.apertures
  6078. except AttributeError:
  6079. pass
  6080. try:
  6081. if obj.tools:
  6082. obj_init.tools = obj.tools
  6083. except AttributeError:
  6084. pass
  6085. def initialize_excellon(obj_init, app):
  6086. # objs = self.collection.get_selected()
  6087. # FlatCAMGeometry.merge(objs, obj)
  6088. solid_geo = []
  6089. for tool in obj.tools:
  6090. for geo in obj.tools[tool]['solid_geometry']:
  6091. solid_geo.append(geo)
  6092. obj_init.solid_geometry = deepcopy(solid_geo)
  6093. if not self.collection.get_selected():
  6094. log.warning("App.convert_any2geo --> No object selected")
  6095. self.inform.emit('[WARNING_NOTCL] %s' %
  6096. _("No object is selected. Select an object and try again."))
  6097. return
  6098. for obj in self.collection.get_selected():
  6099. obj_name = obj.options["name"]
  6100. try:
  6101. if isinstance(obj, FlatCAMExcellon):
  6102. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6103. else:
  6104. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6105. except Exception as e:
  6106. return "Operation failed: %s" % str(e)
  6107. def convert_any2gerber(self):
  6108. self.report_usage("convert_any2gerber()")
  6109. def initialize_geometry(obj_init, app):
  6110. apertures = {}
  6111. apid = 0
  6112. apertures[str(apid)] = {}
  6113. apertures[str(apid)]['geometry'] = []
  6114. for obj_orig in obj.solid_geometry:
  6115. new_elem = dict()
  6116. new_elem['solid'] = obj_orig
  6117. try:
  6118. new_elem['follow'] = obj_orig.exterior
  6119. except AttributeError:
  6120. pass
  6121. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6122. apertures[str(apid)]['size'] = 0.0
  6123. apertures[str(apid)]['type'] = 'C'
  6124. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6125. obj_init.apertures = deepcopy(apertures)
  6126. def initialize_excellon(obj_init, app):
  6127. apertures = {}
  6128. apid = 10
  6129. for tool in obj.tools:
  6130. apertures[str(apid)] = {}
  6131. apertures[str(apid)]['geometry'] = []
  6132. for geo in obj.tools[tool]['solid_geometry']:
  6133. new_el = dict()
  6134. new_el['solid'] = geo
  6135. new_el['follow'] = geo.exterior
  6136. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6137. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6138. apertures[str(apid)]['type'] = 'C'
  6139. apid += 1
  6140. # create solid_geometry
  6141. solid_geometry = []
  6142. for apid in apertures:
  6143. for geo_el in apertures[apid]['geometry']:
  6144. solid_geometry.append(geo_el['solid'])
  6145. solid_geometry = MultiPolygon(solid_geometry)
  6146. solid_geometry = solid_geometry.buffer(0.0000001)
  6147. obj_init.solid_geometry = deepcopy(solid_geometry)
  6148. obj_init.apertures = deepcopy(apertures)
  6149. # clear the working objects (perhaps not necessary due of Python GC)
  6150. apertures.clear()
  6151. if not self.collection.get_selected():
  6152. log.warning("App.convert_any2gerber --> No object selected")
  6153. self.inform.emit('[WARNING_NOTCL] %s' %
  6154. _("No object is selected. Select an object and try again."))
  6155. return
  6156. for obj in self.collection.get_selected():
  6157. obj_name = obj.options["name"]
  6158. try:
  6159. if isinstance(obj, FlatCAMExcellon):
  6160. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6161. elif isinstance(obj, FlatCAMGeometry):
  6162. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6163. else:
  6164. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6165. except Exception as e:
  6166. return "Operation failed: %s" % str(e)
  6167. def abort_all_tasks(self):
  6168. if self.abort_flag is False:
  6169. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6170. self.abort_flag = True
  6171. def app_is_idle(self):
  6172. if self.abort_flag:
  6173. self.inform.emit('[WARNING_NOTCL] %s' %
  6174. _("The current task was gracefully closed on user request..."))
  6175. self.abort_flag = False
  6176. def on_selectall(self):
  6177. self.report_usage("on_selectall()")
  6178. # delete the possible selection box around a possible selected object
  6179. self.delete_selection_shape()
  6180. for name in self.collection.get_names():
  6181. self.collection.set_active(name)
  6182. curr_sel_obj = self.collection.get_by_name(name)
  6183. # create the selection box around the selected object
  6184. if self.defaults['global_selection_shape'] is True:
  6185. self.draw_selection_shape(curr_sel_obj)
  6186. def on_preferences(self):
  6187. """
  6188. Adds the Preferences in a Tab in Plot Area
  6189. :return:
  6190. """
  6191. # add the tab if it was closed
  6192. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6193. # delete the absolute and relative position and messages in the infobar
  6194. self.ui.position_label.setText("")
  6195. self.ui.rel_position_label.setText("")
  6196. # Switch plot_area to preferences page
  6197. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6198. # self.ui.show()
  6199. # detect changes in the preferences
  6200. for idx in range(self.ui.pref_tab_area.count()):
  6201. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6202. try:
  6203. try:
  6204. tb.textEdited.disconnect(self.on_preferences_edited)
  6205. except (TypeError, AttributeError):
  6206. pass
  6207. tb.textEdited.connect(self.on_preferences_edited)
  6208. except AttributeError:
  6209. pass
  6210. try:
  6211. try:
  6212. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6213. except (TypeError, AttributeError):
  6214. pass
  6215. tb.modificationChanged.connect(self.on_preferences_edited)
  6216. except AttributeError:
  6217. pass
  6218. try:
  6219. try:
  6220. tb.toggled.disconnect(self.on_preferences_edited)
  6221. except (TypeError, AttributeError):
  6222. pass
  6223. tb.toggled.connect(self.on_preferences_edited)
  6224. except AttributeError:
  6225. pass
  6226. try:
  6227. try:
  6228. tb.valueChanged.disconnect(self.on_preferences_edited)
  6229. except (TypeError, AttributeError):
  6230. pass
  6231. tb.valueChanged.connect(self.on_preferences_edited)
  6232. except AttributeError:
  6233. pass
  6234. try:
  6235. try:
  6236. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6237. except (TypeError, AttributeError):
  6238. pass
  6239. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6240. except AttributeError:
  6241. pass
  6242. def on_preferences_edited(self):
  6243. self.inform.emit('[WARNING_NOTCL] %s' %
  6244. _("Preferences edited but not saved."))
  6245. for idx in range(self.ui.plot_tab_area.count()):
  6246. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  6247. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6248. self.preferences_changed_flag = True
  6249. def on_tools_database(self):
  6250. """
  6251. Adds the Tools Database in a Tab in Plot Area
  6252. :return:
  6253. """
  6254. for idx in range(self.ui.plot_tab_area.count()):
  6255. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6256. # there can be only one instance of Tools Database at one time
  6257. return
  6258. self.tools_db_tab = ToolsDB(
  6259. app=self,
  6260. parent=self.ui,
  6261. callback_on_edited=self.on_tools_db_edited,
  6262. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  6263. )
  6264. # add the tab if it was closed
  6265. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  6266. self.tools_db_tab.setObjectName("database_tab")
  6267. # delete the absolute and relative position and messages in the infobar
  6268. self.ui.position_label.setText("")
  6269. self.ui.rel_position_label.setText("")
  6270. # Switch plot_area to preferences page
  6271. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  6272. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  6273. self.tools_db_tab.ui_connect()
  6274. def on_tools_db_edited(self):
  6275. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  6276. for idx in range(self.ui.plot_tab_area.count()):
  6277. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6278. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6279. self.tools_db_changed_flag = True
  6280. def on_geometry_tool_add_from_db_executed(self, tool):
  6281. """
  6282. Here add the tool from DB in the selected geometry object
  6283. :return:
  6284. """
  6285. tool_from_db = deepcopy(tool)
  6286. obj = self.collection.get_active()
  6287. if isinstance(obj, FlatCAMGeometry):
  6288. obj.on_tool_from_db_inserted(tool=tool_from_db)
  6289. for idx in range(self.ui.plot_tab_area.count()):
  6290. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6291. wdg = self.ui.plot_tab_area.widget(idx)
  6292. wdg.deleteLater()
  6293. self.ui.plot_tab_area.removeTab(idx)
  6294. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  6295. else:
  6296. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  6297. def on_plot_area_tab_closed(self, title):
  6298. if title == _("Preferences"):
  6299. # disconnect
  6300. for idx in range(self.ui.pref_tab_area.count()):
  6301. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6302. try:
  6303. tb.textEdited.disconnect(self.on_preferences_edited)
  6304. except (TypeError, AttributeError):
  6305. pass
  6306. try:
  6307. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6308. except (TypeError, AttributeError):
  6309. pass
  6310. try:
  6311. tb.toggled.disconnect(self.on_preferences_edited)
  6312. except (TypeError, AttributeError):
  6313. pass
  6314. try:
  6315. tb.valueChanged.disconnect(self.on_preferences_edited)
  6316. except (TypeError, AttributeError):
  6317. pass
  6318. try:
  6319. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6320. except (TypeError, AttributeError):
  6321. pass
  6322. if self.preferences_changed_flag is True:
  6323. msgbox = QtWidgets.QMessageBox()
  6324. msgbox.setText(_("One or more values are changed.\n"
  6325. "Do you want to save the Preferences?"))
  6326. msgbox.setWindowTitle(_("Save Preferences"))
  6327. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6328. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6329. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6330. msgbox.setDefaultButton(bt_yes)
  6331. msgbox.exec_()
  6332. response = msgbox.clickedButton()
  6333. if response == bt_yes:
  6334. self.on_save_button()
  6335. self.inform.emit('[success] %s' % _("Preferences saved."))
  6336. else:
  6337. self.preferences_changed_flag = False
  6338. self.inform.emit('')
  6339. return
  6340. if title == _("Tools Database"):
  6341. # disconnect the signals from the table widget in tab
  6342. self.tools_db_tab.ui_disconnect()
  6343. if self.tools_db_changed_flag is True:
  6344. msgbox = QtWidgets.QMessageBox()
  6345. msgbox.setText(_("One or more Tools are edited.\n"
  6346. "Do you want to update the Tools Database?"))
  6347. msgbox.setWindowTitle(_("Save Tools Database"))
  6348. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6349. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6350. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6351. msgbox.setDefaultButton(bt_yes)
  6352. msgbox.exec_()
  6353. response = msgbox.clickedButton()
  6354. if response == bt_yes:
  6355. self.tools_db_tab.on_save_tools_db()
  6356. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6357. else:
  6358. self.tools_db_changed_flag = False
  6359. self.inform.emit('')
  6360. return
  6361. self.tools_db_tab.deleteLater()
  6362. if title == _("Code Editor"):
  6363. self.toggle_codeeditor = False
  6364. if title == _("Bookmarks Manager"):
  6365. self.book_dialog_tab.rebuild_actions()
  6366. self.book_dialog_tab.deleteLater()
  6367. def on_flipy(self):
  6368. self.report_usage("on_flipy()")
  6369. obj_list = self.collection.get_selected()
  6370. xminlist = []
  6371. yminlist = []
  6372. xmaxlist = []
  6373. ymaxlist = []
  6374. if not obj_list:
  6375. self.inform.emit('[WARNING_NOTCL] %s' %
  6376. _("No object selected to Flip on Y axis."))
  6377. else:
  6378. try:
  6379. # first get a bounding box to fit all
  6380. for obj in obj_list:
  6381. xmin, ymin, xmax, ymax = obj.bounds()
  6382. xminlist.append(xmin)
  6383. yminlist.append(ymin)
  6384. xmaxlist.append(xmax)
  6385. ymaxlist.append(ymax)
  6386. # get the minimum x,y and maximum x,y for all objects selected
  6387. xminimal = min(xminlist)
  6388. yminimal = min(yminlist)
  6389. xmaximal = max(xmaxlist)
  6390. ymaximal = max(ymaxlist)
  6391. px = 0.5 * (xminimal + xmaximal)
  6392. py = 0.5 * (yminimal + ymaximal)
  6393. # execute mirroring
  6394. for obj in obj_list:
  6395. obj.mirror('X', [px, py])
  6396. obj.plot()
  6397. self.object_changed.emit(obj)
  6398. self.inform.emit('[success] %s' %
  6399. _("Flip on Y axis done."))
  6400. except Exception as e:
  6401. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6402. return
  6403. def on_flipx(self):
  6404. self.report_usage("on_flipx()")
  6405. obj_list = self.collection.get_selected()
  6406. xminlist = []
  6407. yminlist = []
  6408. xmaxlist = []
  6409. ymaxlist = []
  6410. if not obj_list:
  6411. self.inform.emit('[WARNING_NOTCL] %s' %
  6412. _("No object selected to Flip on X axis."))
  6413. else:
  6414. try:
  6415. # first get a bounding box to fit all
  6416. for obj in obj_list:
  6417. xmin, ymin, xmax, ymax = obj.bounds()
  6418. xminlist.append(xmin)
  6419. yminlist.append(ymin)
  6420. xmaxlist.append(xmax)
  6421. ymaxlist.append(ymax)
  6422. # get the minimum x,y and maximum x,y for all objects selected
  6423. xminimal = min(xminlist)
  6424. yminimal = min(yminlist)
  6425. xmaximal = max(xmaxlist)
  6426. ymaximal = max(ymaxlist)
  6427. px = 0.5 * (xminimal + xmaximal)
  6428. py = 0.5 * (yminimal + ymaximal)
  6429. # execute mirroring
  6430. for obj in obj_list:
  6431. obj.mirror('Y', [px, py])
  6432. obj.plot()
  6433. self.object_changed.emit(obj)
  6434. self.inform.emit('[success] %s' %
  6435. _("Flip on X axis done."))
  6436. except Exception as e:
  6437. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6438. return
  6439. def on_rotate(self, silent=False, preset=None):
  6440. self.report_usage("on_rotate()")
  6441. obj_list = self.collection.get_selected()
  6442. xminlist = []
  6443. yminlist = []
  6444. xmaxlist = []
  6445. ymaxlist = []
  6446. if not obj_list:
  6447. self.inform.emit('[WARNING_NOTCL] %s' %
  6448. _("No object selected to Rotate."))
  6449. else:
  6450. if silent is False:
  6451. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6452. min=-360, max=360, decimals=4,
  6453. init_val=float(self.defaults['tools_transform_rotate']))
  6454. num, ok = rotatebox.get_value()
  6455. else:
  6456. num = preset
  6457. ok = True
  6458. if ok:
  6459. try:
  6460. # first get a bounding box to fit all
  6461. for obj in obj_list:
  6462. xmin, ymin, xmax, ymax = obj.bounds()
  6463. xminlist.append(xmin)
  6464. yminlist.append(ymin)
  6465. xmaxlist.append(xmax)
  6466. ymaxlist.append(ymax)
  6467. # get the minimum x,y and maximum x,y for all objects selected
  6468. xminimal = min(xminlist)
  6469. yminimal = min(yminlist)
  6470. xmaximal = max(xmaxlist)
  6471. ymaximal = max(ymaxlist)
  6472. px = 0.5 * (xminimal + xmaximal)
  6473. py = 0.5 * (yminimal + ymaximal)
  6474. for sel_obj in obj_list:
  6475. sel_obj.rotate(-float(num), point=(px, py))
  6476. sel_obj.plot()
  6477. self.object_changed.emit(sel_obj)
  6478. self.inform.emit('[success] %s' %
  6479. _("Rotation done."))
  6480. except Exception as e:
  6481. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6482. return
  6483. def on_skewx(self):
  6484. self.report_usage("on_skewx()")
  6485. obj_list = self.collection.get_selected()
  6486. xminlist = []
  6487. yminlist = []
  6488. if not obj_list:
  6489. self.inform.emit('[WARNING_NOTCL] %s' %
  6490. _("No object selected to Skew/Shear on X axis."))
  6491. else:
  6492. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6493. min=-360, max=360, decimals=4,
  6494. init_val=float(self.defaults['tools_transform_skew_x']))
  6495. num, ok = skewxbox.get_value()
  6496. if ok:
  6497. # first get a bounding box to fit all
  6498. for obj in obj_list:
  6499. xmin, ymin, xmax, ymax = obj.bounds()
  6500. xminlist.append(xmin)
  6501. yminlist.append(ymin)
  6502. # get the minimum x,y and maximum x,y for all objects selected
  6503. xminimal = min(xminlist)
  6504. yminimal = min(yminlist)
  6505. for obj in obj_list:
  6506. obj.skew(num, 0, point=(xminimal, yminimal))
  6507. obj.plot()
  6508. self.object_changed.emit(obj)
  6509. self.inform.emit('[success] %s' %
  6510. _("Skew on X axis done."))
  6511. def on_skewy(self):
  6512. self.report_usage("on_skewy()")
  6513. obj_list = self.collection.get_selected()
  6514. xminlist = []
  6515. yminlist = []
  6516. if not obj_list:
  6517. self.inform.emit('[WARNING_NOTCL] %s' %
  6518. _("No object selected to Skew/Shear on Y axis."))
  6519. else:
  6520. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6521. min=-360, max=360, decimals=4,
  6522. init_val=float(self.defaults['tools_transform_skew_y']))
  6523. num, ok = skewybox.get_value()
  6524. if ok:
  6525. # first get a bounding box to fit all
  6526. for obj in obj_list:
  6527. xmin, ymin, xmax, ymax = obj.bounds()
  6528. xminlist.append(xmin)
  6529. yminlist.append(ymin)
  6530. # get the minimum x,y and maximum x,y for all objects selected
  6531. xminimal = min(xminlist)
  6532. yminimal = min(yminlist)
  6533. for obj in obj_list:
  6534. obj.skew(0, num, point=(xminimal, yminimal))
  6535. obj.plot()
  6536. self.object_changed.emit(obj)
  6537. self.inform.emit('[success] %s' %
  6538. _("Skew on Y axis done."))
  6539. def on_plots_updated(self):
  6540. """
  6541. Callback used to report when the plots have changed.
  6542. Adjust axes and zooms to fit.
  6543. :return: None
  6544. """
  6545. if self.is_legacy is False:
  6546. self.plotcanvas.update() # TODO: Need update canvas?
  6547. else:
  6548. self.plotcanvas.auto_adjust_axes()
  6549. self.on_zoom_fit(None)
  6550. self.collection.update_view()
  6551. # self.inform.emit(_("Plots updated ..."))
  6552. # TODO: Rework toolbar 'clear', 'replot' functions
  6553. def on_toolbar_replot(self):
  6554. """
  6555. Callback for toolbar button. Re-plots all objects.
  6556. :return: None
  6557. """
  6558. self.report_usage("on_toolbar_replot")
  6559. self.log.debug("on_toolbar_replot()")
  6560. try:
  6561. self.collection.get_active().read_form()
  6562. except AttributeError:
  6563. self.log.debug("on_toolbar_replot(): AttributeError")
  6564. pass
  6565. self.plot_all()
  6566. def on_row_activated(self, index):
  6567. if index.isValid():
  6568. if index.internalPointer().parent_item != self.collection.root_item:
  6569. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6570. self.collection.on_item_activated(index)
  6571. def on_row_selected(self, obj_name):
  6572. # this is a special string; when received it will make all entries unchecked
  6573. # it mean we clicked outside of the items and deselected all
  6574. if obj_name == 'none':
  6575. for act in self.ui.menuobjects.actions():
  6576. act.setChecked(False)
  6577. return
  6578. # get the name of the selected objects and add them to a list
  6579. name_list = list()
  6580. for obj in self.collection.get_selected():
  6581. name_list.append(obj.options['name'])
  6582. # set all actions as unchecked but the ones selected make them checked
  6583. for act in self.ui.menuobjects.actions():
  6584. act.setChecked(False)
  6585. if act.text() in name_list:
  6586. act.setChecked(True)
  6587. def on_collection_updated(self, obj, state, old_name):
  6588. """
  6589. Create a menu from the object loaded in the collection.
  6590. TODO: should use the collection model to do this
  6591. :param obj: object that was changd (added, deleted, renamed)
  6592. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6593. :param old_name: the old name of the object before the action that triggered this slot happened
  6594. :return: None
  6595. """
  6596. icon_files = {
  6597. "gerber": "share/flatcam_icon16.png",
  6598. "excellon": "share/drill16.png",
  6599. "cncjob": "share/cnc16.png",
  6600. "geometry": "share/geometry16.png",
  6601. "script": "share/script_new16.png",
  6602. "document": "share/notes16_1.png"
  6603. }
  6604. if state == 'append':
  6605. for act in self.ui.menuobjects.actions():
  6606. try:
  6607. act.triggered.disconnect()
  6608. except TypeError:
  6609. pass
  6610. self.ui.menuobjects.clear()
  6611. gerber_list = list()
  6612. exc_list = list()
  6613. cncjob_list = list()
  6614. geo_list = list()
  6615. script_list = list()
  6616. doc_list = list()
  6617. for name in self.collection.get_names():
  6618. obj_named = self.collection.get_by_name(name)
  6619. if obj_named.kind == 'gerber':
  6620. gerber_list.append(name)
  6621. elif obj_named.kind == 'excellon':
  6622. exc_list.append(name)
  6623. elif obj_named.kind == 'cncjob':
  6624. cncjob_list.append(name)
  6625. elif obj_named.kind == 'geometry':
  6626. geo_list.append(name)
  6627. elif obj_named.kind == 'script':
  6628. script_list.append(name)
  6629. elif obj_named.kind == 'document':
  6630. doc_list.append(name)
  6631. def add_act(o_name):
  6632. obj_for_icon = self.collection.get_by_name(o_name)
  6633. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6634. add_action.setCheckable(True)
  6635. add_action.setText(o_name)
  6636. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6637. add_action.triggered.connect(
  6638. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  6639. self.collection.set_inactive(o_name))
  6640. self.ui.menuobjects.addAction(add_action)
  6641. for name in gerber_list:
  6642. add_act(name)
  6643. self.ui.menuobjects.addSeparator()
  6644. for name in exc_list:
  6645. add_act(name)
  6646. self.ui.menuobjects.addSeparator()
  6647. for name in cncjob_list:
  6648. add_act(name)
  6649. self.ui.menuobjects.addSeparator()
  6650. for name in geo_list:
  6651. add_act(name)
  6652. self.ui.menuobjects.addSeparator()
  6653. for name in script_list:
  6654. add_act(name)
  6655. self.ui.menuobjects.addSeparator()
  6656. for name in doc_list:
  6657. add_act(name)
  6658. self.ui.menuobjects.addSeparator()
  6659. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6660. QtGui.QIcon('share/select_all.png'),
  6661. _('Select All')
  6662. )
  6663. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6664. QtGui.QIcon('share/deselect_all32.png'),
  6665. _('Deselect All')
  6666. )
  6667. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6668. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6669. elif state == 'delete':
  6670. for act in self.ui.menuobjects.actions():
  6671. if act.text() == obj.options['name']:
  6672. try:
  6673. act.triggered.disconnect()
  6674. except TypeError:
  6675. pass
  6676. self.ui.menuobjects.removeAction(act)
  6677. break
  6678. elif state == 'rename':
  6679. for act in self.ui.menuobjects.actions():
  6680. if act.text() == old_name:
  6681. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6682. add_action.setText(obj.options['name'])
  6683. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6684. add_action.triggered.connect(
  6685. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  6686. self.collection.set_inactive(obj.options['name']))
  6687. self.ui.menuobjects.insertAction(act, add_action)
  6688. try:
  6689. act.triggered.disconnect()
  6690. except TypeError:
  6691. pass
  6692. self.ui.menuobjects.removeAction(act)
  6693. break
  6694. elif state == 'delete_all':
  6695. for act in self.ui.menuobjects.actions():
  6696. try:
  6697. act.triggered.disconnect()
  6698. except TypeError:
  6699. pass
  6700. self.ui.menuobjects.clear()
  6701. self.ui.menuobjects.addSeparator()
  6702. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6703. QtGui.QIcon('share/select_all.png'),
  6704. _('Select All')
  6705. )
  6706. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6707. QtGui.QIcon('share/deselect_all32.png'),
  6708. _('Deselect All')
  6709. )
  6710. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6711. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6712. def on_objects_selection(self, on_off):
  6713. obj_list = self.collection.get_names()
  6714. if on_off is True:
  6715. self.collection.set_all_active()
  6716. for act in self.ui.menuobjects.actions():
  6717. try:
  6718. act.setChecked(True)
  6719. except Exception:
  6720. pass
  6721. if obj_list:
  6722. self.inform.emit('[selected] %s' % _("All objects are selected."))
  6723. else:
  6724. self.collection.set_all_inactive()
  6725. for act in self.ui.menuobjects.actions():
  6726. try:
  6727. act.setChecked(False)
  6728. except Exception:
  6729. pass
  6730. self.inform.emit('%s' % _("Objects selection is cleared."))
  6731. def grid_status(self):
  6732. if self.ui.grid_snap_btn.isChecked():
  6733. return True
  6734. else:
  6735. return False
  6736. def populate_cmenu_grids(self):
  6737. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6738. self.ui.cmenu_gridmenu.clear()
  6739. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6740. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6741. grid_toggle.setCheckable(True)
  6742. if self.grid_status() == True:
  6743. grid_toggle.setChecked(True)
  6744. else:
  6745. grid_toggle.setChecked(False)
  6746. self.ui.cmenu_gridmenu.addSeparator()
  6747. for grid in sorted_list:
  6748. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6749. action.triggered.connect(self.set_grid)
  6750. self.ui.cmenu_gridmenu.addSeparator()
  6751. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6752. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6753. grid_add.triggered.connect(self.on_grid_add)
  6754. grid_delete.triggered.connect(self.on_grid_delete)
  6755. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6756. def set_grid(self):
  6757. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6758. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6759. def on_grid_add(self):
  6760. # ## Current application units in lower Case
  6761. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6762. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6763. text=_('Enter a Grid Value:'),
  6764. min=0.0000, max=99.9999, decimals=4)
  6765. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6766. val, ok = grid_add_popup.get_value()
  6767. if ok:
  6768. if float(val) == 0:
  6769. self.inform.emit('[WARNING_NOTCL] %s' %
  6770. _("Please enter a grid value with non-zero value, in Float format."))
  6771. return
  6772. else:
  6773. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6774. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6775. self.inform.emit('[success] %s...' %
  6776. _("New Grid added"))
  6777. else:
  6778. self.inform.emit('[WARNING_NOTCL] %s...' %
  6779. _("Grid already exists"))
  6780. else:
  6781. self.inform.emit('[WARNING_NOTCL] %s...' %
  6782. _("Adding New Grid cancelled"))
  6783. def on_grid_delete(self):
  6784. # ## Current application units in lower Case
  6785. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6786. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6787. text='Enter a Grid Value:',
  6788. min=0.0000, max=99.9999, decimals=4)
  6789. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6790. val, ok = grid_del_popup.get_value()
  6791. if ok:
  6792. if float(val) == 0:
  6793. self.inform.emit('[WARNING_NOTCL] %s' %
  6794. _("Please enter a grid value with non-zero value, in Float format."))
  6795. return
  6796. else:
  6797. try:
  6798. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6799. except ValueError:
  6800. self.inform.emit('[ERROR_NOTCL]%s...' %
  6801. _(" Grid Value does not exist"))
  6802. return
  6803. self.inform.emit('[success] %s...' %
  6804. _("Grid Value deleted"))
  6805. else:
  6806. self.inform.emit('[WARNING_NOTCL] %s...' %
  6807. _("Delete Grid value cancelled"))
  6808. def on_shortcut_list(self):
  6809. self.report_usage("on_shortcut_list()")
  6810. # add the tab if it was closed
  6811. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6812. # delete the absolute and relative position and messages in the infobar
  6813. self.ui.position_label.setText("")
  6814. self.ui.rel_position_label.setText("")
  6815. # Switch plot_area to preferences page
  6816. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6817. # self.ui.show()
  6818. def on_select_tab(self, name):
  6819. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6820. if self.ui.splitter.sizes()[0] == 0:
  6821. self.ui.splitter.setSizes([1, 1])
  6822. else:
  6823. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6824. self.ui.splitter.setSizes([0, 1])
  6825. if name == 'project':
  6826. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6827. elif name == 'selected':
  6828. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6829. elif name == 'tool':
  6830. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6831. def on_copy_name(self):
  6832. self.report_usage("on_copy_name()")
  6833. obj = self.collection.get_active()
  6834. try:
  6835. name = obj.options["name"]
  6836. except AttributeError:
  6837. log.debug("on_copy_name() --> No object selected to copy it's name")
  6838. self.inform.emit('[WARNING_NOTCL]%s' %
  6839. _(" No object selected to copy it's name"))
  6840. return
  6841. self.clipboard.setText(name)
  6842. self.inform.emit(_("Name copied on clipboard ..."))
  6843. def on_mouse_click_over_plot(self, event):
  6844. """
  6845. Default actions are:
  6846. :param event: Contains information about the event, like which button
  6847. was clicked, the pixel coordinates and the axes coordinates.
  6848. :return: None
  6849. """
  6850. self.pos = []
  6851. if self.is_legacy is False:
  6852. event_pos = event.pos
  6853. if self.defaults["global_pan_button"] == '2':
  6854. pan_button = 2
  6855. else:
  6856. pan_button = 3
  6857. # Set the mouse button for panning
  6858. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6859. else:
  6860. event_pos = (event.xdata, event.ydata)
  6861. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6862. if self.defaults["global_pan_button"] == '2':
  6863. pan_button = 3
  6864. else:
  6865. pan_button = 2
  6866. # So it can receive key presses
  6867. self.plotcanvas.native.setFocus()
  6868. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6869. if self.grid_status() == True:
  6870. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6871. else:
  6872. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6873. try:
  6874. if event.button == 1:
  6875. # Reset here the relative coordinates so there is a new reference on the click position
  6876. if self.rel_point1 is None:
  6877. self.rel_point1 = self.pos
  6878. else:
  6879. self.rel_point2 = copy(self.rel_point1)
  6880. self.rel_point1 = self.pos
  6881. self.on_mouse_move_over_plot(event, origin_click=True)
  6882. except Exception as e:
  6883. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6884. def on_mouse_double_click_over_plot(self, event):
  6885. if event.button == 1:
  6886. self.doubleclick = True
  6887. def on_mouse_move_over_plot(self, event, origin_click=None):
  6888. """
  6889. Callback for the mouse motion event over the plot.
  6890. :param event: Contains information about the event.
  6891. :param origin_click
  6892. :return: None
  6893. """
  6894. if self.is_legacy is False:
  6895. event_pos = event.pos
  6896. if self.defaults["global_pan_button"] == '2':
  6897. pan_button = 2
  6898. else:
  6899. pan_button = 3
  6900. event_is_dragging = event.is_dragging
  6901. else:
  6902. event_pos = (event.xdata, event.ydata)
  6903. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6904. if self.defaults["global_pan_button"] == '2':
  6905. pan_button = 3
  6906. else:
  6907. pan_button = 2
  6908. event_is_dragging = self.plotcanvas.is_dragging
  6909. # So it can receive key presses
  6910. self.plotcanvas.native.setFocus()
  6911. self.pos_jump = event_pos
  6912. self.ui.popMenu.mouse_is_panning = False
  6913. if not origin_click:
  6914. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6915. if event.button == pan_button and event_is_dragging == 1:
  6916. self.ui.popMenu.mouse_is_panning = True
  6917. return
  6918. if self.rel_point1 is not None:
  6919. try: # May fail in case mouse not within axes
  6920. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6921. if self.grid_status() == True:
  6922. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6923. # Update cursor
  6924. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6925. symbol='++', edge_color=self.cursor_color_3D,
  6926. size=self.defaults["global_cursor_size"])
  6927. else:
  6928. pos = (pos_canvas[0], pos_canvas[1])
  6929. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6930. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6931. dx = pos[0] - float(self.rel_point1[0])
  6932. dy = pos[1] - float(self.rel_point1[1])
  6933. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6934. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6935. self.mouse = [pos[0], pos[1]]
  6936. # if the mouse is moved and the LMB is clicked then the action is a selection
  6937. if event_is_dragging == 1 and event.button == 1:
  6938. self.delete_selection_shape()
  6939. if dx < 0:
  6940. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6941. face_color=self.defaults['global_alt_sel_fill'])
  6942. self.selection_type = False
  6943. elif dx > 0:
  6944. self.draw_moving_selection_shape(self.pos, pos)
  6945. self.selection_type = True
  6946. else:
  6947. self.selection_type = None
  6948. # hover effect - enabled in Preferences -> General -> GUI Settings
  6949. if self.defaults['global_hover']:
  6950. for obj in self.collection.get_list():
  6951. try:
  6952. # select the object(s) only if it is enabled (plotted)
  6953. if obj.options['plot']:
  6954. if obj not in self.collection.get_selected():
  6955. poly_obj = Polygon(
  6956. [(obj.options['xmin'], obj.options['ymin']),
  6957. (obj.options['xmax'], obj.options['ymin']),
  6958. (obj.options['xmax'], obj.options['ymax']),
  6959. (obj.options['xmin'], obj.options['ymax'])]
  6960. )
  6961. if Point(pos).within(poly_obj):
  6962. if obj.isHovering is False:
  6963. obj.isHovering = True
  6964. obj.notHovering = True
  6965. # create the selection box around the selected object
  6966. self.draw_hover_shape(obj, color='#d1e0e0FF')
  6967. else:
  6968. if obj.notHovering is True:
  6969. obj.notHovering = False
  6970. obj.isHovering = False
  6971. self.delete_hover_shape()
  6972. except Exception:
  6973. # the Exception here will happen if we try to select on screen and we have an
  6974. # newly (and empty) just created Geometry or Excellon object that do not have the
  6975. # xmin, xmax, ymin, ymax options.
  6976. # In this case poly_obj creation (see above) will fail
  6977. pass
  6978. except Exception:
  6979. self.ui.position_label.setText("")
  6980. self.ui.rel_position_label.setText("")
  6981. self.mouse = None
  6982. def on_mouse_click_release_over_plot(self, event):
  6983. """
  6984. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6985. and has been registered in ''self.__init__()''.
  6986. :param event: contains information about the event.
  6987. :return:
  6988. """
  6989. if self.is_legacy is False:
  6990. event_pos = event.pos
  6991. right_button = 2
  6992. else:
  6993. event_pos = (event.xdata, event.ydata)
  6994. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6995. right_button = 3
  6996. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6997. if self.grid_status() == True:
  6998. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6999. else:
  7000. pos = (pos_canvas[0], pos_canvas[1])
  7001. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7002. # canvas menu
  7003. if event.button == right_button: # right click
  7004. if self.ui.popMenu.mouse_is_panning is False:
  7005. self.cursor = QtGui.QCursor()
  7006. self.populate_cmenu_grids()
  7007. self.ui.popMenu.popup(self.cursor.pos())
  7008. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7009. # selection and then select a type of selection ("enclosing" or "touching")
  7010. try:
  7011. if event.button == 1: # left click
  7012. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7013. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7014. if modifiers == QtCore.Qt.ShiftModifier:
  7015. # do not auto open the Project Tab
  7016. self.click_noproject = True
  7017. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  7018. self.inform.emit('[success] %s' %
  7019. _("Coordinates copied to clipboard."))
  7020. return
  7021. if self.doubleclick is True:
  7022. self.doubleclick = False
  7023. if self.collection.get_selected():
  7024. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7025. if self.ui.splitter.sizes()[0] == 0:
  7026. self.ui.splitter.setSizes([1, 1])
  7027. # delete the selection shape(S) as it may be in the way
  7028. self.delete_selection_shape()
  7029. self.delete_hover_shape()
  7030. else:
  7031. if self.selection_type is not None:
  7032. self.selection_area_handler(self.pos, pos, self.selection_type)
  7033. self.selection_type = None
  7034. else:
  7035. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7036. if key_modifier == QtCore.Qt.ShiftModifier:
  7037. mod_key = 'Shift'
  7038. elif key_modifier == QtCore.Qt.ControlModifier:
  7039. mod_key = 'Control'
  7040. else:
  7041. mod_key = None
  7042. if mod_key == self.defaults["global_mselect_key"]:
  7043. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7044. # deselect, and if it's not selected then it will be selected
  7045. # If there is no active command (self.command_active is None) then we check if we clicked
  7046. # on a object by checking the bounding limits against mouse click position
  7047. if self.command_active is None:
  7048. self.select_objects(key='CTRL')
  7049. self.delete_hover_shape()
  7050. else:
  7051. # If there is no active command (self.command_active is None) then we check if we clicked
  7052. # on a object by checking the bounding limits against mouse click position
  7053. if self.command_active is None:
  7054. self.select_objects()
  7055. self.delete_hover_shape()
  7056. except Exception as e:
  7057. log.warning("Error: %s" % str(e))
  7058. return
  7059. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7060. """
  7061. :param start_pos: mouse position when the selection LMB click was done
  7062. :param end_pos: mouse position when the left mouse button is released
  7063. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7064. :return:
  7065. """
  7066. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7067. # delete previous selection shape
  7068. self.delete_selection_shape()
  7069. # make all objects inactive
  7070. self.collection.set_all_inactive()
  7071. for obj in self.collection.get_list():
  7072. try:
  7073. # select the object(s) only if it is enabled (plotted)
  7074. if obj.options['plot']:
  7075. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7076. (obj.options['xmax'], obj.options['ymin']),
  7077. (obj.options['xmax'], obj.options['ymax']),
  7078. (obj.options['xmin'], obj.options['ymax'])])
  7079. if sel_type is True:
  7080. if poly_obj.within(poly_selection):
  7081. # create the selection box around the selected object
  7082. if self.defaults['global_selection_shape'] is True:
  7083. self.draw_selection_shape(obj)
  7084. self.collection.set_active(obj.options['name'])
  7085. else:
  7086. if poly_selection.intersects(poly_obj):
  7087. # create the selection box around the selected object
  7088. if self.defaults['global_selection_shape'] is True:
  7089. self.draw_selection_shape(obj)
  7090. self.collection.set_active(obj.options['name'])
  7091. except Exception as e:
  7092. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7093. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7094. # In this case poly_obj creation (see above) will fail
  7095. log.debug("App.selection_area_handler() --> %s" % str(e))
  7096. def select_objects(self, key=None):
  7097. """
  7098. Will select objects clicked on canvas
  7099. :param key: for future use in cumulative selection
  7100. :return:
  7101. """
  7102. # list where we store the overlapped objects under our mouse left click position
  7103. objects_under_the_click_list = []
  7104. # Populate the list with the overlapped objects on the click position
  7105. curr_x, curr_y = self.pos
  7106. for obj in self.all_objects_list:
  7107. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7108. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7109. if obj.options['name'] not in objects_under_the_click_list:
  7110. if obj.options['plot']:
  7111. # add objects to the objects_under_the_click list only if the object is plotted
  7112. # (active and not disabled)
  7113. objects_under_the_click_list.append(obj.options['name'])
  7114. try:
  7115. if objects_under_the_click_list:
  7116. curr_sel_obj = self.collection.get_active()
  7117. # case when there is only an object under the click and we toggle it
  7118. if len(objects_under_the_click_list) == 1:
  7119. if curr_sel_obj is None:
  7120. self.collection.set_active(objects_under_the_click_list[0])
  7121. curr_sel_obj = self.collection.get_active()
  7122. # create the selection box around the selected object
  7123. if self.defaults['global_selection_shape'] is True:
  7124. self.draw_selection_shape(curr_sel_obj)
  7125. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  7126. self.on_objects_selection(False)
  7127. self.delete_selection_shape()
  7128. self.collection.set_active(objects_under_the_click_list[0])
  7129. curr_sel_obj = self.collection.get_active()
  7130. # create the selection box around the selected object
  7131. if self.defaults['global_selection_shape'] is True:
  7132. self.draw_selection_shape(curr_sel_obj)
  7133. self.selected_message(curr_sel_obj=curr_sel_obj)
  7134. else:
  7135. self.on_objects_selection(False)
  7136. self.delete_selection_shape()
  7137. if self.call_source != 'app':
  7138. self.call_source = 'app'
  7139. self.selected_message(curr_sel_obj=curr_sel_obj)
  7140. else:
  7141. # If there is no selected object
  7142. # make active the first element of the overlapped objects list
  7143. if self.collection.get_active() is None:
  7144. self.collection.set_active(objects_under_the_click_list[0])
  7145. name_sel_obj = self.collection.get_active().options['name']
  7146. # In case that there is a selected object but it is not in the overlapped object list
  7147. # make that object inactive and activate the first element in the overlapped object list
  7148. if name_sel_obj not in objects_under_the_click_list:
  7149. self.collection.set_inactive(name_sel_obj)
  7150. name_sel_obj = objects_under_the_click_list[0]
  7151. self.collection.set_active(name_sel_obj)
  7152. else:
  7153. sel_idx = objects_under_the_click_list.index(name_sel_obj)
  7154. self.collection.set_all_inactive()
  7155. self.collection.set_active(objects_under_the_click_list[(sel_idx + 1) %
  7156. len(objects_under_the_click_list)])
  7157. curr_sel_obj = self.collection.get_active()
  7158. # delete the possible selection box around a possible selected object
  7159. self.delete_selection_shape()
  7160. # create the selection box around the selected object
  7161. if self.defaults['global_selection_shape'] is True:
  7162. self.draw_selection_shape(curr_sel_obj)
  7163. self.selected_message(curr_sel_obj=curr_sel_obj)
  7164. else:
  7165. # deselect everything
  7166. self.on_objects_selection(False)
  7167. # delete the possible selection box around a possible selected object
  7168. self.delete_selection_shape()
  7169. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7170. # only when working on App
  7171. if self.call_source == 'app':
  7172. if self.click_noproject is False:
  7173. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7174. else:
  7175. # restore auto open the Project Tab
  7176. self.click_noproject = False
  7177. # delete any text in the status bar, implicitly the last object name that was selected
  7178. # self.inform.emit("")
  7179. else:
  7180. self.call_source = 'app'
  7181. except Exception as e:
  7182. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7183. def selected_message(self, curr_sel_obj):
  7184. if curr_sel_obj:
  7185. if curr_sel_obj.kind == 'gerber':
  7186. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7187. color='green', name=str(curr_sel_obj.options['name'])))
  7188. elif curr_sel_obj.kind == 'excellon':
  7189. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7190. color='brown', name=str(curr_sel_obj.options['name'])))
  7191. elif curr_sel_obj.kind == 'cncjob':
  7192. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7193. color='blue', name=str(curr_sel_obj.options['name'])))
  7194. elif curr_sel_obj.kind == 'geometry':
  7195. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7196. color='red', name=str(curr_sel_obj.options['name'])))
  7197. def delete_hover_shape(self):
  7198. self.hover_shapes.clear()
  7199. self.hover_shapes.redraw()
  7200. def draw_hover_shape(self, sel_obj, color=None):
  7201. """
  7202. :param sel_obj: the object for which the hover shape must be drawn
  7203. :return:
  7204. """
  7205. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7206. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7207. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7208. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7209. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7210. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  7211. hover_rect = hover_rect.buffer(-0.1)
  7212. hover_rect = hover_rect.buffer(0.2)
  7213. else:
  7214. hover_rect = hover_rect.buffer(-0.00393)
  7215. hover_rect = hover_rect.buffer(0.00787)
  7216. # if color:
  7217. # face = Color(color)
  7218. # face.alpha = 0.2
  7219. # outline = Color(color, alpha=0.8)
  7220. # else:
  7221. # face = Color(self.defaults['global_sel_fill'])
  7222. # face.alpha = 0.2
  7223. # outline = self.defaults['global_sel_line']
  7224. if color:
  7225. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7226. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7227. else:
  7228. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7229. outline = self.defaults['global_sel_line']
  7230. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7231. if self.is_legacy is True:
  7232. self.hover_shapes.redraw()
  7233. def delete_selection_shape(self):
  7234. self.move_tool.sel_shapes.clear()
  7235. self.move_tool.sel_shapes.redraw()
  7236. def draw_selection_shape(self, sel_obj, color=None):
  7237. """
  7238. :param sel_obj: the object for which the selection shape must be drawn
  7239. :return:
  7240. """
  7241. if sel_obj is None:
  7242. return
  7243. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7244. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7245. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7246. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7247. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7248. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  7249. sel_rect = sel_rect.buffer(-0.1)
  7250. sel_rect = sel_rect.buffer(0.2)
  7251. else:
  7252. sel_rect = sel_rect.buffer(-0.00393)
  7253. sel_rect = sel_rect.buffer(0.00787)
  7254. if color:
  7255. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7256. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7257. else:
  7258. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7259. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7260. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7261. color=outline,
  7262. face_color=face,
  7263. update=True,
  7264. layer=0,
  7265. tolerance=None))
  7266. if self.is_legacy is True:
  7267. self.move_tool.sel_shapes.redraw()
  7268. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7269. """
  7270. :param old_coords: old coordinates
  7271. :param coords: new coordinates
  7272. :return:
  7273. """
  7274. if 'color' in kwargs:
  7275. color = kwargs['color']
  7276. else:
  7277. color = self.defaults['global_sel_line']
  7278. if 'face_color' in kwargs:
  7279. face_color = kwargs['face_color']
  7280. else:
  7281. face_color = self.defaults['global_sel_fill']
  7282. if 'face_alpha' in kwargs:
  7283. face_alpha = kwargs['face_alpha']
  7284. else:
  7285. face_alpha = 0.3
  7286. x0, y0 = old_coords
  7287. x1, y1 = coords
  7288. pt1 = (x0, y0)
  7289. pt2 = (x1, y0)
  7290. pt3 = (x1, y1)
  7291. pt4 = (x0, y1)
  7292. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7293. # color_t = Color(face_color)
  7294. # color_t.alpha = face_alpha
  7295. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7296. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7297. layer=0, tolerance=None)
  7298. if self.is_legacy is True:
  7299. self.move_tool.sel_shapes.redraw()
  7300. def on_file_new_click(self):
  7301. if self.collection.get_list() and self.should_we_save:
  7302. msgbox = QtWidgets.QMessageBox()
  7303. # msgbox.setText("<B>Save changes ...</B>")
  7304. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7305. "Creating a New project will delete them.\n"
  7306. "Do you want to Save the project?"))
  7307. msgbox.setWindowTitle(_("Save changes"))
  7308. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7309. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7310. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7311. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7312. msgbox.setDefaultButton(bt_yes)
  7313. msgbox.exec_()
  7314. response = msgbox.clickedButton()
  7315. if response == bt_yes:
  7316. self.on_file_saveprojectas()
  7317. elif response == bt_cancel:
  7318. return
  7319. elif response == bt_no:
  7320. self.on_file_new()
  7321. else:
  7322. self.on_file_new()
  7323. self.inform.emit('[success] %s...' %
  7324. _("New Project created"))
  7325. def on_file_new(self, cli=None):
  7326. """
  7327. Callback for menu item File -> New. Returns the application to its
  7328. startup state. This method is thread-safe.
  7329. :return: None
  7330. """
  7331. self.report_usage("on_file_new")
  7332. # Remove everything from memory
  7333. App.log.debug("on_file_new()")
  7334. if self.call_source != 'app':
  7335. self.editor2object(cleanup=True)
  7336. # ## EDITOR section
  7337. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7338. self.exc_editor = FlatCAMExcEditor(self)
  7339. self.grb_editor = FlatCAMGrbEditor(self)
  7340. # Clear pool
  7341. self.clear_pool()
  7342. for obj in self.collection.get_list():
  7343. # delete shapes left drawn from mark shape_collections, if any
  7344. if isinstance(obj, FlatCAMGerber):
  7345. try:
  7346. obj.mark_shapes.enabled = False
  7347. obj.mark_shapes.clear(update=True)
  7348. except AttributeError:
  7349. pass
  7350. # also delete annotation shapes, if any
  7351. elif isinstance(obj, FlatCAMCNCjob):
  7352. try:
  7353. obj.annotation.enabled = False
  7354. obj.annotation.clear(update=True)
  7355. except AttributeError:
  7356. pass
  7357. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7358. self.init_tcl()
  7359. self.delete_selection_shape()
  7360. self.collection.delete_all()
  7361. self.setup_component_editor()
  7362. # Clear project filename
  7363. self.project_filename = None
  7364. # Load the application defaults
  7365. self.load_defaults(filename='current_defaults')
  7366. # Re-fresh project options
  7367. self.on_options_app2project()
  7368. # Init Tools
  7369. self.init_tools()
  7370. if cli is None:
  7371. # Close any Tabs opened in the Plot Tab Area section
  7372. for index in range(self.ui.plot_tab_area.count()):
  7373. self.ui.plot_tab_area.closeTab(index)
  7374. # for whatever reason previous command does not close the last tab so I do it manually
  7375. self.ui.plot_tab_area.closeTab(0)
  7376. # # And then add again the Plot Area
  7377. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7378. self.ui.plot_tab_area.protectTab(0)
  7379. # take the focus of the Notebook on Project Tab.
  7380. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7381. self.set_ui_title(name=_("New Project - Not saved"))
  7382. def obj_properties(self):
  7383. """
  7384. Will launch the object Properties Tool
  7385. :return:
  7386. """
  7387. self.report_usage("obj_properties()")
  7388. self.properties_tool.run(toggle=False)
  7389. def on_project_context_save(self):
  7390. """
  7391. Wrapper, will save the object function of it's type
  7392. :return:
  7393. """
  7394. obj = self.collection.get_active()
  7395. if type(obj) == FlatCAMGeometry:
  7396. self.on_file_exportdxf()
  7397. elif type(obj) == FlatCAMExcellon:
  7398. self.on_file_saveexcellon()
  7399. elif type(obj) == FlatCAMCNCjob:
  7400. obj.on_exportgcode_button_click()
  7401. elif type(obj) == FlatCAMGerber:
  7402. self.on_file_savegerber()
  7403. elif type(obj) == FlatCAMScript:
  7404. self.on_file_savescript()
  7405. elif type(obj) == FlatCAMDocument:
  7406. self.on_file_savedocument()
  7407. def obj_move(self):
  7408. self.report_usage("obj_move()")
  7409. self.move_tool.run(toggle=False)
  7410. def on_fileopengerber(self, signal: bool = None, name=None):
  7411. """
  7412. File menu callback for opening a Gerber.
  7413. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7414. :return: None
  7415. """
  7416. self.report_usage("on_fileopengerber")
  7417. App.log.debug("on_fileopengerber()")
  7418. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7419. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7420. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7421. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7422. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7423. "*.mil);;" \
  7424. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7425. "Allegro Files (*.art);;" \
  7426. "Mentor Files (*.pho *.gdo);;" \
  7427. "All Files (*.*)"
  7428. if name is None:
  7429. try:
  7430. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7431. directory=self.get_last_folder(),
  7432. filter=_filter_)
  7433. except TypeError:
  7434. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7435. filenames = [str(filename) for filename in filenames]
  7436. else:
  7437. filenames = [name]
  7438. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7439. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7440. _("Opening Gerber file.")),
  7441. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7442. color=QtGui.QColor("gray"))
  7443. if len(filenames) == 0:
  7444. self.inform.emit('[WARNING_NOTCL] %s' %
  7445. _("Open Gerber cancelled."))
  7446. else:
  7447. for filename in filenames:
  7448. if filename != '':
  7449. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7450. def on_fileopenexcellon(self, signal: bool = None, name=None):
  7451. """
  7452. File menu callback for opening an Excellon file.
  7453. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7454. :return: None
  7455. """
  7456. self.report_usage("on_fileopenexcellon")
  7457. App.log.debug("on_fileopenexcellon()")
  7458. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7459. "All Files (*.*)"
  7460. if name is None:
  7461. try:
  7462. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7463. directory=self.get_last_folder(),
  7464. filter=_filter_)
  7465. except TypeError:
  7466. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7467. filenames = [str(filename) for filename in filenames]
  7468. else:
  7469. filenames = [str(name)]
  7470. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7471. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7472. _("Opening Excellon file.")),
  7473. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7474. color=QtGui.QColor("gray"))
  7475. if len(filenames) == 0:
  7476. self.inform.emit('[WARNING_NOTCL]%s' %
  7477. _(" Open Excellon cancelled."))
  7478. else:
  7479. for filename in filenames:
  7480. if filename != '':
  7481. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7482. def on_fileopengcode(self, signal: bool = None, name=None):
  7483. """
  7484. File menu call back for opening gcode.
  7485. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7486. :return: None
  7487. """
  7488. self.report_usage("on_fileopengcode")
  7489. App.log.debug("on_fileopengcode()")
  7490. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7491. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7492. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7493. "All Files (*.*)"
  7494. if name is None:
  7495. try:
  7496. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7497. directory=self.get_last_folder(),
  7498. filter=_filter_)
  7499. except TypeError:
  7500. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7501. filenames = [str(filename) for filename in filenames]
  7502. else:
  7503. filenames = [name]
  7504. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7505. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7506. _("Opening G-Code file.")),
  7507. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7508. color=QtGui.QColor("gray"))
  7509. if len(filenames) == 0:
  7510. self.inform.emit('[WARNING_NOTCL] %s' %
  7511. _("Open G-Code cancelled."))
  7512. else:
  7513. for filename in filenames:
  7514. if filename != '':
  7515. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7516. def on_file_openproject(self, signal: bool = None):
  7517. """
  7518. File menu callback for opening a project.
  7519. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7520. :return: None
  7521. """
  7522. self.report_usage("on_file_openproject")
  7523. App.log.debug("on_file_openproject()")
  7524. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7525. try:
  7526. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7527. directory=self.get_last_folder(), filter=_filter_)
  7528. except TypeError:
  7529. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7530. # The Qt methods above will return a QString which can cause problems later.
  7531. # So far json.dump() will fail to serialize it.
  7532. # TODO: Improve the serialization methods and remove this fix.
  7533. filename = str(filename)
  7534. if filename == "":
  7535. self.inform.emit('[WARNING_NOTCL] %s' %
  7536. _("Open Project cancelled."))
  7537. else:
  7538. # self.worker_task.emit({'fcn': self.open_project,
  7539. # 'params': [filename]})
  7540. # The above was failing because open_project() is not
  7541. # thread safe. The new_project()
  7542. self.open_project(filename)
  7543. def on_file_openconfig(self, signal: bool = None):
  7544. """
  7545. File menu callback for opening a config file.
  7546. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7547. :return: None
  7548. """
  7549. self.report_usage("on_file_openconfig")
  7550. App.log.debug("on_file_openconfig()")
  7551. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7552. try:
  7553. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7554. directory=self.data_path, filter=_filter_)
  7555. except TypeError:
  7556. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7557. filter=_filter_)
  7558. if filename == "":
  7559. self.inform.emit('[WARNING_NOTCL] %s' %
  7560. _("Open Config cancelled."))
  7561. else:
  7562. self.open_config_file(filename)
  7563. def on_file_exportsvg(self):
  7564. """
  7565. Callback for menu item File->Export SVG.
  7566. :return: None
  7567. """
  7568. self.report_usage("on_file_exportsvg")
  7569. App.log.debug("on_file_exportsvg()")
  7570. obj = self.collection.get_active()
  7571. if obj is None:
  7572. self.inform.emit('[WARNING_NOTCL] %s' %
  7573. _("No object selected."))
  7574. msg = _("Please Select a Geometry object to export")
  7575. msgbox = QtWidgets.QMessageBox()
  7576. msgbox.setInformativeText(msg)
  7577. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7578. msgbox.setDefaultButton(bt_ok)
  7579. msgbox.exec_()
  7580. return
  7581. # Check for more compatible types and add as required
  7582. if (not isinstance(obj, FlatCAMGeometry)
  7583. and not isinstance(obj, FlatCAMGerber)
  7584. and not isinstance(obj, FlatCAMCNCjob)
  7585. and not isinstance(obj, FlatCAMExcellon)):
  7586. msg = '[ERROR_NOTCL] %s' % \
  7587. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7588. msgbox = QtWidgets.QMessageBox()
  7589. msgbox.setInformativeText(msg)
  7590. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7591. msgbox.setDefaultButton(bt_ok)
  7592. msgbox.exec_()
  7593. return
  7594. name = obj.options["name"]
  7595. _filter = "SVG File (*.svg);;All Files (*.*)"
  7596. try:
  7597. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7598. caption=_("Export SVG"),
  7599. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  7600. filter=_filter)
  7601. except TypeError:
  7602. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7603. filename = str(filename)
  7604. if filename == "":
  7605. self.inform.emit('[WARNING_NOTCL]%s' %
  7606. _(" Export SVG cancelled."))
  7607. return
  7608. else:
  7609. self.export_svg(name, filename)
  7610. if self.defaults["global_open_style"] is False:
  7611. self.file_opened.emit("SVG", filename)
  7612. self.file_saved.emit("SVG", filename)
  7613. def on_file_exportpng(self):
  7614. self.report_usage("on_file_exportpng")
  7615. App.log.debug("on_file_exportpng()")
  7616. self.date = str(datetime.today()).rpartition('.')[0]
  7617. self.date = ''.join(c for c in self.date if c not in ':-')
  7618. self.date = self.date.replace(' ', '_')
  7619. if self.is_legacy is False:
  7620. image = _screenshot()
  7621. data = np.asarray(image)
  7622. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7623. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7624. _('Data must be a 3D array with last dimension 3 or 4'))
  7625. return
  7626. filter_ = "PNG File (*.png);;All Files (*.*)"
  7627. try:
  7628. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7629. caption=_("Export PNG Image"),
  7630. directory=self.get_last_save_folder() + '/png_' + self.date,
  7631. filter=filter_)
  7632. except TypeError:
  7633. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7634. filename = str(filename)
  7635. if filename == "":
  7636. self.inform.emit(_("Export PNG cancelled."))
  7637. return
  7638. else:
  7639. if self.is_legacy is False:
  7640. write_png(filename, data)
  7641. else:
  7642. self.plotcanvas.figure.savefig(filename)
  7643. if self.defaults["global_open_style"] is False:
  7644. self.file_opened.emit("png", filename)
  7645. self.file_saved.emit("png", filename)
  7646. def on_file_savegerber(self):
  7647. """
  7648. Callback for menu item in Project context menu.
  7649. :return: None
  7650. """
  7651. self.report_usage("on_file_savegerber")
  7652. App.log.debug("on_file_savegerber()")
  7653. obj = self.collection.get_active()
  7654. if obj is None:
  7655. self.inform.emit('[WARNING_NOTCL] %s' %
  7656. _("No object selected. Please select an Gerber object to export."))
  7657. return
  7658. # Check for more compatible types and add as required
  7659. if not isinstance(obj, FlatCAMGerber):
  7660. self.inform.emit('[ERROR_NOTCL] %s' %
  7661. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7662. return
  7663. name = self.collection.get_active().options["name"]
  7664. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7665. try:
  7666. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7667. caption="Save Gerber source file",
  7668. directory=self.get_last_save_folder() + '/' + name,
  7669. filter=_filter)
  7670. except TypeError:
  7671. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7672. filename = str(filename)
  7673. if filename == "":
  7674. self.inform.emit('[WARNING_NOTCL] %s' %
  7675. _("Save Gerber source file cancelled."))
  7676. return
  7677. else:
  7678. self.save_source_file(name, filename)
  7679. if self.defaults["global_open_style"] is False:
  7680. self.file_opened.emit("Gerber", filename)
  7681. self.file_saved.emit("Gerber", filename)
  7682. def on_file_savescript(self):
  7683. """
  7684. Callback for menu item in Project context menu.
  7685. :return: None
  7686. """
  7687. self.report_usage("on_file_savescript")
  7688. App.log.debug("on_file_savescript()")
  7689. obj = self.collection.get_active()
  7690. if obj is None:
  7691. self.inform.emit('[WARNING_NOTCL] %s' %
  7692. _("No object selected. Please select an Script object to export."))
  7693. return
  7694. # Check for more compatible types and add as required
  7695. if not isinstance(obj, FlatCAMScript):
  7696. self.inform.emit('[ERROR_NOTCL] %s' %
  7697. _("Failed. Only Script objects can be saved as TCL Script files..."))
  7698. return
  7699. name = self.collection.get_active().options["name"]
  7700. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7701. try:
  7702. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7703. caption="Save Script source file",
  7704. directory=self.get_last_save_folder() + '/' + name,
  7705. filter=_filter)
  7706. except TypeError:
  7707. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  7708. filename = str(filename)
  7709. if filename == "":
  7710. self.inform.emit('[WARNING_NOTCL] %s' %
  7711. _("Save Script source file cancelled."))
  7712. return
  7713. else:
  7714. self.save_source_file(name, filename)
  7715. if self.defaults["global_open_style"] is False:
  7716. self.file_opened.emit("Script", filename)
  7717. self.file_saved.emit("Script", filename)
  7718. def on_file_savedocument(self):
  7719. """
  7720. Callback for menu item in Project context menu.
  7721. :return: None
  7722. """
  7723. self.report_usage("on_file_savedocument")
  7724. App.log.debug("on_file_savedocument()")
  7725. obj = self.collection.get_active()
  7726. if obj is None:
  7727. self.inform.emit('[WARNING_NOTCL] %s' %
  7728. _("No object selected. Please select an Document object to export."))
  7729. return
  7730. # Check for more compatible types and add as required
  7731. if not isinstance(obj, FlatCAMScript):
  7732. self.inform.emit('[ERROR_NOTCL] %s' %
  7733. _("Failed. Only Document objects can be saved as Document files..."))
  7734. return
  7735. name = self.collection.get_active().options["name"]
  7736. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7737. try:
  7738. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7739. caption="Save Document source file",
  7740. directory=self.get_last_save_folder() + '/' + name,
  7741. filter=_filter)
  7742. except TypeError:
  7743. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  7744. filename = str(filename)
  7745. if filename == "":
  7746. self.inform.emit('[WARNING_NOTCL] %s' %
  7747. _("Save Document source file cancelled."))
  7748. return
  7749. else:
  7750. self.save_source_file(name, filename)
  7751. if self.defaults["global_open_style"] is False:
  7752. self.file_opened.emit("Document", filename)
  7753. self.file_saved.emit("Document", filename)
  7754. def on_file_saveexcellon(self):
  7755. """
  7756. Callback for menu item in project context menu.
  7757. :return: None
  7758. """
  7759. self.report_usage("on_file_saveexcellon")
  7760. App.log.debug("on_file_saveexcellon()")
  7761. obj = self.collection.get_active()
  7762. if obj is None:
  7763. self.inform.emit('[WARNING_NOTCL] %s' %
  7764. _("No object selected. Please select an Excellon object to export."))
  7765. return
  7766. # Check for more compatible types and add as required
  7767. if not isinstance(obj, FlatCAMExcellon):
  7768. self.inform.emit('[ERROR_NOTCL] %s' %
  7769. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7770. return
  7771. name = self.collection.get_active().options["name"]
  7772. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7773. try:
  7774. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7775. caption=_("Save Excellon source file"),
  7776. directory=self.get_last_save_folder() + '/' + name,
  7777. filter=_filter)
  7778. except TypeError:
  7779. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7780. filename = str(filename)
  7781. if filename == "":
  7782. self.inform.emit('[WARNING_NOTCL] %s' %
  7783. _("Saving Excellon source file cancelled."))
  7784. return
  7785. else:
  7786. self.save_source_file(name, filename)
  7787. if self.defaults["global_open_style"] is False:
  7788. self.file_opened.emit("Excellon", filename)
  7789. self.file_saved.emit("Excellon", filename)
  7790. def on_file_exportexcellon(self):
  7791. """
  7792. Callback for menu item File->Export->Excellon.
  7793. :return: None
  7794. """
  7795. self.report_usage("on_file_exportexcellon")
  7796. App.log.debug("on_file_exportexcellon()")
  7797. obj = self.collection.get_active()
  7798. if obj is None:
  7799. self.inform.emit('[WARNING_NOTCL] %s' %
  7800. _("No object selected. Please Select an Excellon object to export."))
  7801. return
  7802. # Check for more compatible types and add as required
  7803. if not isinstance(obj, FlatCAMExcellon):
  7804. self.inform.emit('[ERROR_NOTCL] %s' %
  7805. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7806. return
  7807. name = self.collection.get_active().options["name"]
  7808. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7809. try:
  7810. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7811. caption=_("Export Excellon"),
  7812. directory=self.get_last_save_folder() + '/' + name,
  7813. filter=_filter)
  7814. except TypeError:
  7815. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7816. filename = str(filename)
  7817. if filename == "":
  7818. self.inform.emit('[WARNING_NOTCL] %s' %
  7819. _("Export Excellon cancelled."))
  7820. return
  7821. else:
  7822. self.export_excellon(name, filename)
  7823. if self.defaults["global_open_style"] is False:
  7824. self.file_opened.emit("Excellon", filename)
  7825. self.file_saved.emit("Excellon", filename)
  7826. def on_file_exportgerber(self):
  7827. """
  7828. Callback for menu item File->Export->Gerber.
  7829. :return: None
  7830. """
  7831. self.report_usage("on_file_exportgerber")
  7832. App.log.debug("on_file_exportgerber()")
  7833. obj = self.collection.get_active()
  7834. if obj is None:
  7835. self.inform.emit('[WARNING_NOTCL] %s' %
  7836. _("No object selected. Please Select an Gerber object to export."))
  7837. return
  7838. # Check for more compatible types and add as required
  7839. if not isinstance(obj, FlatCAMGerber):
  7840. self.inform.emit('[ERROR_NOTCL] %s' %
  7841. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7842. return
  7843. name = self.collection.get_active().options["name"]
  7844. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7845. try:
  7846. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7847. caption=_("Export Gerber"),
  7848. directory=self.get_last_save_folder() + '/' + name,
  7849. filter=_filter_)
  7850. except TypeError:
  7851. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7852. filename = str(filename)
  7853. if filename == "":
  7854. self.inform.emit('[WARNING_NOTCL] %s' %
  7855. _("Export Gerber cancelled."))
  7856. return
  7857. else:
  7858. self.export_gerber(name, filename)
  7859. if self.defaults["global_open_style"] is False:
  7860. self.file_opened.emit("Gerber", filename)
  7861. self.file_saved.emit("Gerber", filename)
  7862. def on_file_exportdxf(self):
  7863. """
  7864. Callback for menu item File->Export DXF.
  7865. :return: None
  7866. """
  7867. self.report_usage("on_file_exportdxf")
  7868. App.log.debug("on_file_exportdxf()")
  7869. obj = self.collection.get_active()
  7870. if obj is None:
  7871. self.inform.emit('[WARNING_NOTCL] %s' %
  7872. _("No object selected."))
  7873. msg = _("Please Select a Geometry object to export")
  7874. msgbox = QtWidgets.QMessageBox()
  7875. msgbox.setInformativeText(msg)
  7876. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7877. msgbox.setDefaultButton(bt_ok)
  7878. msgbox.exec_()
  7879. return
  7880. # Check for more compatible types and add as required
  7881. if not isinstance(obj, FlatCAMGeometry):
  7882. msg = '[ERROR_NOTCL] %s' % \
  7883. _("Only Geometry objects can be used.")
  7884. msgbox = QtWidgets.QMessageBox()
  7885. msgbox.setInformativeText(msg)
  7886. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7887. msgbox.setDefaultButton(bt_ok)
  7888. msgbox.exec_()
  7889. return
  7890. name = self.collection.get_active().options["name"]
  7891. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7892. try:
  7893. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7894. caption=_("Export DXF"),
  7895. directory=self.get_last_save_folder() + '/' + name,
  7896. filter=_filter_)
  7897. except TypeError:
  7898. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7899. filter=_filter_)
  7900. filename = str(filename)
  7901. if filename == "":
  7902. self.inform.emit('[WARNING_NOTCL] %s' %
  7903. _("Export DXF cancelled."))
  7904. return
  7905. else:
  7906. self.export_dxf(name, filename)
  7907. if self.defaults["global_open_style"] is False:
  7908. self.file_opened.emit("DXF", filename)
  7909. self.file_saved.emit("DXF", filename)
  7910. def on_file_importsvg(self, type_of_obj):
  7911. """
  7912. Callback for menu item File->Import SVG.
  7913. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7914. :type type_of_obj: str
  7915. :return: None
  7916. """
  7917. self.report_usage("on_file_importsvg")
  7918. App.log.debug("on_file_importsvg()")
  7919. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7920. try:
  7921. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7922. directory=self.get_last_folder(), filter=_filter_)
  7923. except TypeError:
  7924. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7925. filter=_filter_)
  7926. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7927. type_of_obj = "geometry"
  7928. filenames = [str(filename) for filename in filenames]
  7929. if len(filenames) == 0:
  7930. self.inform.emit('[WARNING_NOTCL] %s' %
  7931. _("Open SVG cancelled."))
  7932. else:
  7933. for filename in filenames:
  7934. if filename != '':
  7935. self.worker_task.emit({'fcn': self.import_svg,
  7936. 'params': [filename, type_of_obj]})
  7937. def on_file_importdxf(self, type_of_obj):
  7938. """
  7939. Callback for menu item File->Import DXF.
  7940. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7941. :type type_of_obj: str
  7942. :return: None
  7943. """
  7944. self.report_usage("on_file_importdxf")
  7945. App.log.debug("on_file_importdxf()")
  7946. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7947. try:
  7948. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7949. directory=self.get_last_folder(),
  7950. filter=_filter_)
  7951. except TypeError:
  7952. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7953. filter=_filter_)
  7954. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7955. type_of_obj = "geometry"
  7956. filenames = [str(filename) for filename in filenames]
  7957. if len(filenames) == 0:
  7958. self.inform.emit('[WARNING_NOTCL] %s' %
  7959. _("Open DXF cancelled."))
  7960. else:
  7961. for filename in filenames:
  7962. if filename != '':
  7963. self.worker_task.emit({'fcn': self.import_dxf,
  7964. 'params': [filename, type_of_obj]})
  7965. # ###############################################################################################################
  7966. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7967. # ###############################################################################################################
  7968. def init_code_editor(self, name):
  7969. self.text_editor_tab = TextEditor(app=self)
  7970. # add the tab if it was closed
  7971. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  7972. self.text_editor_tab.setObjectName('text_editor_tab')
  7973. # delete the absolute and relative position and messages in the infobar
  7974. self.ui.position_label.setText("")
  7975. self.ui.rel_position_label.setText("")
  7976. # first clear previous text in text editor (if any)
  7977. self.text_editor_tab.code_editor.clear()
  7978. self.text_editor_tab.code_editor.setReadOnly(False)
  7979. self.toggle_codeeditor = True
  7980. self.text_editor_tab.code_editor.completer_enable = False
  7981. self.text_editor_tab.buttonRun.hide()
  7982. # make sure to keep a reference to the code editor
  7983. self.reference_code_editor = self.text_editor_tab.code_editor
  7984. # Switch plot_area to CNCJob tab
  7985. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  7986. def on_view_source(self):
  7987. """
  7988. Called when the user wants to see the source file of the selected object
  7989. :return:
  7990. """
  7991. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  7992. self.proc_container.view.set_busy(_("Loading..."))
  7993. try:
  7994. obj = self.collection.get_active()
  7995. except Exception as e:
  7996. log.debug("App.on_view_source() --> %s" % str(e))
  7997. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  7998. return 'fail'
  7999. if obj is None:
  8000. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8001. return 'fail'
  8002. flt = "All Files (*.*)"
  8003. if obj.kind == 'gerber':
  8004. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  8005. elif obj.kind == 'excellon':
  8006. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  8007. elif obj.kind == 'cncjob':
  8008. "GCode Files (*.NC);;All Files (*.*)"
  8009. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  8010. # add the tab if it was closed
  8011. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8012. self.source_editor_tab.setObjectName('source_editor_tab')
  8013. # delete the absolute and relative position and messages in the infobar
  8014. self.ui.position_label.setText("")
  8015. self.ui.rel_position_label.setText("")
  8016. # first clear previous text in text editor (if any)
  8017. self.source_editor_tab.code_editor.clear()
  8018. self.source_editor_tab.code_editor.setReadOnly(False)
  8019. self.source_editor_tab.code_editor.completer_enable = False
  8020. self.source_editor_tab.buttonRun.hide()
  8021. # Switch plot_area to CNCJob tab
  8022. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8023. try:
  8024. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8025. except TypeError:
  8026. pass
  8027. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8028. try:
  8029. self.source_editor_tab.buttonSave.clicked.disconnect()
  8030. except TypeError:
  8031. pass
  8032. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8033. # then append the text from GCode to the text editor
  8034. if obj.kind == 'cncjob':
  8035. try:
  8036. file = obj.export_gcode(
  8037. preamble=self.defaults["cncjob_prepend"],
  8038. postamble=self.defaults["cncjob_append"],
  8039. to_file=True)
  8040. if file == 'fail':
  8041. return 'fail'
  8042. except AttributeError:
  8043. self.inform.emit('[WARNING_NOTCL] %s' %
  8044. _("There is no selected object for which to see it's source file code."))
  8045. return 'fail'
  8046. else:
  8047. try:
  8048. file = StringIO(obj.source_file)
  8049. except AttributeError:
  8050. self.inform.emit('[WARNING_NOTCL] %s' %
  8051. _("There is no selected object for which to see it's source file code."))
  8052. return 'fail'
  8053. self.source_editor_tab.t_frame.hide()
  8054. try:
  8055. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  8056. # for line in file:
  8057. # QtWidgets.QApplication.processEvents()
  8058. # proc_line = str(line).strip('\n')
  8059. # self.source_editor_tab.code_editor.append(proc_line)
  8060. except Exception as e:
  8061. log.debug('App.on_view_source() -->%s' % str(e))
  8062. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  8063. return
  8064. self.source_editor_tab.handleTextChanged()
  8065. self.source_editor_tab.t_frame.show()
  8066. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8067. self.proc_container.view.set_idle()
  8068. # self.ui.show()
  8069. def on_toggle_code_editor(self):
  8070. self.report_usage("on_toggle_code_editor()")
  8071. if self.toggle_codeeditor is False:
  8072. self.init_code_editor(name=_("Code Editor"))
  8073. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8074. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8075. self.text_editor_tab.buttonSave.clicked.disconnect()
  8076. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8077. else:
  8078. for idx in range(self.ui.plot_tab_area.count()):
  8079. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8080. self.ui.plot_tab_area.closeTab(idx)
  8081. break
  8082. self.toggle_codeeditor = False
  8083. def on_code_editor_close(self):
  8084. print("closed")
  8085. self.toggle_codeeditor = False
  8086. def on_filenewscript(self, silent=False, name=None, text=None):
  8087. """
  8088. Will create a new script file and open it in the Code Editor
  8089. :param silent: if True will not display status messages
  8090. :param name: if specified will be the name of the new script
  8091. :param text: pass a source file to the newly created script to be loaded in it
  8092. :return: None
  8093. """
  8094. if silent is False:
  8095. self.inform.emit('[success] %s' %
  8096. _("New TCL script file created in Code Editor."))
  8097. # delete the absolute and relative position and messages in the infobar
  8098. self.ui.position_label.setText("")
  8099. self.ui.rel_position_label.setText("")
  8100. if name is not None:
  8101. self.new_script_object(name=name, text=text)
  8102. else:
  8103. self.new_script_object(text=text)
  8104. # script_text = script_obj.source_file
  8105. #
  8106. # self.proc_container.view.set_busy(_("Loading..."))
  8107. # script_obj.script_editor_tab.t_frame.hide()
  8108. #
  8109. # script_obj.script_editor_tab.t_frame.show()
  8110. # self.proc_container.view.set_idle()
  8111. def on_fileopenscript(self, name=None, silent=False):
  8112. """
  8113. Will open a Tcl script file into the Code Editor
  8114. :param silent: if True will not display status messages
  8115. :param name: name of a Tcl script file to open
  8116. :return:
  8117. """
  8118. self.report_usage("on_fileopenscript")
  8119. App.log.debug("on_fileopenscript()")
  8120. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8121. if name:
  8122. filenames = [name]
  8123. else:
  8124. try:
  8125. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8126. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8127. except TypeError:
  8128. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8129. if len(filenames) == 0:
  8130. if silent is False:
  8131. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  8132. else:
  8133. for filename in filenames:
  8134. if filename != '':
  8135. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8136. def on_filerunscript(self, name=None, silent=False):
  8137. """
  8138. File menu callback for loading and running a TCL script.
  8139. :param silent: if True will not display status messages
  8140. :param name: name of a Tcl script file to be run by FlatCAM
  8141. :return: None
  8142. """
  8143. self.report_usage("on_filerunscript")
  8144. App.log.debug("on_file_runscript()")
  8145. if name:
  8146. filename = name
  8147. if self.cmd_line_headless != 1:
  8148. self.splash.showMessage('%s: %ssec\n%s' %
  8149. (_("Canvas initialization started.\n"
  8150. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8151. _("Executing FlatCAMScript file.")
  8152. ),
  8153. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8154. color=QtGui.QColor("gray"))
  8155. else:
  8156. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8157. try:
  8158. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8159. directory=self.get_last_folder(), filter=_filter_)
  8160. except TypeError:
  8161. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8162. # The Qt methods above will return a QString which can cause problems later.
  8163. # So far json.dump() will fail to serialize it.
  8164. # TODO: Improve the serialization methods and remove this fix.
  8165. filename = str(filename)
  8166. if filename == "":
  8167. if silent is False:
  8168. self.inform.emit('[WARNING_NOTCL] %s' %
  8169. _("Run TCL script cancelled."))
  8170. else:
  8171. if self.cmd_line_headless != 1:
  8172. if self.ui.shell_dock.isHidden():
  8173. self.ui.shell_dock.show()
  8174. try:
  8175. with open(filename, "r") as tcl_script:
  8176. cmd_line_shellfile_content = tcl_script.read()
  8177. if self.cmd_line_headless != 1:
  8178. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  8179. else:
  8180. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8181. if silent is False:
  8182. self.inform.emit('[success] %s' %
  8183. _("TCL script file opened in Code Editor and executed."))
  8184. except Exception as e:
  8185. log.debug("App.on_filerunscript() -> %s" % str(e))
  8186. sys.exit(2)
  8187. def on_file_saveproject(self, silent=False):
  8188. """
  8189. Callback for menu item File->Save Project. Saves the project to
  8190. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8191. if set to None. The project is saved by calling ``self.save_project()``.
  8192. :param silent: if True will not display status messages
  8193. :return: None
  8194. """
  8195. self.report_usage("on_file_saveproject")
  8196. if self.project_filename is None:
  8197. self.on_file_saveprojectas()
  8198. else:
  8199. self.worker_task.emit({'fcn': self.save_project,
  8200. 'params': [self.project_filename, silent]})
  8201. if self.defaults["global_open_style"] is False:
  8202. self.file_opened.emit("project", self.project_filename)
  8203. self.file_saved.emit("project", self.project_filename)
  8204. self.set_ui_title(name=self.project_filename)
  8205. self.should_we_save = False
  8206. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8207. """
  8208. Callback for menu item File->Save Project As... Opens a file
  8209. chooser and saves the project to the given file via
  8210. ``self.save_project()``.
  8211. :param make_copy if to be create a copy of the project; boolean
  8212. :param use_thread: if to be run in a separate thread; boolean
  8213. :param quit_action: if to be followed by quiting the application; boolean
  8214. :return: None
  8215. """
  8216. self.report_usage("on_file_saveprojectas")
  8217. self.date = str(datetime.today()).rpartition('.')[0]
  8218. self.date = ''.join(c for c in self.date if c not in ':-')
  8219. self.date = self.date.replace(' ', '_')
  8220. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  8221. try:
  8222. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8223. caption=_("Save Project As ..."),
  8224. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  8225. filter=filter_)
  8226. except TypeError:
  8227. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  8228. filename = str(filename)
  8229. if filename == '':
  8230. self.inform.emit('[WARNING_NOTCL] %s' %
  8231. _("Save Project cancelled."))
  8232. return
  8233. try:
  8234. f = open(filename, 'r')
  8235. f.close()
  8236. except IOError:
  8237. pass
  8238. if use_thread is True:
  8239. self.worker_task.emit({'fcn': self.save_project,
  8240. 'params': [filename, quit_action]})
  8241. else:
  8242. self.save_project(filename, quit_action)
  8243. # self.save_project(filename)
  8244. if self.defaults["global_open_style"] is False:
  8245. self.file_opened.emit("project", filename)
  8246. self.file_saved.emit("project", filename)
  8247. if not make_copy:
  8248. self.project_filename = filename
  8249. self.set_ui_title(name=self.project_filename)
  8250. self.should_we_save = False
  8251. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8252. """
  8253. Exports a Geometry Object to an SVG file.
  8254. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8255. :param filename: Path to the SVG file to save to.
  8256. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8257. :return:
  8258. """
  8259. self.report_usage("export_svg()")
  8260. if filename is None:
  8261. filename = self.defaults["global_last_save_folder"]
  8262. self.log.debug("export_svg()")
  8263. try:
  8264. obj = self.collection.get_by_name(str(obj_name))
  8265. except Exception:
  8266. # TODO: The return behavior has not been established... should raise exception?
  8267. return "Could not retrieve object: %s" % obj_name
  8268. with self.proc_container.new(_("Exporting SVG")) as proc:
  8269. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8270. # Determine bounding area for svg export
  8271. bounds = obj.bounds()
  8272. size = obj.size()
  8273. # Convert everything to strings for use in the xml doc
  8274. svgwidth = str(size[0])
  8275. svgheight = str(size[1])
  8276. minx = str(bounds[0])
  8277. miny = str(bounds[1] - size[1])
  8278. uom = obj.units.lower()
  8279. # Add a SVG Header and footer to the svg output from shapely
  8280. # The transform flips the Y Axis so that everything renders
  8281. # properly within svg apps such as inkscape
  8282. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8283. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8284. svg_header += 'width="' + svgwidth + uom + '" '
  8285. svg_header += 'height="' + svgheight + uom + '" '
  8286. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8287. svg_header += '<g transform="scale(1,-1)">'
  8288. svg_footer = '</g> </svg>'
  8289. svg_elem = svg_header + exported_svg + svg_footer
  8290. # Parse the xml through a xml parser just to add line feeds
  8291. # and to make it look more pretty for the output
  8292. svgcode = parse_xml_string(svg_elem)
  8293. svgcode = svgcode.toprettyxml()
  8294. try:
  8295. with open(filename, 'w') as fp:
  8296. fp.write(svgcode)
  8297. except PermissionError:
  8298. self.inform.emit('[WARNING] %s' %
  8299. _("Permission denied, saving not possible.\n"
  8300. "Most likely another app is holding the file open and not accessible."))
  8301. return 'fail'
  8302. if self.defaults["global_open_style"] is False:
  8303. self.file_opened.emit("SVG", filename)
  8304. self.file_saved.emit("SVG", filename)
  8305. self.inform.emit('[success] %s: %s' %
  8306. (_("SVG file exported to"), filename))
  8307. def export_svg_negative(self, obj_name, box_name, filename, boundary,
  8308. scale_stroke_factor=0.00,
  8309. scale_factor_x=None, scale_factor_y=None,
  8310. skew_factor_x=None, skew_factor_y=None, skew_reference='center',
  8311. mirror=None,
  8312. use_thread=True):
  8313. """
  8314. Exports a Geometry Object to an SVG file in negative.
  8315. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8316. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8317. :param filename: Path to the SVG file to save to.
  8318. :param boundary: thickness of a black border to surround all the features
  8319. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8320. :param scale_factor_x: factor to scale the svg geometry on the X axis
  8321. :param scale_factor_y: factor to scale the svg geometry on the Y axis
  8322. :param skew_factor_x: factor to skew the svg geometry on the X axis
  8323. :param skew_factor_y: factor to skew the svg geometry on the Y axis
  8324. :param skew_reference: reference to use for skew. Can be 'bottomleft', 'bottomright', 'topleft', 'topright' and
  8325. those are the 4 points of the bounding box of the geometry to be skewed.
  8326. :param mirror: can be 'x' or 'y' or 'both'. Axis on which to mirror the svg geometry
  8327. :param use_thread: if to be run in a separate thread; boolean
  8328. :return:
  8329. """
  8330. self.report_usage("export_negative()")
  8331. if filename is None:
  8332. filename = self.defaults["global_last_save_folder"]
  8333. self.log.debug("export_svg() negative")
  8334. try:
  8335. obj = self.collection.get_by_name(str(obj_name))
  8336. except Exception:
  8337. # TODO: The return behavior has not been established... should raise exception?
  8338. return "Could not retrieve object: %s" % obj_name
  8339. try:
  8340. box = self.collection.get_by_name(str(box_name))
  8341. except Exception:
  8342. # TODO: The return behavior has not been established... should raise exception?
  8343. return "Could not retrieve object: %s" % box_name
  8344. if box is None:
  8345. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8346. (_("No object Box. Using instead"), obj))
  8347. box = obj
  8348. def make_negative_film():
  8349. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor,
  8350. scale_factor_x=scale_factor_x, scale_factor_y=scale_factor_y,
  8351. skew_factor_x=skew_factor_x, skew_factor_y=skew_factor_y,
  8352. mirror=mirror
  8353. )
  8354. # Determine bounding area for svg export
  8355. bounds = box.bounds()
  8356. size = box.size()
  8357. uom = obj.units.lower()
  8358. # Convert everything to strings for use in the xml doc
  8359. svgwidth = str(size[0] + (2 * boundary))
  8360. svgheight = str(size[1] + (2 * boundary))
  8361. minx = str(bounds[0] - boundary)
  8362. miny = str(bounds[1] + boundary + size[1])
  8363. miny_rect = str(bounds[1] - boundary)
  8364. # Add a SVG Header and footer to the svg output from shapely
  8365. # The transform flips the Y Axis so that everything renders
  8366. # properly within svg apps such as inkscape
  8367. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8368. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8369. svg_header += 'width="' + svgwidth + uom + '" '
  8370. svg_header += 'height="' + svgheight + uom + '" '
  8371. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8372. svg_header += '>'
  8373. svg_header += '<g transform="scale(1,-1)">'
  8374. svg_footer = '</g> </svg>'
  8375. # Change the attributes of the exported SVG
  8376. # We don't need stroke-width - wrong, we do when we have lines with certain width
  8377. # We set opacity to maximum
  8378. # We set the color to WHITE
  8379. root = ET.fromstring(exported_svg)
  8380. for child in root:
  8381. child.set('fill', '#FFFFFF')
  8382. child.set('opacity', '1.0')
  8383. child.set('stroke', '#FFFFFF')
  8384. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  8385. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  8386. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  8387. first_svg_elem_tag = 'rect'
  8388. first_svg_elem_attribs = {
  8389. 'x': minx,
  8390. 'y': miny_rect,
  8391. 'width': svgwidth,
  8392. 'height': svgheight,
  8393. 'id': 'neg_rect',
  8394. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  8395. }
  8396. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  8397. exported_svg = ET.tostring(root)
  8398. svg_elem = svg_header + str(exported_svg) + svg_footer
  8399. # Parse the xml through a xml parser just to add line feeds
  8400. # and to make it look more pretty for the output
  8401. doc = parse_xml_string(svg_elem)
  8402. try:
  8403. with open(filename, 'w') as fp:
  8404. fp.write(doc.toprettyxml())
  8405. except PermissionError:
  8406. self.inform.emit('[WARNING] %s' %
  8407. _("Permission denied, saving not possible.\n"
  8408. "Most likely another app is holding the file open and not accessible."))
  8409. return 'fail'
  8410. if self.defaults["global_open_style"] is False:
  8411. self.file_opened.emit("SVG", filename)
  8412. self.file_saved.emit("SVG", filename)
  8413. self.inform.emit('[success] %s: %s' %
  8414. (_("SVG file exported to"), filename))
  8415. if use_thread is True:
  8416. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8417. def job_thread_film(app_obj):
  8418. try:
  8419. make_negative_film()
  8420. except Exception:
  8421. proc.done()
  8422. return
  8423. proc.done()
  8424. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8425. else:
  8426. make_negative_film()
  8427. def export_svg_positive(self, obj_name, box_name, filename,
  8428. scale_stroke_factor=0.00,
  8429. scale_factor_x=None, scale_factor_y=None,
  8430. skew_factor_x=None, skew_factor_y=None, skew_reference='center',
  8431. mirror=None,
  8432. use_thread=True):
  8433. """
  8434. Exports a Geometry Object to an SVG file in positive black.
  8435. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8436. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8437. :param filename: Path to the SVG file to save to.
  8438. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8439. :param scale_factor_x: factor to scale the svg geometry on the X axis
  8440. :param scale_factor_y: factor to scale the svg geometry on the Y axis
  8441. :param skew_factor_x: factor to skew the svg geometry on the X axis
  8442. :param skew_factor_y: factor to skew the svg geometry on the Y axis
  8443. :param skew_reference: reference to use for skew. Can be 'bottomleft', 'bottomright', 'topleft', 'topright' and
  8444. those are the 4 points of the bounding box of the geometry to be skewed.
  8445. :param mirror: can be 'x' or 'y' or 'both'. Axis on which to mirror the svg geometry
  8446. :param use_thread: if to be run in a separate thread; boolean
  8447. :return:
  8448. """
  8449. self.report_usage("export_svg_positive()")
  8450. if filename is None:
  8451. filename = self.defaults["global_last_save_folder"]
  8452. self.log.debug("export_svg() black")
  8453. try:
  8454. obj = self.collection.get_by_name(str(obj_name))
  8455. except Exception:
  8456. # TODO: The return behavior has not been established... should raise exception?
  8457. return "Could not retrieve object: %s" % obj_name
  8458. try:
  8459. box = self.collection.get_by_name(str(box_name))
  8460. except Exception:
  8461. # TODO: The return behavior has not been established... should raise exception?
  8462. return "Could not retrieve object: %s" % box_name
  8463. if box is None:
  8464. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8465. (_("No object Box. Using instead"), obj))
  8466. box = obj
  8467. def make_positive_film():
  8468. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor,
  8469. scale_factor_x=scale_factor_x, scale_factor_y=scale_factor_y,
  8470. skew_factor_x=skew_factor_x, skew_factor_y=skew_factor_y,
  8471. mirror=mirror
  8472. )
  8473. self.progress.emit(40)
  8474. # Change the attributes of the exported SVG
  8475. # We don't need stroke-width
  8476. # We set opacity to maximum
  8477. # We set the colour to WHITE
  8478. root = ET.fromstring(exported_svg)
  8479. for child in root:
  8480. child.set('fill', str(self.defaults['tools_film_color']))
  8481. child.set('opacity', '1.0')
  8482. child.set('stroke', str(self.defaults['tools_film_color']))
  8483. exported_svg = ET.tostring(root)
  8484. # Determine bounding area for svg export
  8485. bounds = box.bounds()
  8486. size = box.size()
  8487. # This contain the measure units
  8488. uom = obj.units.lower()
  8489. # Define a boundary around SVG of about 1.0mm (~39mils)
  8490. if uom in "mm":
  8491. boundary = 1.0
  8492. else:
  8493. boundary = 0.0393701
  8494. self.progress.emit(80)
  8495. # Convert everything to strings for use in the xml doc
  8496. svgwidth = str(size[0] + (2 * boundary))
  8497. svgheight = str(size[1] + (2 * boundary))
  8498. minx = str(bounds[0] - boundary)
  8499. miny = str(bounds[1] + boundary + size[1])
  8500. self.log.debug(minx)
  8501. self.log.debug(miny)
  8502. # Add a SVG Header and footer to the svg output from shapely
  8503. # The transform flips the Y Axis so that everything renders
  8504. # properly within svg apps such as inkscape
  8505. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8506. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8507. svg_header += 'width="' + svgwidth + uom + '" '
  8508. svg_header += 'height="' + svgheight + uom + '" '
  8509. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8510. svg_header += '>'
  8511. svg_header += '<g transform="scale(1,-1)">'
  8512. svg_footer = '</g> </svg>'
  8513. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  8514. self.progress.emit(90)
  8515. # Parse the xml through a xml parser just to add line feeds
  8516. # and to make it look more pretty for the output
  8517. doc = parse_xml_string(svg_elem)
  8518. try:
  8519. with open(filename, 'w') as fp:
  8520. fp.write(doc.toprettyxml())
  8521. except PermissionError:
  8522. self.inform.emit('[WARNING] %s' %
  8523. _("Permission denied, saving not possible.\n"
  8524. "Most likely another app is holding the file open and not accessible."))
  8525. return 'fail'
  8526. self.progress.emit(100)
  8527. if self.defaults["global_open_style"] is False:
  8528. self.file_opened.emit("SVG", filename)
  8529. self.file_saved.emit("SVG", filename)
  8530. self.inform.emit('[success] %s: %s' %
  8531. (_("SVG file exported to"), filename))
  8532. if use_thread is True:
  8533. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8534. def job_thread_film(app_obj):
  8535. try:
  8536. make_positive_film()
  8537. except Exception:
  8538. proc.done()
  8539. return
  8540. proc.done()
  8541. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8542. else:
  8543. make_positive_film()
  8544. def save_source_file(self, obj_name, filename, use_thread=True):
  8545. """
  8546. Exports a FlatCAM Object to an Gerber/Excellon file.
  8547. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8548. :param filename: Path to the Gerber file to save to.
  8549. :param use_thread: if to be run in a separate thread
  8550. :return:
  8551. """
  8552. self.report_usage("save source file()")
  8553. if filename is None:
  8554. filename = self.defaults["global_last_save_folder"]
  8555. self.log.debug("save source file()")
  8556. obj = self.collection.get_by_name(obj_name)
  8557. file_string = StringIO(obj.source_file)
  8558. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8559. try:
  8560. with open(filename, 'w') as file:
  8561. file.writelines('G04*\n')
  8562. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8563. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8564. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8565. file.writelines('G04 Created on : %s*\n' % time_string)
  8566. for line in file_string:
  8567. file.writelines(line)
  8568. except PermissionError:
  8569. self.inform.emit('[WARNING] %s' %
  8570. _("Permission denied, saving not possible.\n"
  8571. "Most likely another app is holding the file open and not accessible."))
  8572. return 'fail'
  8573. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8574. """
  8575. Exports a Excellon Object to an Excellon file.
  8576. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8577. :param filename: Path to the Excellon file to save to.
  8578. :param local_use:
  8579. :param use_thread: if to be run in a separate thread
  8580. :return:
  8581. """
  8582. self.report_usage("export_excellon()")
  8583. if filename is None:
  8584. filename = self.defaults["global_last_save_folder"]
  8585. self.log.debug("export_excellon()")
  8586. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8587. self.defaults["excellon_exp_decimals"]
  8588. )
  8589. if local_use is None:
  8590. try:
  8591. obj = self.collection.get_by_name(str(obj_name))
  8592. except Exception:
  8593. # TODO: The return behavior has not been established... should raise exception?
  8594. return "Could not retrieve object: %s" % obj_name
  8595. else:
  8596. obj = local_use
  8597. # updated units
  8598. eunits = self.defaults["excellon_exp_units"]
  8599. ewhole = self.defaults["excellon_exp_integer"]
  8600. efract = self.defaults["excellon_exp_decimals"]
  8601. ezeros = self.defaults["excellon_exp_zeros"]
  8602. eformat = self.defaults["excellon_exp_format"]
  8603. slot_type = self.defaults["excellon_exp_slot_type"]
  8604. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8605. if fc_units == 'MM':
  8606. factor = 1 if eunits == 'METRIC' else 0.03937
  8607. else:
  8608. factor = 25.4 if eunits == 'METRIC' else 1
  8609. def make_excellon():
  8610. try:
  8611. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8612. header = 'M48\n'
  8613. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8614. (str(self.version), str(self.version_date))
  8615. header += ';Filename: %s' % str(obj_name) + '\n'
  8616. header += ';Created on : %s' % time_str + '\n'
  8617. if eformat == 'dec':
  8618. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8619. header += eunits + '\n'
  8620. for tool in obj.tools:
  8621. if eunits == 'METRIC':
  8622. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8623. tool=str(tool),
  8624. dec=2)
  8625. else:
  8626. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8627. tool=str(tool),
  8628. dec=4)
  8629. else:
  8630. if ezeros == 'LZ':
  8631. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8632. form='ndec', e_zeros='LZ', factor=factor,
  8633. slot_type=slot_type)
  8634. header += '%s,%s\n' % (eunits, 'LZ')
  8635. header += format_exc
  8636. for tool in obj.tools:
  8637. if eunits == 'METRIC':
  8638. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8639. tool=str(tool),
  8640. dec=2)
  8641. else:
  8642. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8643. tool=str(tool),
  8644. dec=4)
  8645. else:
  8646. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8647. form='ndec', e_zeros='TZ', factor=factor,
  8648. slot_type=slot_type)
  8649. header += '%s,%s\n' % (eunits, 'TZ')
  8650. header += format_exc
  8651. for tool in obj.tools:
  8652. if eunits == 'METRIC':
  8653. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8654. tool=str(tool),
  8655. dec=2)
  8656. else:
  8657. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8658. tool=str(tool),
  8659. dec=4)
  8660. header += '%\n'
  8661. footer = 'M30\n'
  8662. exported_excellon = header
  8663. exported_excellon += excellon_code
  8664. exported_excellon += footer
  8665. if local_use is None:
  8666. try:
  8667. with open(filename, 'w') as fp:
  8668. fp.write(exported_excellon)
  8669. except PermissionError:
  8670. self.inform.emit('[WARNING] %s' %
  8671. _("Permission denied, saving not possible.\n"
  8672. "Most likely another app is holding the file open and not accessible."))
  8673. return 'fail'
  8674. if self.defaults["global_open_style"] is False:
  8675. self.file_opened.emit("Excellon", filename)
  8676. self.file_saved.emit("Excellon", filename)
  8677. self.inform.emit('[success] %s: %s' %
  8678. (_("Excellon file exported to"), filename))
  8679. else:
  8680. return exported_excellon
  8681. except Exception as e:
  8682. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8683. return 'fail'
  8684. if use_thread is True:
  8685. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8686. def job_thread_exc(app_obj):
  8687. ret = make_excellon()
  8688. if ret == 'fail':
  8689. self.inform.emit('[ERROR_NOTCL] %s' %
  8690. _('Could not export Excellon file.'))
  8691. return
  8692. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8693. else:
  8694. ret = make_excellon()
  8695. if ret == 'fail':
  8696. self.inform.emit('[ERROR_NOTCL] %s' %
  8697. _('Could not export Excellon file.'))
  8698. return 'fail'
  8699. if local_use is not None:
  8700. return ret
  8701. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8702. """
  8703. Exports a Gerber Object to an Gerber file.
  8704. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8705. :param filename: Path to the Gerber file to save to.
  8706. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8707. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8708. :param use_thread: if to be run in a separate thread
  8709. :return:
  8710. """
  8711. self.report_usage("export_gerber()")
  8712. if filename is None:
  8713. filename = self.defaults["global_last_save_folder"]
  8714. self.log.debug("export_gerber()")
  8715. if local_use is None:
  8716. try:
  8717. obj = self.collection.get_by_name(str(obj_name))
  8718. except Exception:
  8719. # TODO: The return behavior has not been established... should raise exception?
  8720. return "Could not retrieve object: %s" % obj_name
  8721. else:
  8722. obj = local_use
  8723. # updated units
  8724. gunits = self.defaults["gerber_exp_units"]
  8725. gwhole = self.defaults["gerber_exp_integer"]
  8726. gfract = self.defaults["gerber_exp_decimals"]
  8727. gzeros = self.defaults["gerber_exp_zeros"]
  8728. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8729. if fc_units == 'MM':
  8730. factor = 1 if gunits == 'MM' else 0.03937
  8731. else:
  8732. factor = 25.4 if gunits == 'MM' else 1
  8733. def make_gerber():
  8734. try:
  8735. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8736. header = 'G04*\n'
  8737. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8738. (str(self.version), str(self.version_date))
  8739. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8740. header += 'G04 Created on : %s*' % time_str + '\n'
  8741. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8742. header += "%MO{units}*%\n".format(units=gunits)
  8743. for apid in obj.apertures:
  8744. if obj.apertures[apid]['type'] == 'C':
  8745. header += "%ADD{apid}{type},{size}*%\n".format(
  8746. apid=str(apid),
  8747. type='C',
  8748. size=(factor * obj.apertures[apid]['size'])
  8749. )
  8750. elif obj.apertures[apid]['type'] == 'R':
  8751. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8752. apid=str(apid),
  8753. type='R',
  8754. width=(factor * obj.apertures[apid]['width']),
  8755. height=(factor * obj.apertures[apid]['height'])
  8756. )
  8757. elif obj.apertures[apid]['type'] == 'O':
  8758. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8759. apid=str(apid),
  8760. type='O',
  8761. width=(factor * obj.apertures[apid]['width']),
  8762. height=(factor * obj.apertures[apid]['height'])
  8763. )
  8764. header += '\n'
  8765. # obsolete units but some software may need it
  8766. if gunits == 'IN':
  8767. header += 'G70*\n'
  8768. else:
  8769. header += 'G71*\n'
  8770. # Absolute Mode
  8771. header += 'G90*\n'
  8772. header += 'G01*\n'
  8773. # positive polarity
  8774. header += '%LPD*%\n'
  8775. footer = 'M02*\n'
  8776. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8777. exported_gerber = header
  8778. exported_gerber += gerber_code
  8779. exported_gerber += footer
  8780. if local_use is None:
  8781. try:
  8782. with open(filename, 'w') as fp:
  8783. fp.write(exported_gerber)
  8784. except PermissionError:
  8785. self.inform.emit('[WARNING] %s' %
  8786. _("Permission denied, saving not possible.\n"
  8787. "Most likely another app is holding the file open and not accessible."))
  8788. return 'fail'
  8789. if self.defaults["global_open_style"] is False:
  8790. self.file_opened.emit("Gerber", filename)
  8791. self.file_saved.emit("Gerber", filename)
  8792. self.inform.emit('[success] %s: %s' %
  8793. (_("Gerber file exported to"), filename))
  8794. else:
  8795. return exported_gerber
  8796. except Exception as e:
  8797. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8798. return 'fail'
  8799. if use_thread is True:
  8800. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8801. def job_thread_grb(app_obj):
  8802. ret = make_gerber()
  8803. if ret == 'fail':
  8804. self.inform.emit('[ERROR_NOTCL] %s' %
  8805. _('Could not export Gerber file.'))
  8806. return
  8807. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8808. else:
  8809. ret = make_gerber()
  8810. if ret == 'fail':
  8811. self.inform.emit('[ERROR_NOTCL] %s' %
  8812. _('Could not export Gerber file.'))
  8813. return 'fail'
  8814. if local_use is not None:
  8815. return ret
  8816. def export_dxf(self, obj_name, filename, use_thread=True):
  8817. """
  8818. Exports a Geometry Object to an DXF file.
  8819. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8820. :param filename: Path to the DXF file to save to.
  8821. :param use_thread: if to be run in a separate thread
  8822. :return:
  8823. """
  8824. self.report_usage("export_dxf()")
  8825. if filename is None:
  8826. filename = self.defaults["global_last_save_folder"]
  8827. self.log.debug("export_dxf()")
  8828. try:
  8829. obj = self.collection.get_by_name(str(obj_name))
  8830. except Exception:
  8831. # TODO: The return behavior has not been established... should raise exception?
  8832. return "Could not retrieve object: %s" % obj_name
  8833. def make_dxf():
  8834. try:
  8835. dxf_code = obj.export_dxf()
  8836. dxf_code.saveas(filename)
  8837. if self.defaults["global_open_style"] is False:
  8838. self.file_opened.emit("DXF", filename)
  8839. self.file_saved.emit("DXF", filename)
  8840. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8841. except Exception:
  8842. return 'fail'
  8843. if use_thread is True:
  8844. with self.proc_container.new(_("Exporting DXF")) as proc:
  8845. def job_thread_exc(app_obj):
  8846. ret_dxf_val = make_dxf()
  8847. if ret_dxf_val == 'fail':
  8848. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8849. return
  8850. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8851. else:
  8852. ret = make_dxf()
  8853. if ret == 'fail':
  8854. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8855. return
  8856. def import_svg(self, filename, geo_type='geometry', outname=None):
  8857. """
  8858. Adds a new Geometry Object to the projects and populates
  8859. it with shapes extracted from the SVG file.
  8860. :param filename: Path to the SVG file.
  8861. :param geo_type: Type of FlatCAM object that will be created from SVG
  8862. :param outname:
  8863. :return:
  8864. """
  8865. self.report_usage("import_svg()")
  8866. log.debug("App.import_svg()")
  8867. obj_type = ""
  8868. if geo_type is None or geo_type == "geometry":
  8869. obj_type = "geometry"
  8870. elif geo_type == "gerber":
  8871. obj_type = geo_type
  8872. else:
  8873. self.inform.emit('[ERROR_NOTCL] %s' %
  8874. _("Not supported type is picked as parameter. "
  8875. "Only Geometry and Gerber are supported"))
  8876. return
  8877. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8878. def obj_init(geo_obj, app_obj):
  8879. geo_obj.import_svg(filename, obj_type, units=units)
  8880. geo_obj.multigeo = False
  8881. with self.proc_container.new(_("Importing SVG")) as proc:
  8882. # Object name
  8883. name = outname or filename.split('/')[-1].split('\\')[-1]
  8884. self.new_object(obj_type, name, obj_init, autoselected=False)
  8885. # Register recent file
  8886. self.file_opened.emit("svg", filename)
  8887. # GUI feedback
  8888. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8889. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8890. """
  8891. Adds a new Geometry Object to the projects and populates
  8892. it with shapes extracted from the DXF file.
  8893. :param filename: Path to the DXF file.
  8894. :param geo_type: Type of FlatCAM object that will be created from DXF
  8895. :param outname:
  8896. :type putname: str
  8897. :return:
  8898. """
  8899. self.report_usage("import_dxf()")
  8900. obj_type = ""
  8901. if geo_type is None or geo_type == "geometry":
  8902. obj_type = "geometry"
  8903. elif geo_type == "gerber":
  8904. obj_type = geo_type
  8905. else:
  8906. self.inform.emit('[ERROR_NOTCL] %s' %
  8907. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8908. return
  8909. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8910. def obj_init(geo_obj, app_obj):
  8911. geo_obj.import_dxf(filename, obj_type, units=units)
  8912. geo_obj.multigeo = False
  8913. with self.proc_container.new(_("Importing DXF")) as proc:
  8914. # Object name
  8915. name = outname or filename.split('/')[-1].split('\\')[-1]
  8916. self.new_object(obj_type, name, obj_init, autoselected=False)
  8917. self.progress.emit(20)
  8918. # Register recent file
  8919. self.file_opened.emit("dxf", filename)
  8920. # GUI feedback
  8921. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8922. self.progress.emit(100)
  8923. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8924. """
  8925. Adds a new Geometry Object to the projects and populates
  8926. it with shapes extracted from the SVG file.
  8927. :param filename: Path to the SVG file.
  8928. :param o_type: type of FlatCAM objeect
  8929. :param dpi: dot per inch
  8930. :param mode: black or color
  8931. :param mask: dictate the level of detail
  8932. :param outname: name for the resulting file
  8933. :return:
  8934. """
  8935. self.report_usage("import_image()")
  8936. if o_type is None or o_type == "geometry":
  8937. obj_type = "geometry"
  8938. elif o_type == "gerber":
  8939. obj_type = o_type
  8940. else:
  8941. self.inform.emit('[ERROR_NOTCL] %s' %
  8942. _("Not supported type is picked as parameter. "
  8943. "Only Geometry and Gerber are supported"))
  8944. return
  8945. def obj_init(geo_obj, app_obj):
  8946. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8947. geo_obj.multigeo = False
  8948. with self.proc_container.new(_("Importing Image")) as proc:
  8949. # Object name
  8950. name = outname or filename.split('/')[-1].split('\\')[-1]
  8951. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8952. self.new_object(obj_type, name, obj_init)
  8953. self.progress.emit(20)
  8954. # Register recent file
  8955. self.file_opened.emit("image", filename)
  8956. # GUI feedback
  8957. self.inform.emit('[success] %s: %s' %
  8958. (_("Opened"), filename))
  8959. self.progress.emit(100)
  8960. def open_gerber(self, filename, outname=None):
  8961. """
  8962. Opens a Gerber file, parses it and creates a new object for
  8963. it in the program. Thread-safe.
  8964. :param outname: Name of the resulting object. None causes the
  8965. name to be that of the file.
  8966. :param filename: Gerber file filename
  8967. :type filename: str
  8968. :return: None
  8969. """
  8970. # How the object should be initialized
  8971. def obj_init(gerber_obj, app_obj):
  8972. assert isinstance(gerber_obj, FlatCAMGerber), \
  8973. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8974. # Opening the file happens here
  8975. self.progress.emit(30)
  8976. try:
  8977. gerber_obj.parse_file(filename)
  8978. except IOError:
  8979. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8980. (_("Failed to open file"), filename))
  8981. app_obj.progress.emit(0)
  8982. return "fail"
  8983. except ParseError as err:
  8984. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8985. (_("Failed to parse file"), filename, str(err)))
  8986. app_obj.progress.emit(0)
  8987. self.log.error(str(err))
  8988. return "fail"
  8989. except Exception as e:
  8990. log.debug("App.open_gerber() --> %s" % str(e))
  8991. msg = '[ERROR] %s' % \
  8992. _("An internal error has occurred. See shell.\n")
  8993. msg += traceback.format_exc()
  8994. app_obj.inform.emit(msg)
  8995. return "fail"
  8996. if gerber_obj.is_empty():
  8997. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8998. # self.collection.set_active(gerber_obj.options["name"])
  8999. # self.collection.delete_active()
  9000. self.inform.emit('[ERROR_NOTCL] %s' %
  9001. _("Object is not Gerber file or empty. Aborting object creation."))
  9002. return "fail"
  9003. # Further parsing
  9004. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  9005. App.log.debug("open_gerber()")
  9006. with self.proc_container.new(_("Opening Gerber")) as proc:
  9007. self.progress.emit(10)
  9008. # Object name
  9009. name = outname or filename.split('/')[-1].split('\\')[-1]
  9010. # # ## Object creation # ##
  9011. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  9012. if ret == 'fail':
  9013. self.inform.emit('[ERROR_NOTCL]%s' %
  9014. _(' Open Gerber failed. Probable not a Gerber file.'))
  9015. return
  9016. # Register recent file
  9017. self.file_opened.emit("gerber", filename)
  9018. self.progress.emit(100)
  9019. # GUI feedback
  9020. self.inform.emit('[success] %s: %s' %
  9021. (_("Opened"), filename))
  9022. def open_excellon(self, filename, outname=None, plot=True):
  9023. """
  9024. Opens an Excellon file, parses it and creates a new object for
  9025. it in the program. Thread-safe.
  9026. :param outname: Name of the resulting object. None causes the
  9027. name to be that of the file.
  9028. :param filename: Excellon file filename
  9029. :type filename: str
  9030. :return: None
  9031. """
  9032. App.log.debug("open_excellon()")
  9033. # How the object should be initialized
  9034. def obj_init(excellon_obj, app_obj):
  9035. # self.progress.emit(20)
  9036. try:
  9037. ret = excellon_obj.parse_file(filename=filename)
  9038. if ret == "fail":
  9039. log.debug("Excellon parsing failed.")
  9040. self.inform.emit('[ERROR_NOTCL] %s' %
  9041. _("This is not Excellon file."))
  9042. return "fail"
  9043. except IOError:
  9044. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9045. (_("Cannot open file"), filename))
  9046. log.debug("Could not open Excellon object.")
  9047. self.progress.emit(0) # TODO: self and app_bjj mixed
  9048. return "fail"
  9049. except Exception:
  9050. msg = '[ERROR_NOTCL] %s' % \
  9051. _("An internal error has occurred. See shell.\n")
  9052. msg += traceback.format_exc()
  9053. app_obj.inform.emit(msg)
  9054. return "fail"
  9055. ret = excellon_obj.create_geometry()
  9056. if ret == 'fail':
  9057. log.debug("Could not create geometry for Excellon object.")
  9058. return "fail"
  9059. for tool in excellon_obj.tools:
  9060. if excellon_obj.tools[tool]['solid_geometry']:
  9061. return
  9062. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9063. (_("No geometry found in file"), filename))
  9064. return "fail"
  9065. with self.proc_container.new(_("Opening Excellon.")):
  9066. # Object name
  9067. name = outname or filename.split('/')[-1].split('\\')[-1]
  9068. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  9069. if ret_val == 'fail':
  9070. self.inform.emit('[ERROR_NOTCL] %s' %
  9071. _('Open Excellon file failed. Probable not an Excellon file.'))
  9072. return
  9073. # Register recent file
  9074. self.file_opened.emit("excellon", filename)
  9075. # GUI feedback
  9076. self.inform.emit('[success] %s: %s' %
  9077. (_("Opened"), filename))
  9078. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  9079. """
  9080. Opens a G-gcode file, parses it and creates a new object for
  9081. it in the program. Thread-safe.
  9082. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9083. :param filename: G-code file filename
  9084. :type filename: str
  9085. :return: None
  9086. """
  9087. App.log.debug("open_gcode()")
  9088. # How the object should be initialized
  9089. def obj_init(job_obj, app_obj_):
  9090. """
  9091. :param job_obj: the resulting object
  9092. :type app_obj_: App
  9093. """
  9094. assert isinstance(app_obj_, App), \
  9095. "Initializer expected App, got %s" % type(app_obj_)
  9096. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  9097. try:
  9098. f = open(filename)
  9099. gcode = f.read()
  9100. f.close()
  9101. except IOError:
  9102. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  9103. (_("Failed to open"), filename))
  9104. return "fail"
  9105. job_obj.gcode = gcode
  9106. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  9107. if gcode_ret == "fail":
  9108. self.inform.emit('[ERROR_NOTCL] %s' %
  9109. _("This is not GCODE"))
  9110. return "fail"
  9111. job_obj.create_geometry()
  9112. with self.proc_container.new(_("Opening G-Code.")):
  9113. # Object name
  9114. name = outname or filename.split('/')[-1].split('\\')[-1]
  9115. # New object creation and file processing
  9116. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9117. if obj_ret == 'fail':
  9118. self.inform.emit('[ERROR_NOTCL] %s' %
  9119. _("Failed to create CNCJob Object. Probable not a GCode file. "
  9120. "Try to load it from File menu.\n "
  9121. "Attempting to create a FlatCAM CNCJob Object from "
  9122. "G-Code file failed during processing"))
  9123. return "fail"
  9124. # Register recent file
  9125. self.file_opened.emit("cncjob", filename)
  9126. # GUI feedback
  9127. self.inform.emit('[success] %s: %s' %
  9128. (_("Opened"), filename))
  9129. def open_script(self, filename, outname=None, silent=False):
  9130. """
  9131. Opens a Script file, parses it and creates a new object for
  9132. it in the program. Thread-safe.
  9133. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9134. :param filename: Script file filename
  9135. :type filename: str
  9136. :return: None
  9137. """
  9138. App.log.debug("open_script()")
  9139. with self.proc_container.new(_("Opening TCL Script...")):
  9140. try:
  9141. with open(filename, "r") as opened_script:
  9142. script_content = opened_script.readlines()
  9143. script_content = ''.join(script_content)
  9144. if silent is False:
  9145. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  9146. except Exception as e:
  9147. log.debug("App.open_script() -> %s" % str(e))
  9148. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  9149. return
  9150. # Object name
  9151. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  9152. # New object creation and file processing
  9153. self.on_filenewscript(name=script_name, text=script_content)
  9154. # Register recent file
  9155. self.file_opened.emit("script", filename)
  9156. # GUI feedback
  9157. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9158. def open_config_file(self, filename, run_from_arg=None):
  9159. """
  9160. Loads a config file from the specified file.
  9161. :param filename: Name of the file from which to load.
  9162. :type filename: str
  9163. :return: None
  9164. """
  9165. App.log.debug("Opening config file: " + filename)
  9166. if run_from_arg:
  9167. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9168. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9169. _("Opening FlatCAM Config file.")),
  9170. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9171. color=QtGui.QColor("gray"))
  9172. # # add the tab if it was closed
  9173. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9174. # # first clear previous text in text editor (if any)
  9175. # self.ui.text_editor_tab.code_editor.clear()
  9176. #
  9177. # # Switch plot_area to CNCJob tab
  9178. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9179. # close the Code editor if already open
  9180. if self.toggle_codeeditor:
  9181. self.on_toggle_code_editor()
  9182. self.on_toggle_code_editor()
  9183. try:
  9184. if filename:
  9185. f = QtCore.QFile(filename)
  9186. if f.open(QtCore.QIODevice.ReadOnly):
  9187. stream = QtCore.QTextStream(f)
  9188. code_edited = stream.readAll()
  9189. self.text_editor_tab.code_editor.setPlainText(code_edited)
  9190. f.close()
  9191. except IOError:
  9192. App.log.error("Failed to open config file: %s" % filename)
  9193. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9194. (_("Failed to open config file"), filename))
  9195. return
  9196. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  9197. """
  9198. Loads a project from the specified file.
  9199. 1) Loads and parses file
  9200. 2) Registers the file as recently opened.
  9201. 3) Calls on_file_new()
  9202. 4) Updates options
  9203. 5) Calls new_object() with the object's from_dict() as init method.
  9204. 6) Calls plot_all() if plot=True
  9205. :param filename: Name of the file from which to load.
  9206. :type filename: str
  9207. :param run_from_arg: True if run for arguments
  9208. :param plot: If True plot all objects in the project
  9209. :param cli: run from command line
  9210. :return: None
  9211. """
  9212. App.log.debug("Opening project: " + filename)
  9213. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9214. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9215. if cli is None:
  9216. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9217. if run_from_arg:
  9218. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9219. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9220. _("Opening FlatCAM Project file.")),
  9221. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9222. color=QtGui.QColor("gray"))
  9223. # Open and parse an uncompressed Project file
  9224. try:
  9225. f = open(filename, 'r')
  9226. except IOError:
  9227. App.log.error("Failed to open project file: %s" % filename)
  9228. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9229. (_("Failed to open project file"), filename))
  9230. return
  9231. try:
  9232. d = json.load(f, object_hook=dict2obj)
  9233. except Exception as e:
  9234. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9235. (filename, str(e)))
  9236. f.close()
  9237. # Open and parse a compressed Project file
  9238. try:
  9239. with lzma.open(filename) as f:
  9240. file_content = f.read().decode('utf-8')
  9241. d = json.loads(file_content, object_hook=dict2obj)
  9242. except Exception as e:
  9243. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9244. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9245. (_("Failed to open project file"), filename))
  9246. return
  9247. # Clear the current project
  9248. # # NOT THREAD SAFE # ##
  9249. if run_from_arg is True:
  9250. pass
  9251. elif cli is True:
  9252. self.delete_selection_shape()
  9253. else:
  9254. self.on_file_new()
  9255. # Project options
  9256. self.options.update(d['options'])
  9257. self.project_filename = filename
  9258. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9259. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9260. if cli is None:
  9261. self.set_screen_units(self.options["units"])
  9262. # Re create objects
  9263. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9264. for obj in d['objs']:
  9265. def obj_init(obj_inst, app_inst):
  9266. obj_inst.from_dict(obj)
  9267. App.log.debug("Recreating from opened project an %s object: %s" %
  9268. (obj['kind'].capitalize(), obj['options']['name']))
  9269. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9270. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9271. if cli is None:
  9272. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9273. obj['kind'].upper(),
  9274. obj['options']['name']
  9275. )
  9276. )
  9277. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9278. self.inform.emit('[success] %s: %s' %
  9279. (_("Project loaded from"), filename))
  9280. self.should_we_save = False
  9281. self.file_opened.emit("project", filename)
  9282. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9283. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9284. if cli is None:
  9285. self.set_ui_title(name=self.project_filename)
  9286. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9287. def propagate_defaults(self, silent=False):
  9288. """
  9289. This method is used to set default values in classes. It's
  9290. an alternative to project options but allows the use
  9291. of values invisible to the user.
  9292. :return: None
  9293. """
  9294. if silent is False:
  9295. self.log.debug("propagate_defaults()")
  9296. # Which objects to update the given parameters.
  9297. routes = {
  9298. "global_zdownrate": CNCjob,
  9299. "excellon_zeros": Excellon,
  9300. "excellon_format_upper_in": Excellon,
  9301. "excellon_format_lower_in": Excellon,
  9302. "excellon_format_upper_mm": Excellon,
  9303. "excellon_format_lower_mm": Excellon,
  9304. "excellon_units": Excellon,
  9305. "gerber_use_buffer_for_union": Gerber,
  9306. "geometry_multidepth": Geometry
  9307. }
  9308. for param in routes:
  9309. if param in routes[param].defaults:
  9310. try:
  9311. routes[param].defaults[param] = self.defaults[param]
  9312. if silent is False:
  9313. self.log.debug(" " + param + " OK")
  9314. except KeyError:
  9315. if silent is False:
  9316. self.log.debug(" ERROR: " + param + " not in defaults.")
  9317. else:
  9318. # Try extracting the name:
  9319. # classname_param here is param in the object
  9320. if param.find(routes[param].__name__.lower() + "_") == 0:
  9321. p = param[len(routes[param].__name__) + 1:]
  9322. if p in routes[param].defaults:
  9323. routes[param].defaults[p] = self.defaults[param]
  9324. if silent is False:
  9325. self.log.debug(" " + param + " OK!")
  9326. def plot_all(self, zoom=True):
  9327. """
  9328. Re-generates all plots from all objects.
  9329. :return: None
  9330. """
  9331. self.log.debug("Plot_all()")
  9332. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9333. for obj in self.collection.get_list():
  9334. def worker_task(obj):
  9335. with self.proc_container.new("Plotting"):
  9336. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9337. if zoom:
  9338. self.object_plotted.emit(obj)
  9339. # Send to worker
  9340. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9341. def register_folder(self, filename):
  9342. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9343. def register_save_folder(self, filename):
  9344. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9345. def set_progress_bar(self, percentage, text=""):
  9346. self.ui.progress_bar.setValue(int(percentage))
  9347. def setup_shell(self):
  9348. """
  9349. Creates shell functions. Runs once at startup.
  9350. :return: None
  9351. """
  9352. self.log.debug("setup_shell()")
  9353. def shelp(p=None):
  9354. if not p:
  9355. return _("Available commands:\n") + \
  9356. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9357. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9358. if p not in commands:
  9359. return "Unknown command: %s" % p
  9360. return commands[p]["help"]
  9361. # --- Migrated to new architecture ---
  9362. # def options(name):
  9363. # ops = self.collection.get_by_name(str(name)).options
  9364. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9365. def h(*args):
  9366. """
  9367. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9368. and standalone parameters into list.
  9369. """
  9370. kwa = {}
  9371. a = []
  9372. n = len(args)
  9373. name = None
  9374. for i in range(n):
  9375. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9376. if match:
  9377. assert name is None
  9378. name = match.group(1)
  9379. continue
  9380. if name is None:
  9381. a.append(args[i])
  9382. else:
  9383. kwa[name] = args[i]
  9384. name = None
  9385. return a, kwa
  9386. @contextmanager
  9387. def wait_signal(signal, timeout=10000):
  9388. """
  9389. Block loop until signal emitted, timeout (ms) elapses
  9390. or unhandled exception happens in a thread.
  9391. :param timeout: time after which the loop is exited
  9392. :param signal: Signal to wait for.
  9393. """
  9394. loop = QtCore.QEventLoop()
  9395. # Normal termination
  9396. signal.connect(loop.quit)
  9397. # Termination by exception in thread
  9398. self.thread_exception.connect(loop.quit)
  9399. status = {'timed_out': False}
  9400. def report_quit():
  9401. status['timed_out'] = True
  9402. loop.quit()
  9403. yield
  9404. # Temporarily change how exceptions are managed.
  9405. oeh = sys.excepthook
  9406. ex = []
  9407. def except_hook(type_, value, traceback_):
  9408. ex.append(value)
  9409. oeh(type_, value, traceback_)
  9410. sys.excepthook = except_hook
  9411. # Terminate on timeout
  9412. if timeout is not None:
  9413. QtCore.QTimer.singleShot(timeout, report_quit)
  9414. # # ## Block ## ##
  9415. loop.exec_()
  9416. # Restore exception management
  9417. sys.excepthook = oeh
  9418. if ex:
  9419. self.raiseTclError(str(ex[0]))
  9420. if status['timed_out']:
  9421. raise Exception('Timed out!')
  9422. def make_docs():
  9423. output = ''
  9424. import collections
  9425. od = collections.OrderedDict(sorted(commands.items()))
  9426. for cmd_, val in od.items():
  9427. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9428. t = val['help']
  9429. usage_i = t.find('>')
  9430. if usage_i < 0:
  9431. expl = t
  9432. output += expl + '\n\n'
  9433. continue
  9434. expl = t[:usage_i - 1]
  9435. output += expl + '\n\n'
  9436. end_usage_i = t[usage_i:].find('\n')
  9437. if end_usage_i < 0:
  9438. end_usage_i = len(t[usage_i:])
  9439. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9440. else:
  9441. extras = t[usage_i+end_usage_i+1:]
  9442. parts = [s.strip() for s in extras.split('\n')]
  9443. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9444. for p in parts:
  9445. output += ' ' + p + '\n\n'
  9446. return output
  9447. '''
  9448. Howto implement TCL shell commands:
  9449. All parameters passed to command should be possible to set as None and test it afterwards.
  9450. This is because we need to see error caused in tcl,
  9451. if None value as default parameter is not allowed TCL will return empty error.
  9452. Use:
  9453. def mycommand(name=None,...):
  9454. Test it like this:
  9455. if name is None:
  9456. self.raise_tcl_error('Argument name is missing.')
  9457. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9458. otherwise we will miss it and processing will silently continue.
  9459. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9460. which is catched in exec_command and displayed in TCL shell console with red background.
  9461. Error in console is displayed with TCL trace.
  9462. This behavior works only within main thread,
  9463. errors with promissed tasks can be catched and detected only with log.
  9464. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9465. TCL shell.
  9466. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9467. '''
  9468. commands = {
  9469. 'help': {
  9470. 'fcn': shelp,
  9471. 'help': _("Shows list of commands.")
  9472. },
  9473. }
  9474. # Import/overwrite tcl commands as objects of TclCommand descendants
  9475. # This modifies the variable 'commands'.
  9476. tclCommands.register_all_commands(self, commands)
  9477. # Add commands to the tcl interpreter
  9478. for cmd in commands:
  9479. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9480. # Make the tcl puts function return instead of print to stdout
  9481. self.tcl.eval('''
  9482. rename puts original_puts
  9483. proc puts {args} {
  9484. if {[llength $args] == 1} {
  9485. return "[lindex $args 0]"
  9486. } else {
  9487. eval original_puts $args
  9488. }
  9489. }
  9490. ''')
  9491. def setup_recent_items(self):
  9492. # TODO: Move this to constructor
  9493. icons = {
  9494. "gerber": "share/flatcam_icon16.png",
  9495. "excellon": "share/drill16.png",
  9496. 'geometry': "share/geometry16.png",
  9497. "cncjob": "share/cnc16.png",
  9498. "script": "share/script_new24.png",
  9499. "document": "share/notes16_1.png",
  9500. "project": "share/project16.png",
  9501. "svg": "share/geometry16.png",
  9502. "dxf": "share/dxf16.png",
  9503. "pdf": "share/pdf32.png",
  9504. "image": "share/image16.png"
  9505. }
  9506. openers = {
  9507. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9508. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9509. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9510. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9511. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9512. "document": None,
  9513. 'project': self.open_project,
  9514. 'svg': self.import_svg,
  9515. 'dxf': self.import_dxf,
  9516. 'image': self.import_image,
  9517. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9518. }
  9519. # Open recent file for files
  9520. try:
  9521. f = open(self.data_path + '/recent.json')
  9522. except IOError:
  9523. App.log.error("Failed to load recent item list.")
  9524. self.inform.emit('[ERROR_NOTCL] %s' %
  9525. _("Failed to load recent item list."))
  9526. return
  9527. try:
  9528. self.recent = json.load(f)
  9529. except json.scanner.JSONDecodeError:
  9530. App.log.error("Failed to parse recent item list.")
  9531. self.inform.emit('[ERROR_NOTCL] %s' %
  9532. _("Failed to parse recent item list."))
  9533. f.close()
  9534. return
  9535. f.close()
  9536. # Open recent file for projects
  9537. try:
  9538. fp = open(self.data_path + '/recent_projects.json')
  9539. except IOError:
  9540. App.log.error("Failed to load recent project item list.")
  9541. self.inform.emit('[ERROR_NOTCL] %s' %
  9542. _("Failed to load recent projects item list."))
  9543. return
  9544. try:
  9545. self.recent_projects = json.load(fp)
  9546. except json.scanner.JSONDecodeError:
  9547. App.log.error("Failed to parse recent project item list.")
  9548. self.inform.emit('[ERROR_NOTCL] %s' %
  9549. _("Failed to parse recent project item list."))
  9550. fp.close()
  9551. return
  9552. fp.close()
  9553. # Closure needed to create callbacks in a loop.
  9554. # Otherwise late binding occurs.
  9555. def make_callback(func, fname):
  9556. def opener():
  9557. func(fname)
  9558. return opener
  9559. def reset_recent_files():
  9560. # Reset menu
  9561. self.ui.recent.clear()
  9562. self.recent = []
  9563. try:
  9564. ff = open(self.data_path + '/recent.json', 'w')
  9565. except IOError:
  9566. App.log.error("Failed to open recent items file for writing.")
  9567. return
  9568. json.dump(self.recent, ff)
  9569. def reset_recent_projects():
  9570. # Reset menu
  9571. self.ui.recent_projects.clear()
  9572. self.recent_projects = []
  9573. try:
  9574. fp = open(self.data_path + '/recent_projects.json', 'w')
  9575. except IOError:
  9576. App.log.error("Failed to open recent projects items file for writing.")
  9577. return
  9578. json.dump(self.recent, fp)
  9579. # Reset menu
  9580. self.ui.recent.clear()
  9581. self.ui.recent_projects.clear()
  9582. # Create menu items for projects
  9583. for recent in self.recent_projects:
  9584. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9585. if recent['kind'] == 'project':
  9586. try:
  9587. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9588. # Attach callback
  9589. o = make_callback(openers[recent["kind"]], recent['filename'])
  9590. action.triggered.connect(o)
  9591. self.ui.recent_projects.addAction(action)
  9592. except KeyError:
  9593. App.log.error("Unsupported file type: %s" % recent["kind"])
  9594. # Last action in Recent Files menu is one that Clear the content
  9595. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent projects")), self)
  9596. clear_action_proj.triggered.connect(reset_recent_projects)
  9597. self.ui.recent_projects.addSeparator()
  9598. self.ui.recent_projects.addAction(clear_action_proj)
  9599. # Create menu items for files
  9600. for recent in self.recent:
  9601. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9602. if recent['kind'] != 'project':
  9603. try:
  9604. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9605. # Attach callback
  9606. o = make_callback(openers[recent["kind"]], recent['filename'])
  9607. action.triggered.connect(o)
  9608. self.ui.recent.addAction(action)
  9609. except KeyError:
  9610. App.log.error("Unsupported file type: %s" % recent["kind"])
  9611. # Last action in Recent Files menu is one that Clear the content
  9612. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9613. clear_action.triggered.connect(reset_recent_files)
  9614. self.ui.recent.addSeparator()
  9615. self.ui.recent.addAction(clear_action)
  9616. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9617. # self.ui.menufilerecent.set_submenu(recent_menu)
  9618. # recent_menu.show_all()
  9619. # self.ui.recent.show()
  9620. self.log.debug("Recent items list has been populated.")
  9621. def setup_component_editor(self):
  9622. # label = QtWidgets.QLabel("Choose an item from Project")
  9623. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9624. sel_title = QtWidgets.QTextEdit(
  9625. _('<b>Shortcut Key List</b>'))
  9626. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9627. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9628. settings = QSettings("Open Source", "FlatCAM")
  9629. if settings.contains("notebook_font_size"):
  9630. fsize = settings.value('notebook_font_size', type=int)
  9631. else:
  9632. fsize = 12
  9633. tsize = fsize + int(fsize / 2)
  9634. # selected_text = (_('''
  9635. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9636. #
  9637. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9638. # The normal flow when working in FlatCAM is the following:</span></p>
  9639. #
  9640. # <ol>
  9641. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9642. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9643. # even dragging and dropping the files on the GUI.<br />
  9644. # <br />
  9645. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9646. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9647. # &nbsp;</li>
  9648. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9649. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9650. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9651. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9652. # <br />
  9653. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9654. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9655. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9656. # it even if it was out of focus.<br />
  9657. # <br />
  9658. # You can change the parameters in this screen and the flow direction is like this:<br />
  9659. # <br />
  9660. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9661. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9662. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9663. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9664. # </ol>
  9665. #
  9666. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9667. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9668. # <strong>F3</strong>.</span></p>
  9669. #
  9670. # ''').format(fsize=fsize, tsize=tsize))
  9671. selected_text = '''
  9672. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9673. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9674. {s1}</span></p>
  9675. <ol>
  9676. <li><span style="font-size:{fsize}px">{s2}<br />
  9677. <br />
  9678. {s3}</span><br />
  9679. &nbsp;</li>
  9680. <li><span style="font-size:{fsize}px">{s4}<br />
  9681. &nbsp;</li>
  9682. <br />
  9683. <li><span style="font-size:{fsize}px">{s5}<br />
  9684. &nbsp;</li>
  9685. <br />
  9686. <li><span style="font-size:{fsize}px">{s6}<br />
  9687. <br />
  9688. {s7}</span></li>
  9689. </ol>
  9690. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9691. '''.format(
  9692. title=_("Selected Tab - Choose an Item from Project Tab"),
  9693. subtitle=_("Details"),
  9694. s1=_("The normal flow when working in FlatCAM is the following:"),
  9695. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9696. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9697. "files on the GUI."),
  9698. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9699. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9700. "actions offered within the app."),
  9701. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9702. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9703. "SELECTED TAB will be updated with the object properties according to its kind: "
  9704. "Gerber, Excellon, Geometry or CNCJob object."),
  9705. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9706. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9707. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9708. "the SELECTED TAB and populate it even if it was out of focus."),
  9709. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9710. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9711. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9712. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9713. "(again, done in SELECTED TAB) --> Save GCode."),
  9714. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9715. "or through its own key shortcut: <b>F3</b>."),
  9716. tsize=tsize,
  9717. fsize=fsize
  9718. )
  9719. sel_title.setText(selected_text)
  9720. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9721. self.ui.selected_scroll_area.setWidget(sel_title)
  9722. def setup_obj_classes(self):
  9723. """
  9724. Sets up application specifics on the FlatCAMObj class.
  9725. :return: None
  9726. """
  9727. FlatCAMObj.app = self
  9728. ObjectCollection.app = self
  9729. Gerber.app = self
  9730. Excellon.app = self
  9731. Geometry.app = self
  9732. CNCjob.app = self
  9733. FCProcess.app = self
  9734. FCProcessContainer.app = self
  9735. def version_check(self):
  9736. """
  9737. Checks for the latest version of the program. Alerts the
  9738. user if theirs is outdated. This method is meant to be run
  9739. in a separate thread.
  9740. :return: None
  9741. """
  9742. self.log.debug("version_check()")
  9743. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9744. full_url = App.version_url + \
  9745. "?s=" + str(self.defaults['global_serial']) + \
  9746. "&v=" + str(self.version) + \
  9747. "&os=" + str(self.os) + \
  9748. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9749. else:
  9750. # no_stats dict; just so it won't break things on website
  9751. no_ststs_dict = {}
  9752. no_ststs_dict["global_ststs"] = {}
  9753. full_url = App.version_url + \
  9754. "?s=" + str(self.defaults['global_serial']) + \
  9755. "&v=" + str(self.version) + \
  9756. "&os=" + str(self.os) + \
  9757. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9758. App.log.debug("Checking for updates @ %s" % full_url)
  9759. # ## Get the data
  9760. try:
  9761. f = urllib.request.urlopen(full_url)
  9762. except Exception:
  9763. # App.log.warning("Failed checking for latest version. Could not connect.")
  9764. self.log.warning("Failed checking for latest version. Could not connect.")
  9765. self.inform.emit('[WARNING_NOTCL] %s' %
  9766. _("Failed checking for latest version. Could not connect."))
  9767. return
  9768. try:
  9769. data = json.load(f)
  9770. except Exception as e:
  9771. App.log.error("Could not parse information about latest version.")
  9772. self.inform.emit('[ERROR_NOTCL] %s' %
  9773. _("Could not parse information about latest version."))
  9774. App.log.debug("json.load(): %s" % str(e))
  9775. f.close()
  9776. return
  9777. f.close()
  9778. # ## Latest version?
  9779. if self.version >= data["version"]:
  9780. App.log.debug("FlatCAM is up to date!")
  9781. self.inform.emit('[success] %s' %
  9782. _("FlatCAM is up to date!"))
  9783. return
  9784. App.log.debug("Newer version available.")
  9785. self.message.emit(
  9786. _("Newer Version Available"),
  9787. _("There is a newer version of FlatCAM available for download:\n\n") +
  9788. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9789. _("info")
  9790. )
  9791. def on_plotcanvas_setup(self, container=None):
  9792. """
  9793. This is doing the setup for the plot area (VisPy canvas)
  9794. :param container: widget where to install the canvas
  9795. :return: None
  9796. """
  9797. if container:
  9798. plot_container = container
  9799. else:
  9800. plot_container = self.ui.right_layout
  9801. if self.is_legacy is False:
  9802. self.plotcanvas = PlotCanvas(plot_container, self)
  9803. else:
  9804. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9805. # So it can receive key presses
  9806. self.plotcanvas.native.setFocus()
  9807. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9808. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9809. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9810. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  9811. # Keys over plot enabled
  9812. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9813. if self.defaults['global_cursor_type'] == 'small':
  9814. self.app_cursor = self.plotcanvas.new_cursor()
  9815. else:
  9816. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9817. if self.ui.grid_snap_btn.isChecked():
  9818. self.app_cursor.enabled = True
  9819. else:
  9820. self.app_cursor.enabled = False
  9821. if self.is_legacy is False:
  9822. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9823. else:
  9824. # will use the default Matplotlib axes
  9825. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9826. def on_zoom_fit(self, event):
  9827. """
  9828. Callback for zoom-out request. This can be either from the corresponding
  9829. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9830. with axes limits from the geometry bounds of all objects.
  9831. :param event: Ignored.
  9832. :return: None
  9833. """
  9834. if self.is_legacy is False:
  9835. self.plotcanvas.fit_view()
  9836. else:
  9837. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9838. width = xmax - xmin
  9839. height = ymax - ymin
  9840. xmin -= 0.05 * width
  9841. xmax += 0.05 * width
  9842. ymin -= 0.05 * height
  9843. ymax += 0.05 * height
  9844. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9845. def on_zoom_in(self):
  9846. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9847. def on_zoom_out(self):
  9848. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9849. def disable_all_plots(self):
  9850. self.report_usage("disable_all_plots()")
  9851. self.disable_plots(self.collection.get_list())
  9852. self.inform.emit('[success] %s' %
  9853. _("All plots disabled."))
  9854. def disable_other_plots(self):
  9855. self.report_usage("disable_other_plots()")
  9856. self.disable_plots(self.collection.get_non_selected())
  9857. self.inform.emit('[success] %s' %
  9858. _("All non selected plots disabled."))
  9859. def enable_all_plots(self):
  9860. self.report_usage("enable_all_plots()")
  9861. self.enable_plots(self.collection.get_list())
  9862. self.inform.emit('[success] %s' %
  9863. _("All plots enabled."))
  9864. def on_enable_sel_plots(self):
  9865. log.debug("App.on_enable_sel_plot()")
  9866. object_list = self.collection.get_selected()
  9867. self.enable_plots(objects=object_list)
  9868. self.inform.emit('[success] %s' %
  9869. _("Selected plots enabled..."))
  9870. def on_disable_sel_plots(self):
  9871. log.debug("App.on_disable_sel_plot()")
  9872. # self.inform.emit(_("Disabling plots ..."))
  9873. object_list = self.collection.get_selected()
  9874. self.disable_plots(objects=object_list)
  9875. self.inform.emit('[success] %s' %
  9876. _("Selected plots disabled..."))
  9877. def enable_plots(self, objects):
  9878. """
  9879. Disables plots
  9880. :param objects: list of Objects to be enabled
  9881. :return:
  9882. """
  9883. log.debug("Enabling plots ...")
  9884. # self.inform.emit(_("Working ..."))
  9885. for obj in objects:
  9886. if obj.options['plot'] is False:
  9887. obj.options.set_change_callback(lambda x: None)
  9888. obj.options['plot'] = True
  9889. obj.options.set_change_callback(obj.on_options_change)
  9890. def worker_task(objs):
  9891. with self.proc_container.new(_("Enabling plots ...")):
  9892. for obj in objs:
  9893. # obj.options['plot'] = True
  9894. if isinstance(obj, FlatCAMCNCjob):
  9895. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9896. else:
  9897. obj.plot(visible=True)
  9898. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9899. # self.plots_updated.emit()
  9900. def disable_plots(self, objects):
  9901. """
  9902. Disables plots
  9903. :param objects: list of Objects to be disabled
  9904. :return:
  9905. """
  9906. # if no objects selected then do nothing
  9907. if not self.collection.get_selected():
  9908. return
  9909. log.debug("Disabling plots ...")
  9910. # self.inform.emit(_("Working ..."))
  9911. for obj in objects:
  9912. if obj.options['plot'] is True:
  9913. obj.options.set_change_callback(lambda x: None)
  9914. obj.options['plot'] = False
  9915. obj.options.set_change_callback(obj.on_options_change)
  9916. try:
  9917. self.delete_selection_shape()
  9918. except Exception as e:
  9919. log.debug("App.disable_plots() --> %s" % str(e))
  9920. # self.plots_updated.emit()
  9921. def worker_task(objs):
  9922. with self.proc_container.new(_("Disabling plots ...")):
  9923. for obj in objs:
  9924. # obj.options['plot'] = True
  9925. if isinstance(obj, FlatCAMCNCjob):
  9926. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9927. else:
  9928. obj.plot(visible=False)
  9929. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9930. def toggle_plots(self, objects):
  9931. """
  9932. Toggle plots visibility
  9933. :param objects: list of Objects for which to be toggled the visibility
  9934. :return:
  9935. """
  9936. # if no objects selected then do nothing
  9937. if not self.collection.get_selected():
  9938. return
  9939. log.debug("Toggling plots ...")
  9940. self.inform.emit(_("Working ..."))
  9941. for obj in objects:
  9942. if obj.options['plot'] is False:
  9943. obj.options['plot'] = True
  9944. else:
  9945. obj.options['plot'] = False
  9946. self.plots_updated.emit()
  9947. def clear_plots(self):
  9948. objects = self.collection.get_list()
  9949. for obj in objects:
  9950. obj.clear(obj == objects[-1])
  9951. # Clear pool to free memory
  9952. self.clear_pool()
  9953. def generate_cnc_job(self, objects):
  9954. self.report_usage("generate_cnc_job()")
  9955. # for obj in objects:
  9956. # obj.generatecncjob()
  9957. for obj in objects:
  9958. obj.on_generatecnc_button_click()
  9959. def save_project(self, filename, quit_action=False, silent=False):
  9960. """
  9961. Saves the current project to the specified file.
  9962. :param filename: Name of the file in which to save.
  9963. :type filename: str
  9964. :param quit_action: if the project saving will be followed by an app quit; boolean
  9965. :param silent: if True will not display status messages
  9966. :return: None
  9967. """
  9968. self.log.debug("save_project()")
  9969. self.save_in_progress = True
  9970. with self.proc_container.new(_("Saving FlatCAM Project")):
  9971. # Capture the latest changes
  9972. # Current object
  9973. try:
  9974. self.collection.get_active().read_form()
  9975. except Exception as e:
  9976. self.log.debug("There was no active object. %s" % str(e))
  9977. pass
  9978. # Serialize the whole project
  9979. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9980. "options": self.options,
  9981. "version": self.version}
  9982. if self.defaults["global_save_compressed"] is True:
  9983. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9984. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9985. # # Write
  9986. f.write(g)
  9987. self.inform.emit('[success] %s: %s' %
  9988. (_("Project saved to"), filename))
  9989. else:
  9990. # Open file
  9991. try:
  9992. f = open(filename, 'w')
  9993. except IOError:
  9994. App.log.error("Failed to open file for saving: %s", filename)
  9995. return
  9996. # Write
  9997. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9998. f.close()
  9999. # verification of the saved project
  10000. # Open and parse
  10001. try:
  10002. saved_f = open(filename, 'r')
  10003. except IOError:
  10004. if silent is False:
  10005. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10006. (_("Failed to verify project file"), filename, _("Retry to save it."))
  10007. )
  10008. return
  10009. try:
  10010. saved_d = json.load(saved_f, object_hook=dict2obj)
  10011. except Exception:
  10012. if silent is False:
  10013. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10014. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  10015. )
  10016. f.close()
  10017. return
  10018. saved_f.close()
  10019. if silent is False:
  10020. if 'version' in saved_d:
  10021. self.inform.emit('[success] %s: %s' %
  10022. (_("Project saved to"), filename))
  10023. else:
  10024. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10025. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  10026. )
  10027. tb_settings = QSettings("Open Source", "FlatCAM")
  10028. lock_state = self.ui.lock_action.isChecked()
  10029. tb_settings.setValue('toolbar_lock', lock_state)
  10030. # This will write the setting to the platform specific storage.
  10031. del tb_settings
  10032. # if quit:
  10033. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  10034. # t.start()
  10035. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  10036. def start_delayed_quit(self, delay, filename, should_quit=None):
  10037. """
  10038. :param delay: period of checking if project file size is more than zero; in seconds
  10039. :param filename: the name of the project file to be checked periodically for size more than zero
  10040. :param should_quit: if the task finished will be followed by an app quit; boolean
  10041. :return:
  10042. """
  10043. to_quit = should_quit
  10044. self.save_timer = QtCore.QTimer()
  10045. self.save_timer.setInterval(delay)
  10046. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  10047. self.save_timer.start()
  10048. def check_project_file_size(self, filename, should_quit=None):
  10049. """
  10050. :param filename: the name of the project file to be checked periodically for size more than zero
  10051. :param should_quit: will quit the app if True; boolean
  10052. :return:
  10053. """
  10054. try:
  10055. if os.stat(filename).st_size > 0:
  10056. self.save_in_progress = False
  10057. self.save_timer.stop()
  10058. if should_quit:
  10059. self.app_quit.emit()
  10060. except Exception:
  10061. traceback.print_exc()
  10062. def on_plotarea_tab_closed(self, tab_idx):
  10063. widget = self.ui.plot_tab_area.widget(tab_idx)
  10064. if widget is not None:
  10065. widget.deleteLater()
  10066. self.ui.plot_tab_area.removeTab(tab_idx)
  10067. def on_options_app2project(self):
  10068. """
  10069. Callback for Options->Transfer Options->App=>Project. Copies options
  10070. from application defaults to project defaults.
  10071. :return: None
  10072. """
  10073. self.report_usage("on_options_app2project")
  10074. self.defaults_read_form()
  10075. self.options.update(self.defaults)
  10076. # self.options_write_form()
  10077. class ArgsThread(QtCore.QObject):
  10078. open_signal = pyqtSignal(list)
  10079. start = pyqtSignal()
  10080. if sys.platform == 'win32':
  10081. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  10082. else:
  10083. address = ('/tmp/testipc', 'AF_UNIX')
  10084. def __init__(self):
  10085. super(ArgsThread, self).__init__()
  10086. self.start.connect(self.run)
  10087. def my_loop(self, address):
  10088. try:
  10089. listener = Listener(*address)
  10090. while True:
  10091. conn = listener.accept()
  10092. self.serve(conn)
  10093. except socket.error:
  10094. conn = Client(*address)
  10095. conn.send(sys.argv)
  10096. conn.send('close')
  10097. # close the current instance only if there are args
  10098. if len(sys.argv) > 1:
  10099. sys.exit()
  10100. def serve(self, conn):
  10101. while True:
  10102. msg = conn.recv()
  10103. if msg == 'close':
  10104. break
  10105. self.open_signal.emit(msg)
  10106. conn.close()
  10107. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10108. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10109. @pyqtSlot()
  10110. def run(self):
  10111. self.my_loop(self.address)
  10112. class GracefulException(Exception):
  10113. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  10114. def __init__(self):
  10115. super().__init__()
  10116. def __str__(self):
  10117. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  10118. # end of file