FlatCAMApp.py 535 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import tkinter as tk
  21. from PyQt5 import QtPrintSupport
  22. from contextlib import contextmanager
  23. import gc
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from multiprocessing.connection import Listener, Client
  26. from multiprocessing import Pool, cpu_count
  27. import socket
  28. from array import array
  29. # #######################################
  30. # # Imports part of FlatCAM ##
  31. # #######################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from flatcamGUI.PlotCanvas import *
  35. from flatcamGUI.PlotCanvasLegacy import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from flatcamEditors.FlatCAMTextEditor import TextEditor
  43. from FlatCAMProcess import *
  44. from FlatCAMWorkerStack import WorkerStack
  45. # from flatcamGUI.VisPyVisuals import Color
  46. from vispy.gloo.util import _screenshot
  47. from vispy.io import write_png
  48. from flatcamTools import *
  49. import tclCommands
  50. import gettext
  51. import FlatCAMTranslation as fcTranslate
  52. import builtins
  53. if sys.platform == 'win32':
  54. import winreg
  55. fcTranslate.apply_language('strings')
  56. if '_' not in builtins.__dict__:
  57. _ = gettext.gettext
  58. class App(QtCore.QObject):
  59. # ########################################
  60. # # App ###
  61. # ########################################
  62. """
  63. The main application class. The constructor starts the GUI.
  64. """
  65. # Get Cmd Line Options
  66. cmd_line_shellfile = ''
  67. cmd_line_shellvar = ''
  68. cmd_line_headless = None
  69. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  70. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  71. "FlatCam.py --headless=1"
  72. try:
  73. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  74. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  75. "shellvar=",
  76. "headless=",
  77. "multiprocessing-fork="])
  78. except getopt.GetoptError:
  79. print(cmd_line_help)
  80. sys.exit(2)
  81. for opt, arg in cmd_line_options:
  82. if opt == '-h':
  83. print(cmd_line_help)
  84. sys.exit()
  85. elif opt == '--shellfile':
  86. cmd_line_shellfile = arg
  87. elif opt == '--shellvar':
  88. cmd_line_shellvar = arg
  89. elif opt == '--headless':
  90. try:
  91. cmd_line_headless = eval(arg)
  92. except NameError:
  93. pass
  94. # ## Logging ###
  95. log = logging.getLogger('base')
  96. log.setLevel(logging.DEBUG)
  97. # log.setLevel(logging.WARNING)
  98. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  99. handler = logging.StreamHandler()
  100. handler.setFormatter(formatter)
  101. log.addHandler(handler)
  102. # ##########################################################################
  103. # ################## Version and VERSION DATE ##############################
  104. # ##########################################################################
  105. version = 8.98
  106. version_date = "2019/10/7"
  107. beta = True
  108. engine = '3D'
  109. # current date now
  110. date = str(datetime.today()).rpartition('.')[0]
  111. date = ''.join(c for c in date if c not in ':-')
  112. date = date.replace(' ', '_')
  113. # URL for update checks and statistics
  114. version_url = "http://flatcam.org/version"
  115. # App URL
  116. app_url = "http://flatcam.org"
  117. # Manual URL
  118. manual_url = "http://flatcam.org/manual/index.html"
  119. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  120. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  121. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  122. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  123. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  124. # this variable will hold the project status
  125. # if True it will mean that the project was modified and not saved
  126. should_we_save = False
  127. # flag is True if saving action has been triggered
  128. save_in_progress = False
  129. # ###########################################################################
  130. # ############################# Signals ################################
  131. # ###########################################################################
  132. # Inform the user
  133. # Handled by:
  134. # * App.info() --> Print on the status bar
  135. inform = QtCore.pyqtSignal(str)
  136. app_quit = QtCore.pyqtSignal()
  137. # General purpose background task
  138. worker_task = QtCore.pyqtSignal(dict)
  139. # File opened
  140. # Handled by:
  141. # * register_folder()
  142. # * register_recent()
  143. # Note: Setting the parameters to unicode does not seem
  144. # to have an effect. Then are received as Qstring
  145. # anyway.
  146. # File type and filename
  147. file_opened = QtCore.pyqtSignal(str, str)
  148. # File type and filename
  149. file_saved = QtCore.pyqtSignal(str, str)
  150. # Percentage of progress
  151. progress = QtCore.pyqtSignal(int)
  152. plots_updated = QtCore.pyqtSignal()
  153. # Emitted by new_object() and passes the new object as argument, plot flag.
  154. # on_object_created() adds the object to the collection, plots on appropriate flag
  155. # and emits new_object_available.
  156. object_created = QtCore.pyqtSignal(object, bool, bool)
  157. # Emitted when a object has been changed (like scaled, mirrored)
  158. object_changed = QtCore.pyqtSignal(object)
  159. # Emitted after object has been plotted.
  160. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  161. object_plotted = QtCore.pyqtSignal(object)
  162. # Emitted when a new object has been added or deleted from/to the collection
  163. object_status_changed = QtCore.pyqtSignal(object, str, str)
  164. message = QtCore.pyqtSignal(str, str, str)
  165. # Emmited when shell command is finished(one command only)
  166. shell_command_finished = QtCore.pyqtSignal(object)
  167. # Emitted when multiprocess pool has been recreated
  168. pool_recreated = QtCore.pyqtSignal(object)
  169. # Emitted when an unhandled exception happens
  170. # in the worker task.
  171. thread_exception = QtCore.pyqtSignal(object)
  172. # used to signal that there are arguments for the app
  173. args_at_startup = QtCore.pyqtSignal(list)
  174. # a reusable signal to replot a list of objects
  175. # should be disconnected after use so it can be reused
  176. replot_signal = pyqtSignal(list)
  177. def __init__(self, user_defaults=True, post_gui=None):
  178. """
  179. Starts the application.
  180. :return: app
  181. :rtype: App
  182. """
  183. App.log.info("FlatCAM Starting...")
  184. self.main_thread = QtWidgets.QApplication.instance().thread()
  185. # ############################################################################
  186. # # ################# OS-specific ############################################
  187. # ############################################################################
  188. portable = False
  189. # Folder for user settings.
  190. if sys.platform == 'win32':
  191. # #########################################################################
  192. # Setup the listening thread for another instance launching with args #####
  193. # #########################################################################
  194. # make sure the thread is stored by using a self. otherwise it's garbage collected
  195. self.th = QtCore.QThread()
  196. self.th.start(priority=QtCore.QThread.LowestPriority)
  197. self.new_launch = ArgsThread()
  198. self.new_launch.open_signal[list].connect(self.on_startup_args)
  199. self.new_launch.moveToThread(self.th)
  200. self.new_launch.start.emit()
  201. from win32com.shell import shell, shellcon
  202. if platform.architecture()[0] == '32bit':
  203. App.log.debug("Win32!")
  204. else:
  205. App.log.debug("Win64!")
  206. # #########################################################################
  207. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  208. # #########################################################################
  209. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  210. try:
  211. with open(config_file, 'r'):
  212. pass
  213. except FileNotFoundError:
  214. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  215. try:
  216. with open(config_file, 'r') as f:
  217. try:
  218. for line in f:
  219. param = str(line).replace('\n', '').rpartition('=')
  220. if param[0] == 'portable':
  221. try:
  222. portable = eval(param[2])
  223. except NameError:
  224. portable = False
  225. if param[0] == 'headless':
  226. if param[2].lower() == 'true':
  227. self.cmd_line_headless = 1
  228. else:
  229. self.cmd_line_headless = None
  230. except Exception as e:
  231. log.debug('App.__init__() -->%s' % str(e))
  232. return
  233. except FileNotFoundError as e:
  234. log.debug(str(e))
  235. pass
  236. if portable is False:
  237. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  238. else:
  239. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  240. self.os = 'windows'
  241. else: # Linux/Unix/MacOS
  242. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  243. self.os = 'unix'
  244. # ##########################################################################
  245. # ################## Setup folders and files ###############################
  246. # ##########################################################################
  247. if not os.path.exists(self.data_path):
  248. os.makedirs(self.data_path)
  249. App.log.debug('Created data folder: ' + self.data_path)
  250. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  251. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  252. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  253. if not os.path.exists(self.postprocessorpaths):
  254. os.makedirs(self.postprocessorpaths)
  255. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  256. # create current_defaults.FlatConfig file if there is none
  257. try:
  258. f = open(self.data_path + '/current_defaults.FlatConfig')
  259. f.close()
  260. except IOError:
  261. App.log.debug('Creating empty current_defaults.FlatConfig')
  262. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  263. json.dump({}, f)
  264. f.close()
  265. # create factory_defaults.FlatConfig file if there is none
  266. try:
  267. f = open(self.data_path + '/factory_defaults.FlatConfig')
  268. f.close()
  269. except IOError:
  270. App.log.debug('Creating empty factory_defaults.FlatConfig')
  271. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  272. json.dump({}, f)
  273. f.close()
  274. # create a recent files json file if there is none
  275. try:
  276. f = open(self.data_path + '/recent.json')
  277. f.close()
  278. except IOError:
  279. App.log.debug('Creating empty recent.json')
  280. f = open(self.data_path + '/recent.json', 'w')
  281. json.dump([], f)
  282. f.close()
  283. # create a recent projects json file if there is none
  284. try:
  285. fp = open(self.data_path + '/recent_projects.json')
  286. fp.close()
  287. except IOError:
  288. App.log.debug('Creating empty recent_projects.json')
  289. fp = open(self.data_path + '/recent_projects.json', 'w')
  290. json.dump([], fp)
  291. fp.close()
  292. # Application directory. CHDIR to it. Otherwise, trying to load
  293. # GUI icons will fail as their path is relative.
  294. # This will fail under cx_freeze ...
  295. self.app_home = os.path.dirname(os.path.realpath(__file__))
  296. App.log.debug("Application path is " + self.app_home)
  297. App.log.debug("Started in " + os.getcwd())
  298. # cx_freeze workaround
  299. if os.path.isfile(self.app_home):
  300. self.app_home = os.path.dirname(self.app_home)
  301. os.chdir(self.app_home)
  302. # #############################################################################
  303. # ##################### CREATE MULTIPROCESSING POOL ###########################
  304. # #############################################################################
  305. self.pool = Pool(processes=cpu_count())
  306. # ##########################################################################
  307. # ################## Setting the Splash Screen #############################
  308. # ##########################################################################
  309. settings = QSettings("Open Source", "FlatCAM")
  310. if settings.contains("splash_screen"):
  311. show_splash = settings.value("splash_screen")
  312. else:
  313. settings.setValue('splash_screen', 1)
  314. # This will write the setting to the platform specific storage.
  315. del settings
  316. show_splash = 1
  317. if show_splash and self.cmd_line_headless != 1:
  318. splash_pix = QtGui.QPixmap('share/splash.png')
  319. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  320. # self.splash.setMask(splash_pix.mask())
  321. # move splashscreen to the current monitor
  322. desktop = QtWidgets.QApplication.desktop()
  323. screen = desktop.screenNumber(QtGui.QCursor.pos())
  324. current_screen_center = desktop.availableGeometry(screen).center()
  325. self.splash.move(current_screen_center - self.splash.rect().center())
  326. self.splash.show()
  327. self.splash.showMessage(_("FlatCAM is initializing ..."),
  328. alignment=Qt.AlignBottom | Qt.AlignLeft,
  329. color=QtGui.QColor("gray"))
  330. else:
  331. show_splash = 0
  332. # #############################################################################
  333. # ##################### Initialize GUI ########################################
  334. # #############################################################################
  335. # FlatCAM colors used in plotting
  336. self.FC_light_green = '#BBF268BF'
  337. self.FC_dark_green = '#006E20BF'
  338. self.FC_light_blue = '#a5a5ffbf'
  339. self.FC_dark_blue = '#0000ffbf'
  340. QtCore.QObject.__init__(self)
  341. self.ui = FlatCAMGUI(self.version, self.beta, self)
  342. settings = QtCore.QSettings("Open Source", "FlatCAM")
  343. if settings.contains("theme"):
  344. theme = settings.value('theme', type=str)
  345. else:
  346. theme = 'white'
  347. if theme == 'white':
  348. self.cursor_color_3D = 'black'
  349. else:
  350. self.cursor_color_3D = 'gray'
  351. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  352. self.ui.final_save.connect(self.final_save)
  353. # #############################################################################
  354. # ############################## Data #########################################
  355. # #############################################################################
  356. self.recent = []
  357. self.recent_projects = []
  358. self.clipboard = QtWidgets.QApplication.clipboard()
  359. self.project_filename = None
  360. self.toggle_units_ignore = False
  361. # self.defaults_form = PreferencesUI()
  362. # when adding entries here read the comments in the method found bellow named:
  363. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  364. self.defaults_form_fields = {
  365. # General App
  366. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  367. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  368. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  369. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  370. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  371. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  372. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  373. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  374. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  375. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  376. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  377. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  378. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  379. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  380. # General GUI Preferences
  381. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  382. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  383. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  384. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  385. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  386. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  387. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  388. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  389. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  390. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  391. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  392. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  393. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  394. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  395. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  396. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  397. # General GUI Settings
  398. "global_theme": self.ui.general_defaults_form.general_gui_set_group.theme_radio,
  399. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  400. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  401. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  402. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  403. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  404. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  405. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  406. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  407. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  408. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  409. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  410. # Gerber General
  411. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  412. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  413. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  414. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  415. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  416. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  417. # Gerber Options
  418. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  419. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  420. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  421. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  422. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  423. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  424. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  425. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  426. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  427. # Gerber Advanced Options
  428. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  429. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  430. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  431. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  432. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  433. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  434. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  435. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  436. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  437. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  438. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  439. # Gerber Export
  440. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  441. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  442. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  443. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  444. # Gerber Editor
  445. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  446. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  447. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  448. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  449. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  450. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  451. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  452. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  453. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  454. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  455. "gerber_editor_circ_angle":
  456. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  457. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  458. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  459. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  460. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  461. # Excellon General
  462. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  463. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  464. "excellon_format_upper_in":
  465. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  466. "excellon_format_lower_in":
  467. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  468. "excellon_format_upper_mm":
  469. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  470. "excellon_format_lower_mm":
  471. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  472. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  473. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  474. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  475. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  476. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  477. # Excellon Options
  478. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  479. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  480. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  481. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  482. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  483. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  484. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  485. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  486. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  487. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  488. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  489. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  490. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  491. # Excellon Advanced Options
  492. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  493. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  494. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  495. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  496. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  497. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  498. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  499. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  500. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  501. # Excellon Export
  502. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  503. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  504. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  505. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  506. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  507. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  508. # Excellon Editor
  509. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  510. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  511. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  512. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  513. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  514. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  515. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  516. "excellon_editor_circ_angle":
  517. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  518. # Excellon Slots
  519. "excellon_editor_slot_direction":
  520. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  521. "excellon_editor_slot_angle":
  522. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  523. "excellon_editor_slot_length":
  524. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  525. # Excellon Slots
  526. "excellon_editor_slot_array_size":
  527. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  528. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  529. "excellon_editor_slot_lin_pitch":
  530. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  531. "excellon_editor_slot_lin_angle":
  532. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  533. "excellon_editor_slot_circ_dir":
  534. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  535. "excellon_editor_slot_circ_angle":
  536. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  537. # Geometry General
  538. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  539. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  540. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  541. # Geometry Options
  542. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  543. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  544. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  545. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  546. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  547. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  548. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  549. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  550. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  551. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  552. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  553. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  554. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  555. # Geometry Advanced Options
  556. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  557. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  558. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  559. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  560. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  561. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  562. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  563. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  564. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  565. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  566. # Geometry Editor
  567. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  568. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  569. # CNCJob General
  570. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  571. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  572. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  573. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  574. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  575. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  576. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  577. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  578. # CNC Job Options
  579. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  580. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  581. # CNC Job Advanced Options
  582. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  583. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  584. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  585. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  586. # NCC Tool
  587. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  588. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  589. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  590. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  591. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  592. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  593. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  594. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  595. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  596. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  597. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  598. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  599. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  600. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  601. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  602. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  603. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  604. # CutOut Tool
  605. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  606. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  607. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  608. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  609. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  610. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  611. # Paint Area Tool
  612. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  613. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  614. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  615. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  616. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  617. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  618. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  619. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  620. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  621. # 2-sided Tool
  622. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  623. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  624. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  625. # Film Tool
  626. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  627. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  628. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  629. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  630. # Panelize Tool
  631. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  632. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  633. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  634. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  635. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  636. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  637. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  638. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  639. # Calculators Tool
  640. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  641. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  642. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  643. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  644. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  645. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  646. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  647. # Transformations Tool
  648. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  649. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  650. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  651. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  652. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  653. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  654. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  655. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  656. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  657. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  658. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  659. # SolderPaste Dispensing Tool
  660. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  661. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  662. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  663. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  664. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  665. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  666. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  667. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  668. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  669. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  670. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  671. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  672. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  673. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  674. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  675. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  676. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  677. # Utilities
  678. # File associations
  679. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  680. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  681. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  682. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  683. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  684. }
  685. # ############################
  686. # ### LOAD POSTPROCESSORS ####
  687. # ############################
  688. self.postprocessors = load_postprocessors(self)
  689. for name in list(self.postprocessors.keys()):
  690. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  691. if name.partition('_')[0] == 'Paste':
  692. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  693. continue
  694. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  695. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  696. if name == 'hpgl':
  697. continue
  698. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  699. # ############################
  700. # ### LOAD LANGUAGES ####
  701. # ############################
  702. self.languages = fcTranslate.load_languages()
  703. for name in sorted(self.languages.values()):
  704. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  705. # #################################################################################
  706. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  707. # #################################################################################
  708. self.defaults = LoudDict()
  709. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  710. self.defaults.update({
  711. # Global APP Preferences
  712. "first_run": True,
  713. "units": "IN",
  714. "global_serial": 0,
  715. "global_stats": {},
  716. "global_tabs_detachable": True,
  717. "global_graphic_engine": '3D',
  718. "global_app_level": 'b',
  719. "global_portable": False,
  720. "global_language": 'English',
  721. "global_version_check": True,
  722. "global_send_stats": True,
  723. "global_pan_button": '2',
  724. "global_mselect_key": 'Control',
  725. "global_project_at_startup": False,
  726. "global_systray_icon": True,
  727. "global_project_autohide": True,
  728. "global_toggle_tooltips": True,
  729. "global_worker_number": 2,
  730. "global_tolerance": 0.0002,
  731. "global_open_style": True,
  732. "global_delete_confirmation": True,
  733. "global_compression_level": 3,
  734. "global_save_compressed": True,
  735. # Global GUI Preferences
  736. "global_gridx": 0.0393701,
  737. "global_gridy": 0.0393701,
  738. "global_snap_max": 0.001968504,
  739. "global_workspace": False,
  740. "global_workspaceT": "A4P",
  741. "global_grid_context_menu": {
  742. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  743. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  744. },
  745. "global_plot_fill": '#BBF268BF',
  746. "global_plot_line": '#006E20BF',
  747. "global_sel_fill": '#a5a5ffbf',
  748. "global_sel_line": '#0000ffbf',
  749. "global_alt_sel_fill": '#BBF268BF',
  750. "global_alt_sel_line": '#006E20BF',
  751. "global_draw_color": '#FF0000',
  752. "global_sel_draw_color": '#0000FF',
  753. "global_proj_item_color": '#000000',
  754. "global_proj_item_dis_color": '#b7b7cb',
  755. "global_activity_icon": 'Ball green',
  756. "global_toolbar_view": 511,
  757. "global_background_timeout": 300000, # Default value is 5 minutes
  758. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  759. # (python trace only for unknown errors),
  760. # 1 = show trace(show trace always),
  761. # 2 = (For the future).
  762. # Persistence
  763. "global_last_folder": None,
  764. "global_last_save_folder": None,
  765. # Default window geometry
  766. "global_def_win_x": 100,
  767. "global_def_win_y": 100,
  768. "global_def_win_w": 1024,
  769. "global_def_win_h": 650,
  770. "global_def_notebook_width": 1,
  771. # Constants...
  772. "global_defaults_save_period_ms": 20000, # Time between default saves.
  773. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  774. "global_shell_at_startup": False, # Show the shell at startup.
  775. "global_recent_limit": 10, # Max. items in recent list.
  776. "fit_key": 'V',
  777. "zoom_out_key": '-',
  778. "zoom_in_key": '=',
  779. "grid_toggle_key": 'G',
  780. "global_zoom_ratio": 1.5,
  781. "global_point_clipboard_format": "(%.4f, %.4f)",
  782. "global_zdownrate": None,
  783. # General GUI Settings
  784. "global_theme": 'white',
  785. "global_hover": False,
  786. "global_selection_shape": True,
  787. "global_layout": "compact",
  788. "global_cursor_type": "small",
  789. "global_cursor_size": 20,
  790. # Gerber General
  791. "gerber_plot": True,
  792. "gerber_solid": True,
  793. "gerber_multicolored": False,
  794. "gerber_circle_steps": 128,
  795. "gerber_use_buffer_for_union": True,
  796. "gerber_def_units": 'IN',
  797. "gerber_def_zeros": 'L',
  798. # Gerber Options
  799. "gerber_isotooldia": 0.00787402,
  800. "gerber_isopasses": 1,
  801. "gerber_isooverlap": 0.00393701,
  802. "gerber_milling_type": "cl",
  803. "gerber_combine_passes": False,
  804. "gerber_noncoppermargin": 0.00393701,
  805. "gerber_noncopperrounded": False,
  806. "gerber_bboxmargin": 0.00393701,
  807. "gerber_bboxrounded": False,
  808. # Gerber Advanced Options
  809. "gerber_aperture_display": False,
  810. "gerber_aperture_scale_factor": 1.0,
  811. "gerber_aperture_buffer_factor": 0.0,
  812. "gerber_follow": False,
  813. "gerber_tool_type": 'circular',
  814. "gerber_vtipdia": 0.1,
  815. "gerber_vtipangle": 30,
  816. "gerber_vcutz": -0.05,
  817. "gerber_buffering": "full",
  818. "gerber_simplification": False,
  819. "gerber_simp_tolerance": 0.0005,
  820. # Gerber Export
  821. "gerber_exp_units": 'IN',
  822. "gerber_exp_integer": 2,
  823. "gerber_exp_decimals": 4,
  824. "gerber_exp_zeros": 'L',
  825. # Gerber Editor
  826. "gerber_editor_sel_limit": 30,
  827. "gerber_editor_newcode": 10,
  828. "gerber_editor_newsize": 0.8,
  829. "gerber_editor_newtype": 'C',
  830. "gerber_editor_newdim": "0.5, 0.5",
  831. "gerber_editor_array_size": 5,
  832. "gerber_editor_lin_axis": 'X',
  833. "gerber_editor_lin_pitch": 1,
  834. "gerber_editor_lin_angle": 0.0,
  835. "gerber_editor_circ_dir": 'CW',
  836. "gerber_editor_circ_angle": 0.0,
  837. "gerber_editor_scale_f": 1.0,
  838. "gerber_editor_buff_f": 0.1,
  839. "gerber_editor_ma_low": 0.0,
  840. "gerber_editor_ma_high": 1.0,
  841. # Excellon General
  842. "excellon_plot": True,
  843. "excellon_solid": True,
  844. "excellon_format_upper_in": 2,
  845. "excellon_format_lower_in": 4,
  846. "excellon_format_upper_mm": 3,
  847. "excellon_format_lower_mm": 3,
  848. "excellon_zeros": "L",
  849. "excellon_units": "INCH",
  850. "excellon_update": True,
  851. "excellon_optimization_type": 'B',
  852. "excellon_search_time": 3,
  853. # Excellon Options
  854. "excellon_drillz": -0.0590551,
  855. "excellon_travelz": 0.0787402,
  856. "excellon_endz": 0.5,
  857. "excellon_feedrate": 3.14961,
  858. "excellon_spindlespeed": None,
  859. "excellon_dwell": False,
  860. "excellon_dwelltime": 1,
  861. "excellon_toolchange": False,
  862. "excellon_toolchangez": 0.5,
  863. "excellon_ppname_e": 'default',
  864. "excellon_tooldia": 0.0314961,
  865. "excellon_slot_tooldia": 0.0708661,
  866. "excellon_gcode_type": "drills",
  867. # Excellon Advanced Options
  868. "excellon_offset": 0.0,
  869. "excellon_toolchangexy": "0.0, 0.0",
  870. "excellon_startz": None,
  871. "excellon_feedrate_rapid": 31.4961,
  872. "excellon_z_pdepth": -0.02,
  873. "excellon_feedrate_probe": 3.14961,
  874. "excellon_spindledir": 'CW',
  875. "excellon_f_plunge": False,
  876. "excellon_f_retract": False,
  877. # Excellon Export
  878. "excellon_exp_units": 'INCH',
  879. "excellon_exp_format": 'ndec',
  880. "excellon_exp_integer": 2,
  881. "excellon_exp_decimals": 4,
  882. "excellon_exp_zeros": 'LZ',
  883. "excellon_exp_slot_type": 'routing',
  884. # Excellon Editor
  885. "excellon_editor_sel_limit": 30,
  886. "excellon_editor_newdia": 0.039,
  887. "excellon_editor_array_size": 5,
  888. "excellon_editor_lin_dir": 'X',
  889. "excellon_editor_lin_pitch": 0.1,
  890. "excellon_editor_lin_angle": 0.0,
  891. "excellon_editor_circ_dir": 'CW',
  892. "excellon_editor_circ_angle": 12,
  893. # Excellon Slots
  894. "excellon_editor_slot_direction": 'X',
  895. "excellon_editor_slot_angle": 0.0,
  896. "excellon_editor_slot_length": 5.0,
  897. # Excellon Slot Array
  898. "excellon_editor_slot_array_size": 5,
  899. "excellon_editor_slot_lin_dir": 'X',
  900. "excellon_editor_slot_lin_pitch": 0.1,
  901. "excellon_editor_slot_lin_angle": 0.0,
  902. "excellon_editor_slot_circ_dir": 'CW',
  903. "excellon_editor_slot_circ_angle": 0.0,
  904. # Geometry General
  905. "geometry_plot": True,
  906. "geometry_circle_steps": 128,
  907. "geometry_cnctooldia": "0.0944882",
  908. # Geometry Options
  909. "geometry_cutz": -0.0944882,
  910. "geometry_vtipdia": 0.1,
  911. "geometry_vtipangle": 30,
  912. "geometry_multidepth": False,
  913. "geometry_depthperpass": 0.0314961,
  914. "geometry_travelz": 0.0787402,
  915. "geometry_toolchange": False,
  916. "geometry_toolchangez": 0.5,
  917. "geometry_endz": 0.5,
  918. "geometry_feedrate": 3.14961,
  919. "geometry_feedrate_z": 3.14961,
  920. "geometry_spindlespeed": None,
  921. "geometry_dwell": False,
  922. "geometry_dwelltime": 1,
  923. "geometry_ppname_g": 'default',
  924. # Geometry Advanced Options
  925. "geometry_toolchangexy": "0.0, 0.0",
  926. "geometry_startz": None,
  927. "geometry_feedrate_rapid": 3.14961,
  928. "geometry_extracut": False,
  929. "geometry_z_pdepth": -0.02,
  930. "geometry_f_plunge": False,
  931. "geometry_spindledir": 'CW',
  932. "geometry_feedrate_probe": 3.14961,
  933. "geometry_segx": 0.0,
  934. "geometry_segy": 0.0,
  935. # Geometry Editor
  936. "geometry_editor_sel_limit": 30,
  937. "geometry_editor_milling_type": "cl",
  938. # CNC Job General
  939. "cncjob_plot": True,
  940. "cncjob_plot_kind": 'all',
  941. "cncjob_annotation": True,
  942. "cncjob_tooldia": 0.0393701,
  943. "cncjob_coords_type": "G90",
  944. "cncjob_coords_decimals": 4,
  945. "cncjob_fr_decimals": 2,
  946. "cncjob_steps_per_circle": 128,
  947. # CNC Job Options
  948. "cncjob_prepend": "",
  949. "cncjob_append": "",
  950. # CNC Job Advanced Options
  951. "cncjob_toolchange_macro": "",
  952. "cncjob_toolchange_macro_enable": False,
  953. "cncjob_annotation_fontsize": 9,
  954. "cncjob_annotation_fontcolor": '#990000',
  955. # NCC Tool
  956. "tools_ncctools": "0.0393701, 0.019685",
  957. "tools_nccorder": 'rev',
  958. "tools_nccoverlap": 0.015748,
  959. "tools_nccmargin": 0.0393701,
  960. "tools_nccmethod": "seed",
  961. "tools_nccconnect": True,
  962. "tools_ncccontour": True,
  963. "tools_nccrest": False,
  964. "tools_ncc_offset_choice": False,
  965. "tools_ncc_offset_value": 0.0000,
  966. "tools_nccref": 'itself',
  967. "tools_ncc_plotting": 'normal',
  968. "tools_nccmilling_type": 'cl',
  969. "tools_ncctool_type": 'V',
  970. "tools_ncccutz": -0.001968504,
  971. "tools_ncctipdia": 0.00393701,
  972. "tools_ncctipangle": 30,
  973. # Cutout Tool
  974. "tools_cutouttooldia": 0.0944882,
  975. "tools_cutoutkind": "single",
  976. "tools_cutoutmargin": 0.00393701,
  977. "tools_cutoutgapsize": 0.15748,
  978. "tools_gaps_ff": "4",
  979. "tools_cutout_convexshape": False,
  980. # Paint Tool
  981. "tools_painttooldia": 0.023622,
  982. "tools_paintorder": 'rev',
  983. "tools_paintoverlap": 0.015748,
  984. "tools_paintmargin": 0.0,
  985. "tools_paintmethod": "seed",
  986. "tools_selectmethod": "all",
  987. "tools_pathconnect": True,
  988. "tools_paintcontour": True,
  989. "tools_paint_plotting": 'normal',
  990. # 2-Sided Tool
  991. "tools_2sided_mirror_axis": "X",
  992. "tools_2sided_axis_loc": "point",
  993. "tools_2sided_drilldia": 0.11811,
  994. # Film Tool
  995. "tools_film_type": 'neg',
  996. "tools_film_boundary": 0.0393701,
  997. "tools_film_scale": 0,
  998. "tools_film_color": '#000000',
  999. # Panel Tool
  1000. "tools_panelize_spacing_columns": 0,
  1001. "tools_panelize_spacing_rows": 0,
  1002. "tools_panelize_columns": 1,
  1003. "tools_panelize_rows": 1,
  1004. "tools_panelize_constrain": False,
  1005. "tools_panelize_constrainx": 0.0,
  1006. "tools_panelize_constrainy": 0.0,
  1007. "tools_panelize_panel_type": 'gerber',
  1008. # Calculators Tool
  1009. "tools_calc_vshape_tip_dia": 0.007874,
  1010. "tools_calc_vshape_tip_angle": 30,
  1011. "tools_calc_vshape_cut_z": 0.000787,
  1012. "tools_calc_electro_length": 10.0,
  1013. "tools_calc_electro_width": 10.0,
  1014. "tools_calc_electro_cdensity": 13.0,
  1015. "tools_calc_electro_growth": 10.0,
  1016. # Transform Tool
  1017. "tools_transform_rotate": 90,
  1018. "tools_transform_skew_x": 0.0,
  1019. "tools_transform_skew_y": 0.0,
  1020. "tools_transform_scale_x": 1.0,
  1021. "tools_transform_scale_y": 1.0,
  1022. "tools_transform_scale_link": True,
  1023. "tools_transform_scale_reference": True,
  1024. "tools_transform_offset_x": 0.0,
  1025. "tools_transform_offset_y": 0.0,
  1026. "tools_transform_mirror_reference": False,
  1027. "tools_transform_mirror_point": (0, 0),
  1028. # SolderPaste Tool
  1029. "tools_solderpaste_tools": "0.0393701, 0.011811",
  1030. "tools_solderpaste_new": 0.011811,
  1031. "tools_solderpaste_z_start": 0.00019685039,
  1032. "tools_solderpaste_z_dispense": 0.00393701,
  1033. "tools_solderpaste_z_stop": 0.00019685039,
  1034. "tools_solderpaste_z_travel": 0.00393701,
  1035. "tools_solderpaste_z_toolchange": 0.0393701,
  1036. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  1037. "tools_solderpaste_frxy": 3.0,
  1038. "tools_solderpaste_frz": 3.0,
  1039. "tools_solderpaste_frz_dispense": 0.0393701,
  1040. "tools_solderpaste_speedfwd": 20,
  1041. "tools_solderpaste_dwellfwd": 1,
  1042. "tools_solderpaste_speedrev": 10,
  1043. "tools_solderpaste_dwellrev": 1,
  1044. "tools_solderpaste_pp": 'Paste_1',
  1045. # Subtract Tool
  1046. "tools_sub_close_paths": True,
  1047. # Utilities
  1048. # file associations
  1049. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  1050. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  1051. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  1052. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  1053. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  1054. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  1055. # Keyword list
  1056. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  1057. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  1058. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  1059. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  1060. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1061. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1062. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1063. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1064. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1065. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1066. 'toolchange_xy, use_threads, value, x, x0, x1, y, y0, y1, z_cut, z_move',
  1067. "script_autocompleter": True,
  1068. "script_text": "",
  1069. "script_plot": True,
  1070. "script_source_file": "",
  1071. "document_autocompleter": False,
  1072. "document_text": "",
  1073. "document_plot": True,
  1074. "document_source_file": "",
  1075. "document_font_color": '#000000',
  1076. "document_sel_color": '#0055ff',
  1077. "document_font_size": 6,
  1078. "document_tab_size": 80,
  1079. })
  1080. # ############################################################
  1081. # ############### Load defaults from file ####################
  1082. # ############################################################
  1083. if user_defaults:
  1084. self.load_defaults(filename='current_defaults')
  1085. # #############################################################
  1086. # ############## APPLY APP LANGUAGE ###########################
  1087. # #############################################################
  1088. ret_val = fcTranslate.apply_language('strings')
  1089. if ret_val == "no language":
  1090. self.inform.emit('[ERROR] %s' %
  1091. _("Could not find the Language files. The App strings are missing."))
  1092. log.debug("Could not find the Language files. The App strings are missing.")
  1093. else:
  1094. # make the current language the current selection on the language combobox
  1095. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1096. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1097. # ##############################################################
  1098. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1099. # ##############################################################
  1100. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1101. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1102. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1103. self.save_defaults(silent=True, first_time=True)
  1104. self.propagate_defaults(silent=True)
  1105. self.restore_main_win_geom()
  1106. # def auto_save_defaults():
  1107. # try:
  1108. # self.save_defaults(silent=True)
  1109. # self.propagate_defaults(silent=True)
  1110. # finally:
  1111. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1112. # the following lines activates automatic defaults save
  1113. # if user_defaults:
  1114. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1115. # self.options_form = PreferencesUI()
  1116. self.options_form_fields = {
  1117. "units": self.ui.general_options_form.general_app_group.units_radio,
  1118. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1119. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1120. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1121. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1122. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1123. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1124. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1125. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1126. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1127. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1128. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1129. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1130. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1131. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1132. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1133. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1134. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1135. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1136. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1137. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1138. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1139. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1140. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1141. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1142. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1143. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1144. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1145. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1146. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1147. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1148. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1149. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1150. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1151. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1152. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1153. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1154. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1155. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1156. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1157. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1158. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1159. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1160. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1161. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1162. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1163. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1164. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1165. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1166. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1167. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1168. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1169. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1170. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1171. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1172. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1173. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1174. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1175. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1176. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1177. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1178. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1179. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1180. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1181. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1182. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1183. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1184. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1185. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1186. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1187. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1188. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1189. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1190. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1191. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1192. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1193. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1194. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1195. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1196. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1197. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1198. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1199. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1200. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1201. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1202. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1203. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1204. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1205. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1206. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1207. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1208. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1209. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1210. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1211. }
  1212. for name in list(self.postprocessors.keys()):
  1213. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1214. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1215. self.options = LoudDict()
  1216. self.options.set_change_callback(self.on_options_dict_change)
  1217. self.options.update({
  1218. "units": "IN",
  1219. "global_gridx": 1.0,
  1220. "global_gridy": 1.0,
  1221. "global_snap_max": 0.05,
  1222. "global_background_timeout": 300000, # Default value is 5 minutes
  1223. "global_verbose_error_level": 0, # Shell verbosity:
  1224. # 0 = default(python trace only for unknown errors),
  1225. # 1 = show trace(show trace allways), 2 = (For the future).
  1226. "gerber_plot": True,
  1227. "gerber_solid": True,
  1228. "gerber_multicolored": False,
  1229. "gerber_isotooldia": 0.016,
  1230. "gerber_isopasses": 1,
  1231. "gerber_isooverlap": 0.15,
  1232. "gerber_combine_passes": True,
  1233. "gerber_noncoppermargin": 0.0,
  1234. "gerber_noncopperrounded": False,
  1235. "gerber_bboxmargin": 0.0,
  1236. "gerber_bboxrounded": False,
  1237. "excellon_plot": True,
  1238. "excellon_solid": False,
  1239. "excellon_format_upper_in": 2,
  1240. "excellon_format_lower_in": 4,
  1241. "excellon_format_upper_mm": 3,
  1242. "excellon_format_lower_mm": 3,
  1243. "excellon_units": 'INCH',
  1244. "excellon_optimization_type": 'B',
  1245. "excellon_search_time": 3,
  1246. "excellon_zeros": "L",
  1247. "excellon_drillz": -0.1,
  1248. "excellon_travelz": 0.1,
  1249. "excellon_feedrate": 3.0,
  1250. "excellon_feedrate_rapid": 3.0,
  1251. "excellon_spindlespeed": None,
  1252. "excellon_spindledir": 'CW',
  1253. "excellon_dwell": True,
  1254. "excellon_dwelltime": 1000,
  1255. "excellon_toolchange": False,
  1256. "excellon_toolchangez": 1.0,
  1257. "excellon_toolchangexy": "0.0, 0.0",
  1258. "excellon_tooldia": 0.016,
  1259. "excellon_ppname_e": 'default',
  1260. "excellon_f_plunge": False,
  1261. "excellon_startz": None,
  1262. "excellon_endz": 2.0,
  1263. "geometry_plot": True,
  1264. "geometry_segx": 0.0,
  1265. "geometry_segy": 0.0,
  1266. "geometry_cutz": -0.002,
  1267. "geometry_vtipdia": 0.1,
  1268. "geometry_vtipangle": 30,
  1269. "geometry_travelz": 0.1,
  1270. "geometry_feedrate": 3.0,
  1271. "geometry_feedrate_z": 3.0,
  1272. "geometry_feedrate_rapid": 3.0,
  1273. "geometry_spindlespeed": None,
  1274. "geometry_spindledir": 'CW',
  1275. "geometry_dwell": True,
  1276. "geometry_dwelltime": 1000,
  1277. "geometry_cnctooldia": 0.016,
  1278. "geometry_toolchange": False,
  1279. "geometry_toolchangez": 2.0,
  1280. "geometry_toolchangexy": "0.0, 0.0",
  1281. "geometry_startz": None,
  1282. "geometry_endz": 2.0,
  1283. "geometry_ppname_g": "default",
  1284. "geometry_f_plunge": False,
  1285. "geometry_depthperpass": 0.002,
  1286. "geometry_multidepth": False,
  1287. "geometry_extracut": False,
  1288. "cncjob_plot": True,
  1289. "cncjob_tooldia": 0.016,
  1290. "cncjob_prepend": "",
  1291. "cncjob_append": "",
  1292. "tools_ncctools": "1.0, 0.5",
  1293. "tools_nccoverlap": 0.4,
  1294. "tools_nccmargin": 1,
  1295. "tools_cutouttooldia": 0.07,
  1296. "tools_cutoutmargin": 0.1,
  1297. "tools_cutoutgapsize": 0.15,
  1298. "tools_gaps_ff": "8",
  1299. "tools_painttooldia": 0.07,
  1300. "tools_paintoverlap": 0.15,
  1301. "tools_paintmargin": 0.0,
  1302. "tools_paintmethod": "seed",
  1303. "tools_selectmethod": "single",
  1304. "tools_pathconnect": True,
  1305. "tools_paintcontour": True,
  1306. "tools_2sided_mirror_axis": "X",
  1307. "tools_2sided_axis_loc": 'point',
  1308. "tools_2sided_drilldia": 1,
  1309. "tools_film_type": 'neg',
  1310. "tools_film_boundary": 1,
  1311. "tools_film_scale": 0,
  1312. "tools_panelize_spacing_columns": 0,
  1313. "tools_panelize_spacing_rows": 0,
  1314. "tools_panelize_columns": 1,
  1315. "tools_panelize_rows": 1,
  1316. "tools_panelize_constrain": False,
  1317. "tools_panelize_constrainx": 0.0,
  1318. "tools_panelize_constrainy": 0.0,
  1319. "script_text": "",
  1320. "script_plot": False,
  1321. "script_source_file": "",
  1322. "document_text": "",
  1323. "document_plot": False,
  1324. "document_source_file": "",
  1325. })
  1326. self.options.update(self.defaults) # Copy app defaults to project options
  1327. self.gen_form = None
  1328. self.ger_form = None
  1329. self.exc_form = None
  1330. self.geo_form = None
  1331. self.cnc_form = None
  1332. self.tools_form = None
  1333. self.fa_form = None
  1334. self.on_options_combo_change(0) # Will show the initial form
  1335. # ################################
  1336. # ### Initialize the color box's color in Preferences -> Global -> Color
  1337. # Init Plot Colors
  1338. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1339. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1340. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1341. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1342. int(self.defaults['global_plot_fill'][7:9], 16))
  1343. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1344. int(self.defaults['global_plot_fill'][7:9], 16))
  1345. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1346. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1347. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1348. # Init Left-Right Selection colors
  1349. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1350. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1351. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1352. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1353. int(self.defaults['global_sel_fill'][7:9], 16))
  1354. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1355. int(self.defaults['global_sel_fill'][7:9], 16))
  1356. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1357. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1358. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1359. # Init Right-Left Selection colors
  1360. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1361. self.defaults['global_alt_sel_fill'])
  1362. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1363. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1364. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1365. int(self.defaults['global_sel_fill'][7:9], 16))
  1366. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1367. int(self.defaults['global_sel_fill'][7:9], 16))
  1368. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1369. self.defaults['global_alt_sel_line'])
  1370. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1371. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1372. # Init Draw color and Selection Draw Color
  1373. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1374. self.defaults['global_draw_color'])
  1375. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1376. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1377. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1378. self.defaults['global_sel_draw_color'])
  1379. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1380. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1381. # Init Project Items color
  1382. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1383. self.defaults['global_proj_item_color'])
  1384. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1385. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1386. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1387. self.defaults['global_proj_item_dis_color'])
  1388. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1389. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1390. # Init the Annotation CNC Job color
  1391. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1392. self.defaults['cncjob_annotation_fontcolor'])
  1393. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1394. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1395. # Init the Tool Film color
  1396. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1397. self.defaults['tools_film_color'])
  1398. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1399. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1400. # ### End of Data ####
  1401. # ##############################################
  1402. # ######### SETUP OBJECT COLLECTION ############
  1403. # ##############################################
  1404. self.collection = ObjectCollection(self)
  1405. self.ui.project_tab_layout.addWidget(self.collection.view)
  1406. # ### Adjust tabs width ## ##
  1407. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1408. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1409. self.collection.view.setMinimumWidth(290)
  1410. self.log.debug("Finished creating Object Collection.")
  1411. # ###############################################
  1412. # ############# SETUP Plot Area #################
  1413. # ###############################################
  1414. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1415. if self.defaults["global_graphic_engine"] == '3D':
  1416. self.is_legacy = False
  1417. else:
  1418. self.is_legacy = True
  1419. # Matplotlib axis
  1420. self.axes = None
  1421. if show_splash:
  1422. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1423. "Canvas initialization started."),
  1424. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1425. color=QtGui.QColor("gray"))
  1426. start_plot_time = time.time() # debug
  1427. self.plotcanvas = None
  1428. self.app_cursor = None
  1429. self.hover_shapes = None
  1430. self.on_plotcanvas_setup()
  1431. end_plot_time = time.time()
  1432. self.used_time = end_plot_time - start_plot_time
  1433. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1434. if show_splash:
  1435. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1436. "Canvas initialization started.\n"
  1437. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1438. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1439. color=QtGui.QColor("gray"))
  1440. self.ui.splitter.setStretchFactor(1, 2)
  1441. # #################################################################
  1442. # ####################### SYS TRAY ################################
  1443. # #################################################################
  1444. if self.defaults["global_systray_icon"]:
  1445. self.parent_w = QtWidgets.QWidget()
  1446. if self.cmd_line_headless == 1:
  1447. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1448. headless=True,
  1449. parent=self.parent_w)
  1450. else:
  1451. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1452. parent=self.parent_w)
  1453. # ###############################################
  1454. # ############# Worker SETUP ####################
  1455. # ###############################################
  1456. if self.defaults["global_worker_number"]:
  1457. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1458. else:
  1459. self.workers = WorkerStack(workers_number=2)
  1460. self.worker_task.connect(self.workers.add_task)
  1461. self.log.debug("Finished creating Workers crew.")
  1462. # ################################################
  1463. # ############### Activity Monitor ###############
  1464. # ################################################
  1465. if self.defaults["global_activity_icon"] == "Ball green":
  1466. icon = 'share/active_2_static.png'
  1467. movie = "share/active_2.gif"
  1468. elif self.defaults["global_activity_icon"] == "Ball black":
  1469. icon = 'share/active_static.png'
  1470. movie = "share/active.gif"
  1471. elif self.defaults["global_activity_icon"] == "Arrow green":
  1472. icon = 'share/active_3_static.png'
  1473. movie = "share/active_3.gif"
  1474. elif self.defaults["global_activity_icon"] == "Eclipse green":
  1475. icon = 'share/active_4_static.png'
  1476. movie = "share/active_4.gif"
  1477. else:
  1478. icon = 'share/active_static.png'
  1479. movie = "share/active.gif"
  1480. self.activity_view = FlatCAMActivityView(icon=icon, movie=movie)
  1481. self.ui.infobar.addWidget(self.activity_view)
  1482. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1483. # ################################################
  1484. # ############### Signal handling ################
  1485. # ################################################
  1486. # ############# Custom signals ##################
  1487. # signal for displaying messages in status bar
  1488. self.inform.connect(self.info)
  1489. # signal to be called when the app is quiting
  1490. self.app_quit.connect(self.quit_application)
  1491. self.message.connect(self.message_dialog)
  1492. self.progress.connect(self.set_progress_bar)
  1493. # signals that are emitted when object state changes
  1494. self.object_created.connect(self.on_object_created)
  1495. self.object_changed.connect(self.on_object_changed)
  1496. self.object_plotted.connect(self.on_object_plotted)
  1497. self.plots_updated.connect(self.on_plots_updated)
  1498. # signals emitted when file state change
  1499. self.file_opened.connect(self.register_recent)
  1500. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1501. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1502. # ############# Standard signals ###################
  1503. # ### Menu
  1504. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1505. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1506. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1507. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1508. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1509. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1510. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1511. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1512. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1513. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1514. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1515. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1516. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1517. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1518. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1519. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1520. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1521. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1522. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1523. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1524. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1525. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1526. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1527. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1528. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1529. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1530. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1531. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1532. self.ui.menufile_exit.triggered.connect(self.final_save)
  1533. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1534. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1535. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1536. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1537. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1538. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1539. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1540. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1541. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1542. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1543. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1544. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1545. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1546. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1547. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1548. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1549. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1550. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1551. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1552. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1553. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1554. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1555. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1556. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1557. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1558. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1559. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1560. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1561. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1562. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1563. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1564. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1565. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1566. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1567. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1568. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1569. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1570. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1571. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1572. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1573. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1574. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1575. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1576. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1577. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1578. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1579. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1580. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1581. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1582. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1583. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1584. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1585. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1586. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1587. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1588. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1589. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1590. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1591. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1592. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1593. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1594. # ToolBar signals
  1595. self.connect_toolbar_signals()
  1596. # Notebook signals
  1597. # make the right click on the notebook tab connect to a function
  1598. self.ui.notebook.setupContextMenu()
  1599. self.ui.notebook.addContextMenu(
  1600. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1601. initial_checked=self.defaults["global_tabs_detachable"])
  1602. # activate initial state
  1603. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1604. # Context Menu
  1605. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1606. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1607. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1608. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1609. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1610. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1611. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1612. self.ui.clearplot.triggered.connect(self.clear_plots)
  1613. self.ui.replot.triggered.connect(self.plot_all)
  1614. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1615. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1616. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1617. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1618. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1619. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1620. # Preferences Plot Area TAB
  1621. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1622. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1623. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1624. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1625. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1626. # ##############################
  1627. # ### GUI PREFERENCES SIGNALS ##
  1628. # ##############################
  1629. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1630. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1631. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1632. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1633. )
  1634. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1635. lambda: self.on_toggle_units(no_pref=False))
  1636. # ###############################################################
  1637. # ################### GUI COLORS SIGNALS ########################
  1638. # ###############################################################
  1639. # Setting plot colors signals
  1640. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1641. self.on_pf_color_entry)
  1642. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1643. self.on_pf_color_button)
  1644. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1645. self.on_pf_color_spinner)
  1646. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1647. self.on_pf_color_slider)
  1648. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1649. self.on_pl_color_entry)
  1650. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1651. self.on_pl_color_button)
  1652. # Setting selection (left - right) colors signals
  1653. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1654. self.on_sf_color_entry)
  1655. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1656. self.on_sf_color_button)
  1657. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1658. self.on_sf_color_spinner)
  1659. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1660. self.on_sf_color_slider)
  1661. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1662. self.on_sl_color_entry)
  1663. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1664. self.on_sl_color_button)
  1665. # Setting selection (right - left) colors signals
  1666. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1667. self.on_alt_sf_color_entry)
  1668. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1669. self.on_alt_sf_color_button)
  1670. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1671. self.on_alt_sf_color_spinner)
  1672. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1673. self.on_alt_sf_color_slider)
  1674. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1675. self.on_alt_sl_color_entry)
  1676. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1677. self.on_alt_sl_color_button)
  1678. # Setting Editor Draw colors signals
  1679. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1680. self.on_draw_color_entry)
  1681. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1682. self.on_draw_color_button)
  1683. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1684. self.on_sel_draw_color_entry)
  1685. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1686. self.on_sel_draw_color_button)
  1687. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1688. self.on_proj_color_entry)
  1689. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1690. self.on_proj_color_button)
  1691. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1692. self.on_proj_color_dis_entry)
  1693. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1694. self.on_proj_color_dis_button)
  1695. # ########## workspace setting signals ###########
  1696. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1697. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1698. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1699. # #################################################
  1700. # ############ GUI SETTINGS SIGNALS ###############
  1701. # #################################################
  1702. self.ui.general_defaults_form.general_gui_set_group.theme_radio.activated_custom.connect(self.on_theme_change)
  1703. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1704. # ########## CNC Job related signals #############
  1705. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1706. self.on_cnc_custom_parameters)
  1707. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1708. self.on_annotation_fontcolor_entry)
  1709. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1710. self.on_annotation_fontcolor_button)
  1711. # ########## Tools related signals #############
  1712. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1713. self.on_film_color_entry)
  1714. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1715. self.on_film_color_button)
  1716. # portability changed signal
  1717. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1718. # Object list
  1719. self.collection.view.activated.connect(self.on_row_activated)
  1720. self.object_status_changed.connect(self.on_collection_updated)
  1721. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1722. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1723. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1724. # Export Excellon parameters.
  1725. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1726. self.on_update_exc_export
  1727. )
  1728. # call it once to make sure it is updated at startup
  1729. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1730. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1731. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1732. self.on_excellon_defaults_button)
  1733. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1734. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1735. self.on_excellon_options_button)
  1736. # when there are arguments at application startup this get launched
  1737. self.args_at_startup[list].connect(self.on_startup_args)
  1738. # ##############################################################
  1739. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1740. # ##############################################################
  1741. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1742. lambda: self.restore_extensions(ext_type='excellon'))
  1743. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1744. lambda: self.restore_extensions(ext_type='gcode'))
  1745. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1746. lambda: self.restore_extensions(ext_type='gerber'))
  1747. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1748. lambda: self.delete_all_extensions(ext_type='excellon'))
  1749. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1750. lambda: self.delete_all_extensions(ext_type='gcode'))
  1751. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1752. lambda: self.delete_all_extensions(ext_type='gerber'))
  1753. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1754. lambda: self.add_extension(ext_type='excellon'))
  1755. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1756. lambda: self.add_extension(ext_type='gcode'))
  1757. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1758. lambda: self.add_extension(ext_type='gerber'))
  1759. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1760. lambda: self.del_extension(ext_type='excellon'))
  1761. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1762. lambda: self.del_extension(ext_type='gcode'))
  1763. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1764. lambda: self.del_extension(ext_type='gerber'))
  1765. # connect the 'Apply' buttons from the Preferences/File Associations
  1766. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1767. lambda: self.on_register_files(obj_type='excellon'))
  1768. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1769. lambda: self.on_register_files(obj_type='gcode'))
  1770. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1771. lambda: self.on_register_files(obj_type='gerber'))
  1772. # ##############################################################
  1773. # ###################### KEYWORDS SIGNALS ######################
  1774. # ##############################################################
  1775. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1776. lambda: self.restore_extensions(ext_type='keyword'))
  1777. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1778. lambda: self.delete_all_extensions(ext_type='keyword'))
  1779. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1780. lambda: self.add_extension(ext_type='keyword'))
  1781. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1782. lambda: self.del_extension(ext_type='keyword'))
  1783. # splash screen button signal
  1784. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1785. # connect the abort_all_tasks related slots to the related signals
  1786. self.proc_container.idle_flag.connect(self.app_is_idle)
  1787. # signal emitted when a tab is closed in the Plot Area
  1788. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1789. # #####################################################################################
  1790. # ########### FINISHED CONNECTING SIGNALS #############################################
  1791. # #####################################################################################
  1792. self.log.debug("Finished connecting Signals.")
  1793. # #####################################################################################
  1794. # ########################## Other setups #############################################
  1795. # #####################################################################################
  1796. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1797. # depending on from where those tools are called different actions can be done
  1798. self.call_source = 'app'
  1799. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1800. self.tool_tab_locked = False
  1801. # decide if to show or hide the Notebook side of the screen at startup
  1802. if self.defaults["global_project_at_startup"] is True:
  1803. self.ui.splitter.setSizes([1, 1])
  1804. else:
  1805. self.ui.splitter.setSizes([0, 1])
  1806. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1807. self.setup_obj_classes()
  1808. self.setup_recent_items()
  1809. self.setup_component_editor()
  1810. # this does not work in Legacy Mode
  1811. if self.is_legacy is True:
  1812. self.ui.general_defaults_form.general_gui_group.workspace_cb.setDisabled(True)
  1813. self.ui.general_defaults_form.general_gui_group.workspace_type_lbl.setDisabled(True)
  1814. self.ui.general_defaults_form.general_gui_group.wk_cb.setDisabled(True)
  1815. # #####################################################################################
  1816. # ######################### Auto-complete KEYWORDS ####################################
  1817. # #####################################################################################
  1818. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1819. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1820. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1821. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1822. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1823. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1824. 'mirror', 'ncc',
  1825. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1826. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1827. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1828. 'save', 'save_project',
  1829. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1830. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1831. 'version', 'write_gcode'
  1832. ]
  1833. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1834. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1835. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1836. 'axisoffset',
  1837. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1838. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1839. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1840. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1841. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1842. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1843. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1844. 'spacing_columns',
  1845. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'use_threads', 'value', 'x',
  1846. 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1847. ]
  1848. self.tcl_keywords = [
  1849. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1850. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1851. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1852. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1853. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1854. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1855. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1856. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1857. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1858. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1859. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1860. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1861. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1862. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1863. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1864. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1865. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1866. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1867. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1868. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1869. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1870. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1871. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1872. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1873. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1874. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1875. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1876. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1877. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1878. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1879. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1880. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1881. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1882. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1883. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1884. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1885. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1886. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1887. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1888. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1889. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1890. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1891. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1892. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1893. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1894. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1895. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1896. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1897. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1898. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1899. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1900. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1901. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1902. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1903. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1904. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1905. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1906. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1907. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1908. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1909. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1910. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1911. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1912. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1913. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1914. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1915. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1916. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1917. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1918. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1919. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1920. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1921. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1922. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1923. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1924. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1925. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1926. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1927. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1928. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1929. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1930. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1931. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1932. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1933. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1934. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1935. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1936. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1937. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1938. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1939. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1940. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1941. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1942. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1943. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1944. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1945. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1946. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1947. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1948. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1949. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1950. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1951. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1952. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1953. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1954. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1955. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1956. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1957. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1958. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1959. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1960. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1961. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1962. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1963. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1964. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1965. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1966. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1967. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1968. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1969. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1970. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1971. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1972. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1973. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1974. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1975. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1976. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1977. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1978. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1979. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1980. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1981. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1982. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1983. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1984. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1985. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1986. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1987. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1988. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1989. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1990. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1991. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1992. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1993. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1994. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1995. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1996. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1997. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1998. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1999. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  2000. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  2001. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  2002. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  2003. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  2004. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  2005. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  2006. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  2007. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  2008. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  2009. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  2010. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  2011. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  2012. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  2013. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  2014. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2015. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2016. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2017. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2018. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2019. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2020. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2021. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2022. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2023. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2024. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2025. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2026. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2027. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2028. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2029. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2030. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2031. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2032. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2033. ]
  2034. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2035. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2036. # ####################################################################################
  2037. # ####################### Shell SETUP ################################################
  2038. # ####################################################################################
  2039. self.shell = FCShell(self, version=self.version)
  2040. self.shell._edit.set_model_data(self.myKeywords)
  2041. self.shell.setWindowIcon(self.ui.app_icon)
  2042. self.shell.setWindowTitle("FlatCAM Shell")
  2043. self.shell.resize(*self.defaults["global_shell_shape"])
  2044. self.shell.append_output("FlatCAM %s - " % self.version)
  2045. self.shell.append_output(_("Type >help< to get started\n\n"))
  2046. self.init_tcl()
  2047. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2048. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2049. self.ui.shell_dock.setWidget(self.shell)
  2050. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2051. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2052. QtWidgets.QDockWidget.DockWidgetFloatable |
  2053. QtWidgets.QDockWidget.DockWidgetClosable)
  2054. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2055. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2056. if self.defaults["global_shell_at_startup"]:
  2057. self.ui.shell_dock.show()
  2058. else:
  2059. self.ui.shell_dock.hide()
  2060. # ##################################################################################
  2061. # ###################### Tools and Plugins #########################################
  2062. # ##################################################################################
  2063. self.dblsidedtool = None
  2064. self.distance_tool = None
  2065. self.distance_min_tool = None
  2066. self.panelize_tool = None
  2067. self.film_tool = None
  2068. self.paste_tool = None
  2069. self.calculator_tool = None
  2070. self.rules_tool = None
  2071. self.sub_tool = None
  2072. self.move_tool = None
  2073. self.cutout_tool = None
  2074. self.ncclear_tool = None
  2075. self.optimal_tool=None
  2076. self.paint_tool = None
  2077. self.transform_tool = None
  2078. self.properties_tool = None
  2079. self.pdf_tool = None
  2080. self.image_tool = None
  2081. self.pcb_wizard_tool = None
  2082. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2083. self.install_tools()
  2084. # ### System Font Parsing ###
  2085. # self.f_parse = ParseFont(self)
  2086. # self.parse_system_fonts()
  2087. # #####################################################################################
  2088. # ######################## Check for updates ##########################################
  2089. # #####################################################################################
  2090. # Separate thread (Not worker)
  2091. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2092. if (self.beta is False or self.beta is None) and \
  2093. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  2094. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2095. self.thr2 = QtCore.QThread()
  2096. self.worker_task.emit({'fcn': self.version_check,
  2097. 'params': []})
  2098. self.thr2.start(QtCore.QThread.LowPriority)
  2099. # #####################################################################################
  2100. # ######################### Register files with FlatCAM; #############################
  2101. # ######################### It works only for Windows for now ########################
  2102. # #####################################################################################
  2103. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2104. self.on_register_files()
  2105. # #####################################################################################
  2106. # ###################### Variables for global usage ###################################
  2107. # #####################################################################################
  2108. # coordinates for relative position display
  2109. self.rel_point1 = (0, 0)
  2110. self.rel_point2 = (0, 0)
  2111. # variable to store coordinates
  2112. self.pos = (0, 0)
  2113. self.pos_jump = (0, 0)
  2114. # variable to store mouse coordinates
  2115. self.mouse = [0, 0]
  2116. # decide if we have a double click or single click
  2117. self.doubleclick = False
  2118. # variable to store if a command is active (then the var is not None) and which one it is
  2119. self.command_active = None
  2120. # variable to store the status of moving selection action
  2121. # None value means that it's not an selection action
  2122. # True value = a selection from left to right
  2123. # False value = a selection from right to left
  2124. self.selection_type = None
  2125. # List to store the objects that are currently loaded in FlatCAM
  2126. # This list is updated on each object creation or object delete
  2127. self.all_objects_list = list()
  2128. # List to store the objects that are selected
  2129. self.sel_objects_list = list()
  2130. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2131. self.key_modifiers = None
  2132. # Variable to hold the status of the axis
  2133. self.toggle_axis = True
  2134. # Variable to store the status of the fullscreen event
  2135. self.toggle_fscreen = False
  2136. # Variable to store the status of the code editor
  2137. self.toggle_codeeditor = False
  2138. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2139. self.click_noproject = False
  2140. self.cursor = None
  2141. # Variable to store the GCODE that was edited
  2142. self.gcode_edited = ""
  2143. self.text_editor_tab = None
  2144. # reference for the self.ui.code_editor
  2145. self.reference_code_editor = None
  2146. self.script_code = ''
  2147. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2148. self.preferences_changed_flag = False
  2149. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2150. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2151. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2152. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2153. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2154. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2155. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2156. 'tap', 'xpi']
  2157. self.svg_list = ['svg']
  2158. self.dxf_list = ['dxf']
  2159. self.pdf_list = ['pdf']
  2160. self.prj_list = ['flatprj']
  2161. self.conf_list = ['flatconfig']
  2162. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2163. # flag for polygons not cleared
  2164. self.poly_not_cleared = False
  2165. # VisPy visuals
  2166. self.isHovering = False
  2167. self.notHovering = True
  2168. # Window geometry
  2169. self.x_pos = None
  2170. self.y_pos = None
  2171. self.width = None
  2172. self.height = None
  2173. # Event signals disconnect id holders
  2174. self.mp = None
  2175. self.mm = None
  2176. self.mr = None
  2177. self.mp_zc = None
  2178. # when True, the app has to return from any thread
  2179. self.abort_flag = False
  2180. # set the value used in the Windows Title
  2181. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2182. # ###############################################################################
  2183. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2184. # ############# It's done only once after install ###############
  2185. # ###############################################################################
  2186. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2187. fac_def_from_file = factory_file.read()
  2188. factory_defaults = json.loads(fac_def_from_file)
  2189. # if the file contain an empty dictionary then save the factory defaults into the file
  2190. if not factory_defaults:
  2191. self.save_factory_defaults(silent=False)
  2192. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2193. initial_lay = 'compact'
  2194. self.on_layout(lay=initial_lay)
  2195. # Set the combobox in Preferences to the current layout
  2196. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2197. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2198. factory_file.close()
  2199. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2200. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2201. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2202. # after the first run, this object should be False
  2203. self.defaults["first_run"] = False
  2204. # ###############################################################################
  2205. # ################# ADDING FlatCAM EDITORS section ##############################
  2206. # ###############################################################################
  2207. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2208. # at the first launch of the App , the editors will not be functional.
  2209. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2210. self.exc_editor = FlatCAMExcEditor(self)
  2211. self.grb_editor = FlatCAMGrbEditor(self)
  2212. self.log.debug("Finished adding FlatCAM Editor's.")
  2213. self.set_ui_title(name=_("New Project - Not saved"))
  2214. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2215. current_platform = platform.architecture()[0]
  2216. if current_platform != '64bit':
  2217. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2218. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2219. # ###############################################################################
  2220. # ####################### Finished the CONSTRUCTOR ##############################
  2221. # ###############################################################################
  2222. App.log.debug("END of constructor. Releasing control.")
  2223. # #####################################################################################
  2224. # ########################## SHOW GUI #################################################
  2225. # #####################################################################################
  2226. # if the app is not started as headless, show it
  2227. if self.cmd_line_headless != 1:
  2228. if show_splash:
  2229. # finish the splash
  2230. self.splash.finish(self.ui)
  2231. settings = QSettings("Open Source", "FlatCAM")
  2232. if settings.contains("maximized_gui"):
  2233. maximized_ui = settings.value('maximized_gui', type=bool)
  2234. if maximized_ui is True:
  2235. self.ui.showMaximized()
  2236. else:
  2237. self.ui.show()
  2238. else:
  2239. self.ui.show()
  2240. if self.defaults["global_systray_icon"]:
  2241. self.trayIcon.show()
  2242. else:
  2243. log.warning("******************* RUNNING HEADLESS *******************")
  2244. # #####################################################################################
  2245. # ########################## START-UP ARGUMENTS #######################################
  2246. # #####################################################################################
  2247. # test if the program was started with a script as parameter
  2248. if self.cmd_line_shellvar:
  2249. try:
  2250. cnt = 0
  2251. command_tcl = 0
  2252. for i in self.cmd_line_shellvar.split(','):
  2253. if i is not None:
  2254. try:
  2255. command_tcl = eval(i)
  2256. except:
  2257. command_tcl = i
  2258. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2259. cnt += 1
  2260. # if there are Windows paths then replace the path separator with a Unix like one
  2261. if sys.platform == 'win32':
  2262. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2263. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2264. except Exception as ext:
  2265. print("ERROR: ", ext)
  2266. sys.exit(2)
  2267. if self.cmd_line_shellfile:
  2268. try:
  2269. if self.ui.shell_dock.isHidden():
  2270. self.ui.shell_dock.show()
  2271. with open(self.cmd_line_shellfile, "r") as myfile:
  2272. if show_splash:
  2273. self.splash.showMessage('%s: %ssec\n%s' % (
  2274. _("Canvas initialization started.\n"
  2275. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2276. _("Executing Tcl Script ...")),
  2277. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2278. color=QtGui.QColor("gray"))
  2279. cmd_line_shellfile_text = myfile.read()
  2280. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2281. except Exception as ext:
  2282. print("ERROR: ", ext)
  2283. sys.exit(2)
  2284. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2285. # the path/file_name must be enclosed in quotes if it contain spaces
  2286. if App.args:
  2287. self.args_at_startup.emit(App.args)
  2288. @staticmethod
  2289. def copy_and_overwrite(from_path, to_path):
  2290. """
  2291. From here:
  2292. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2293. :param from_path: source path
  2294. :param to_path: destination path
  2295. :return: None
  2296. """
  2297. if os.path.exists(to_path):
  2298. shutil.rmtree(to_path)
  2299. try:
  2300. shutil.copytree(from_path, to_path)
  2301. except FileNotFoundError:
  2302. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2303. shutil.copytree(from_new_path, to_path)
  2304. def on_startup_args(self, args, silent=False):
  2305. """
  2306. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2307. :param args: a list containing the application args at startup
  2308. :return: None
  2309. """
  2310. if args is not None:
  2311. args_to_process = args
  2312. else:
  2313. args_to_process = App.args
  2314. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2315. for argument in args_to_process:
  2316. if '.FlatPrj'.lower() in argument.lower():
  2317. try:
  2318. project_name = str(argument)
  2319. if project_name == "":
  2320. if silent is False:
  2321. self.inform.emit(_("Open cancelled."))
  2322. else:
  2323. # self.open_project(project_name)
  2324. run_from_arg = True
  2325. # self.worker_task.emit({'fcn': self.open_project,
  2326. # 'params': [project_name, run_from_arg]})
  2327. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2328. except Exception as e:
  2329. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2330. elif '.FlatConfig'.lower() in argument.lower():
  2331. try:
  2332. file_name = str(argument)
  2333. if file_name == "":
  2334. if silent is False:
  2335. self.inform.emit(_("Open Config file failed."))
  2336. else:
  2337. run_from_arg = True
  2338. # self.worker_task.emit({'fcn': self.open_config_file,
  2339. # 'params': [file_name, run_from_arg]})
  2340. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2341. except Exception as e:
  2342. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2343. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2344. try:
  2345. file_name = str(argument)
  2346. if file_name == "":
  2347. if silent is False:
  2348. self.inform.emit(_("Open Script file failed."))
  2349. else:
  2350. if silent is False:
  2351. self.on_fileopenscript(name=file_name)
  2352. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2353. self.on_filerunscript(name=file_name)
  2354. except Exception as e:
  2355. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2356. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2357. log.debug("App.on_startup_args() --> Quit event.")
  2358. sys.exit()
  2359. elif 'save'.lower() in argument.lower():
  2360. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2361. self.save_defaults()
  2362. else:
  2363. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2364. proc_arg = argument.lower()
  2365. for ext in exc_list:
  2366. proc_ext = ext.replace(' ', '')
  2367. proc_ext = '.%s' % proc_ext
  2368. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2369. file_name = str(argument)
  2370. if file_name == "":
  2371. if silent is False:
  2372. self.inform.emit(_("Open Excellon file failed."))
  2373. else:
  2374. self.on_fileopenexcellon(name=file_name)
  2375. return
  2376. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2377. for ext in gco_list:
  2378. proc_ext = ext.replace(' ', '')
  2379. proc_ext = '.%s' % proc_ext
  2380. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2381. file_name = str(argument)
  2382. if file_name == "":
  2383. if silent is False:
  2384. self.inform.emit(_("Open GCode file failed."))
  2385. else:
  2386. self.on_fileopengcode(name=file_name)
  2387. return
  2388. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2389. for ext in grb_list:
  2390. proc_ext = ext.replace(' ', '')
  2391. proc_ext = '.%s' % proc_ext
  2392. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2393. file_name = str(argument)
  2394. if file_name == "":
  2395. if silent is False:
  2396. self.inform.emit(_("Open Gerber file failed."))
  2397. else:
  2398. self.on_fileopengerber(name=file_name)
  2399. return
  2400. # if it reached here without already returning then the app was registered with a file that it does not
  2401. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2402. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2403. # for arg in args_to_process:
  2404. # if 'FlatCAM.exe' in arg:
  2405. # continue
  2406. # else:
  2407. # sys.exit(2)
  2408. def set_ui_title(self, name):
  2409. """
  2410. Sets the title of the main window.
  2411. :param name: String that store the project path and project name
  2412. :return: None
  2413. """
  2414. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2415. (self.version,
  2416. ('BETA' if self.beta else ''),
  2417. platform.architecture()[0],
  2418. self.engine,
  2419. name)
  2420. )
  2421. def on_theme_change(self, val):
  2422. settings = QSettings("Open Source", "FlatCAM")
  2423. settings.setValue('theme', val)
  2424. # This will write the setting to the platform specific storage.
  2425. del settings
  2426. self.on_app_restart()
  2427. def on_app_restart(self):
  2428. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2429. # be left in the SySTray
  2430. try:
  2431. self.trayIcon.hide()
  2432. except Exception as e:
  2433. pass
  2434. fcTranslate.restart_program(app=self)
  2435. def defaults_read_form(self):
  2436. """
  2437. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2438. :return: None
  2439. """
  2440. for option in self.defaults_form_fields:
  2441. try:
  2442. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2443. except Exception as e:
  2444. log.debug("App.defaults_read_form() --> %s" % str(e))
  2445. def defaults_write_form(self, factor=None, fl_units=None):
  2446. """
  2447. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2448. self.defaults dictionary.
  2449. :param factor: will apply a factor to the values that written in the GUI elements
  2450. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2451. :return: None
  2452. """
  2453. for option in self.defaults:
  2454. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2455. # try:
  2456. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2457. # except KeyError:
  2458. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2459. # # TODO: Rethink this?
  2460. # pass
  2461. def defaults_write_form_field(self, field, factor=None, units=None):
  2462. """
  2463. Basically it is the worker in the self.defaults_write_form()
  2464. :param field: the GUI element in Preferences GUI to be updated
  2465. :param factor: factor to be applied to the field parameter
  2466. :param units: current FLatCAM measuring units
  2467. :return: None, it updates GUI elements
  2468. """
  2469. try:
  2470. if factor is None:
  2471. if units is None:
  2472. self.defaults_form_fields[field].set_value(self.defaults[field])
  2473. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2474. self.defaults_form_fields[field].set_value(self.defaults[field])
  2475. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2476. self.defaults_form_fields[field].set_value(self.defaults[field])
  2477. else:
  2478. if units is None:
  2479. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2480. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2481. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2482. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2483. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2484. except KeyError:
  2485. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2486. # TODO: Rethink this?
  2487. pass
  2488. except AttributeError:
  2489. log.debug(field)
  2490. def clear_pool(self):
  2491. """
  2492. Clear the multiprocessing pool and calls garbage collector.
  2493. :return: None
  2494. """
  2495. self.pool.close()
  2496. self.pool = Pool()
  2497. self.pool_recreated.emit(self.pool)
  2498. gc.collect()
  2499. def install_tools(self):
  2500. """
  2501. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2502. Instantiation of the Tools classes.
  2503. The order that the tools are installed is important as they can depend on each other install position.
  2504. :return: None
  2505. """
  2506. self.dblsidedtool = DblSidedTool(self)
  2507. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2508. self.distance_tool = Distance(self)
  2509. self.distance_tool.install(icon=QtGui.QIcon('share/distance16.png'), pos=self.ui.menuedit,
  2510. before=self.ui.menueditorigin,
  2511. separator=False)
  2512. self.distance_min_tool = DistanceMin(self)
  2513. self.distance_min_tool.install(icon=QtGui.QIcon('share/distance_min16.png'), pos=self.ui.menuedit,
  2514. before=self.ui.menueditorigin,
  2515. separator=True)
  2516. self.panelize_tool = Panelize(self)
  2517. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2518. self.film_tool = Film(self)
  2519. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2520. self.paste_tool = SolderPaste(self)
  2521. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2522. self.calculator_tool = ToolCalculator(self)
  2523. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator16.png'), separator=True)
  2524. self.sub_tool = ToolSub(self)
  2525. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2526. self.rules_tool = RulesCheck(self)
  2527. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2528. self.optimal_tool = ToolOptimal(self)
  2529. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2530. self.move_tool = ToolMove(self)
  2531. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2532. before=self.ui.menueditorigin, separator=True)
  2533. self.cutout_tool = CutOut(self)
  2534. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2535. before=self.sub_tool.menuAction)
  2536. self.ncclear_tool = NonCopperClear(self)
  2537. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2538. before=self.sub_tool.menuAction, separator=True)
  2539. self.paint_tool = ToolPaint(self)
  2540. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2541. before=self.sub_tool.menuAction, separator=True)
  2542. self.transform_tool = ToolTransform(self)
  2543. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2544. self.properties_tool = Properties(self)
  2545. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2546. self.pdf_tool = ToolPDF(self)
  2547. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2548. separator=True)
  2549. self.image_tool = ToolImage(self)
  2550. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2551. separator=True)
  2552. self.pcb_wizard_tool = PcbWizard(self)
  2553. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2554. self.log.debug("Tools are installed.")
  2555. def remove_tools(self):
  2556. """
  2557. Will remove all the actions in the Tool menu.
  2558. :return: None
  2559. """
  2560. for act in self.ui.menutool.actions():
  2561. self.ui.menutool.removeAction(act)
  2562. def init_tools(self):
  2563. """
  2564. Initialize the Tool tab in the notebook side of the central widget.
  2565. Remove the actions in the Tools menu.
  2566. Instantiate again the FlatCAM tools (plugins).
  2567. All this is required when changing the layout: standard, compact etc.
  2568. :return: None
  2569. """
  2570. log.debug("init_tools()")
  2571. # delete the data currently in the Tools Tab and the Tab itself
  2572. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2573. if widget is not None:
  2574. widget.deleteLater()
  2575. self.ui.notebook.removeTab(2)
  2576. # rebuild the Tools Tab
  2577. self.ui.tool_tab = QtWidgets.QWidget()
  2578. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2579. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2580. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2581. self.ui.tool_scroll_area = VerticalScrollArea()
  2582. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2583. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2584. # first remove all of them
  2585. self.remove_tools()
  2586. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2587. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2588. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2589. # third install all of them
  2590. self.install_tools()
  2591. self.log.debug("Tools are initialized.")
  2592. # def parse_system_fonts(self):
  2593. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2594. # 'params': []})
  2595. def connect_toolbar_signals(self):
  2596. """
  2597. Reconnect the signals to the actions in the toolbar.
  2598. This has to be done each time after the FlatCAM tools are removed/installed.
  2599. :return: None
  2600. """
  2601. # Toolbar
  2602. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2603. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2604. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2605. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2606. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2607. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2608. self.ui.replot_btn.triggered.connect(self.plot_all)
  2609. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2610. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2611. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2612. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2613. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2614. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2615. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2616. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2617. self.ui.delete_btn.triggered.connect(self.on_delete)
  2618. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2619. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2620. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2621. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2622. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2623. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2624. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2625. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2626. # Tools Toolbar Signals
  2627. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2628. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2629. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2630. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2631. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2632. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2633. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2634. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2635. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2636. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2637. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2638. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2639. def object2editor(self):
  2640. """
  2641. Send the current Geometry or Excellon object (if any) into the it's editor.
  2642. :return: None
  2643. """
  2644. self.report_usage("object2editor()")
  2645. edited_object = self.collection.get_active()
  2646. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2647. isinstance(edited_object, FlatCAMExcellon):
  2648. pass
  2649. else:
  2650. self.inform.emit('[WARNING_NOTCL] %s' %
  2651. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2652. return
  2653. if isinstance(edited_object, FlatCAMGeometry):
  2654. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2655. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2656. # we set the notebook to hidden
  2657. self.ui.splitter.setSizes([0, 1])
  2658. if edited_object.multigeo is True:
  2659. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2660. if len(edited_tools) > 1:
  2661. self.inform.emit('[WARNING_NOTCL] %s' %
  2662. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2663. "is not possible.\n"
  2664. "Edit only one geometry at a time."))
  2665. # determine the tool dia of the selected tool
  2666. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2667. # now find the key in the edited_object.tools that has this tooldia
  2668. multi_tool = 1
  2669. for tool in edited_object.tools:
  2670. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2671. multi_tool = tool
  2672. break
  2673. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2674. else:
  2675. self.geo_editor.edit_fcgeometry(edited_object)
  2676. # set call source to the Editor we go into
  2677. self.call_source = 'geo_editor'
  2678. elif isinstance(edited_object, FlatCAMExcellon):
  2679. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2680. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2681. if self.ui.splitter.sizes()[0] == 0:
  2682. self.ui.splitter.setSizes([1, 1])
  2683. self.exc_editor.edit_fcexcellon(edited_object)
  2684. # set call source to the Editor we go into
  2685. self.call_source = 'exc_editor'
  2686. elif isinstance(edited_object, FlatCAMGerber):
  2687. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2688. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2689. if self.ui.splitter.sizes()[0] == 0:
  2690. self.ui.splitter.setSizes([1, 1])
  2691. self.grb_editor.edit_fcgerber(edited_object)
  2692. # set call source to the Editor we go into
  2693. self.call_source = 'grb_editor'
  2694. # make sure that we can't select another object while in Editor Mode:
  2695. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2696. self.ui.project_frame.setDisabled(True)
  2697. # delete any selection shape that might be active as they are not relevant in Editor
  2698. self.delete_selection_shape()
  2699. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2700. self.ui.plot_tab_area.protectTab(0)
  2701. self.inform.emit('[WARNING_NOTCL] %s' %
  2702. _("Editor is activated ..."))
  2703. self.should_we_save = True
  2704. def editor2object(self, cleanup=None):
  2705. """
  2706. Transfers the Geometry or Excellon from it's editor to the current object.
  2707. :return: None
  2708. """
  2709. self.report_usage("editor2object()")
  2710. # do not update a geometry or excellon object unless it comes out of an editor
  2711. if self.call_source != 'app':
  2712. edited_obj = self.collection.get_active()
  2713. if cleanup is None:
  2714. msgbox = QtWidgets.QMessageBox()
  2715. msgbox.setText(_("Do you want to save the edited object?"))
  2716. msgbox.setWindowTitle(_("Close Editor"))
  2717. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2718. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2719. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2720. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2721. msgbox.setDefaultButton(bt_yes)
  2722. msgbox.exec_()
  2723. response = msgbox.clickedButton()
  2724. if response == bt_yes:
  2725. # clean the Tools Tab
  2726. self.ui.tool_scroll_area.takeWidget()
  2727. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2728. self.ui.notebook.setTabText(2, "Tool")
  2729. if isinstance(edited_obj, FlatCAMGeometry):
  2730. obj_type = "Geometry"
  2731. if cleanup is None:
  2732. self.geo_editor.update_fcgeometry(edited_obj)
  2733. self.geo_editor.update_options(edited_obj)
  2734. self.geo_editor.deactivate()
  2735. # update the geo object options so it is including the bounding box values
  2736. try:
  2737. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2738. edited_obj.options['xmin'] = xmin
  2739. edited_obj.options['ymin'] = ymin
  2740. edited_obj.options['xmax'] = xmax
  2741. edited_obj.options['ymax'] = ymax
  2742. except AttributeError as e:
  2743. self.inform.emit('[WARNING] %s' %
  2744. _("Object empty after edit."))
  2745. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2746. elif isinstance(edited_obj, FlatCAMGerber):
  2747. obj_type = "Gerber"
  2748. if cleanup is None:
  2749. self.grb_editor.update_fcgerber()
  2750. self.grb_editor.update_options(edited_obj)
  2751. self.grb_editor.deactivate_grb_editor()
  2752. # delete the old object (the source object) if it was an empty one
  2753. try:
  2754. if len(edited_obj.solid_geometry) == 0:
  2755. old_name = edited_obj.options['name']
  2756. self.collection.set_active(old_name)
  2757. self.collection.delete_active()
  2758. except TypeError:
  2759. # if the solid_geometry is a single Polygon the len() will not work
  2760. # in any case, falling here means that we have something in the solid_geometry, even if only
  2761. # a single Polygon, therefore we pass this
  2762. pass
  2763. # restore GUI to the Selected TAB
  2764. # Remove anything else in the GUI
  2765. self.ui.selected_scroll_area.takeWidget()
  2766. # Switch notebook to Selected page
  2767. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2768. elif isinstance(edited_obj, FlatCAMExcellon):
  2769. obj_type = "Excellon"
  2770. if cleanup is None:
  2771. self.exc_editor.update_fcexcellon(edited_obj)
  2772. self.exc_editor.update_options(edited_obj)
  2773. self.exc_editor.deactivate()
  2774. # delete the old object (the source object) if it was an empty one
  2775. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2776. old_name = edited_obj.options['name']
  2777. self.collection.set_active(old_name)
  2778. self.collection.delete_active()
  2779. # restore GUI to the Selected TAB
  2780. # Remove anything else in the GUI
  2781. self.ui.tool_scroll_area.takeWidget()
  2782. # Switch notebook to Selected page
  2783. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2784. else:
  2785. self.inform.emit('[WARNING_NOTCL] %s' %
  2786. _("Select a Gerber, Geometry or Excellon Object to update."))
  2787. return
  2788. self.inform.emit('[selected] %s %s' %
  2789. (obj_type, _("is updated, returning to App...")))
  2790. elif response == bt_no:
  2791. # clean the Tools Tab
  2792. self.ui.tool_scroll_area.takeWidget()
  2793. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2794. self.ui.notebook.setTabText(2, "Tool")
  2795. if isinstance(edited_obj, FlatCAMGeometry):
  2796. self.geo_editor.deactivate()
  2797. elif isinstance(edited_obj, FlatCAMGerber):
  2798. self.grb_editor.deactivate_grb_editor()
  2799. elif isinstance(edited_obj, FlatCAMExcellon):
  2800. self.exc_editor.deactivate()
  2801. # set focus on the project tab
  2802. else:
  2803. self.inform.emit('[WARNING_NOTCL] %s' %
  2804. _("Select a Gerber, Geometry or Excellon Object to update."))
  2805. return
  2806. edited_obj.set_ui(edited_obj.ui_type())
  2807. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2808. elif response == bt_cancel:
  2809. return
  2810. else:
  2811. if isinstance(edited_obj, FlatCAMGeometry):
  2812. self.geo_editor.deactivate()
  2813. elif isinstance(edited_obj, FlatCAMGerber):
  2814. self.grb_editor.deactivate_grb_editor()
  2815. elif isinstance(edited_obj, FlatCAMExcellon):
  2816. self.exc_editor.deactivate()
  2817. else:
  2818. self.inform.emit('[WARNING_NOTCL] %s' %
  2819. _("Select a Gerber, Geometry or Excellon Object to update."))
  2820. return
  2821. # if notebook is hidden we show it
  2822. if self.ui.splitter.sizes()[0] == 0:
  2823. self.ui.splitter.setSizes([1, 1])
  2824. # restore the call_source to app
  2825. self.call_source = 'app'
  2826. edited_obj.plot()
  2827. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2828. self.ui.plot_tab_area.protectTab(0)
  2829. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2830. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2831. self.ui.project_frame.setDisabled(False)
  2832. def get_last_folder(self):
  2833. """
  2834. Get the folder path from where the last file was opened.
  2835. :return: String, last opened folder path
  2836. """
  2837. return self.defaults["global_last_folder"]
  2838. def get_last_save_folder(self):
  2839. """
  2840. Get the folder path from where the last file was saved.
  2841. :return: String, last saved folder path
  2842. """
  2843. loc = self.defaults["global_last_save_folder"]
  2844. if loc is None:
  2845. loc = self.defaults["global_last_folder"]
  2846. if loc is None:
  2847. loc = os.path.dirname(__file__)
  2848. return loc
  2849. def report_usage(self, resource):
  2850. """
  2851. Increments usage counter for the given resource
  2852. in self.defaults['global_stats'].
  2853. :param resource: Name of the resource.
  2854. :return: None
  2855. """
  2856. if resource in self.defaults['global_stats']:
  2857. self.defaults['global_stats'][resource] += 1
  2858. else:
  2859. self.defaults['global_stats'][resource] = 1
  2860. def init_tcl(self):
  2861. """
  2862. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2863. :return: None
  2864. """
  2865. if hasattr(self, 'tcl'):
  2866. # self.tcl = None
  2867. # TODO we need to clean non default variables and procedures here
  2868. # new object cannot be used here as it will not remember values created for next passes,
  2869. # because tcl was execudted in old instance of TCL
  2870. pass
  2871. else:
  2872. self.tcl = tk.Tcl()
  2873. self.setup_shell()
  2874. self.log.debug("TCL Shell has been initialized.")
  2875. # TODO: This shouldn't be here.
  2876. class TclErrorException(Exception):
  2877. """
  2878. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2879. """
  2880. pass
  2881. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2882. """
  2883. Shows a message on the FlatCAM Shell
  2884. :param msg: Message to display.
  2885. :param show: Opens the shell.
  2886. :param error: Shows the message as an error.
  2887. :param warning: Shows the message as an warning.
  2888. :param success: Shows the message as an success.
  2889. :param selected: Indicate that something was selected on canvas
  2890. :return: None
  2891. """
  2892. if show:
  2893. self.ui.shell_dock.show()
  2894. try:
  2895. if error:
  2896. self.shell.append_error(msg + "\n")
  2897. elif warning:
  2898. self.shell.append_warning(msg + "\n")
  2899. elif success:
  2900. self.shell.append_success(msg + "\n")
  2901. elif selected:
  2902. self.shell.append_selected(msg + "\n")
  2903. else:
  2904. self.shell.append_output(msg + "\n")
  2905. except AttributeError:
  2906. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2907. def raise_tcl_unknown_error(self, unknownException):
  2908. """
  2909. Raise exception if is different type than TclErrorException
  2910. this is here mainly to show unknown errors inside TCL shell console.
  2911. :param unknownException:
  2912. :return:
  2913. """
  2914. if not isinstance(unknownException, self.TclErrorException):
  2915. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2916. else:
  2917. raise unknownException
  2918. def display_tcl_error(self, error, error_info=None):
  2919. """
  2920. Escape bracket [ with '\' otherwise there is error
  2921. "ERROR: missing close-bracket" instead of real error
  2922. :param error: it may be text or exception
  2923. :param error_info: Some informations about the error
  2924. :return: None
  2925. """
  2926. if isinstance(error, Exception):
  2927. exc_type, exc_value, exc_traceback = error_info
  2928. if not isinstance(error, self.TclErrorException):
  2929. show_trace = 1
  2930. else:
  2931. show_trace = int(self.defaults['global_verbose_error_level'])
  2932. if show_trace > 0:
  2933. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2934. trc_formated = []
  2935. for a in reversed(trc):
  2936. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2937. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2938. else:
  2939. text = "%s" % error
  2940. else:
  2941. text = error
  2942. text = text.replace('[', '\\[').replace('"', '\\"')
  2943. self.tcl.eval('return -code error "%s"' % text)
  2944. def raise_tcl_error(self, text):
  2945. """
  2946. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2947. :param text: text of error
  2948. :return: raise exception
  2949. """
  2950. self.display_tcl_error(text)
  2951. raise self.TclErrorException(text)
  2952. def exec_command(self, text, no_echo=False):
  2953. """
  2954. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2955. Also handles execution in separated threads
  2956. :param text: FlatCAM TclCommand with parameters
  2957. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2958. will create crashes of the _Expandable_Edit widget
  2959. :return: output if there was any
  2960. """
  2961. self.report_usage('exec_command')
  2962. result = self.exec_command_test(text, False, no_echo=no_echo)
  2963. # MS: added this method call so the geometry is updated once the TCL command is executed
  2964. # if no_plot is None:
  2965. # self.plot_all()
  2966. return result
  2967. def exec_command_test(self, text, reraise=True, no_echo=False):
  2968. """
  2969. Same as exec_command(...) with additional control over exceptions.
  2970. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2971. :param text: Input command
  2972. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2973. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2974. will create crashes of the _Expandable_Edit widget
  2975. :return: Output from the command
  2976. """
  2977. tcl_command_string = str(text)
  2978. try:
  2979. if no_echo is False:
  2980. self.shell.open_proccessing() # Disables input box.
  2981. result = self.tcl.eval(str(tcl_command_string))
  2982. if result != 'None' and no_echo is False:
  2983. self.shell.append_output(result + '\n')
  2984. except tk.TclError as e:
  2985. # This will display more precise answer if something in TCL shell fails
  2986. result = self.tcl.eval("set errorInfo")
  2987. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2988. if no_echo is False:
  2989. self.shell.append_error('ERROR: ' + result + '\n')
  2990. # Show error in console and just return or in test raise exception
  2991. if reraise:
  2992. raise e
  2993. finally:
  2994. if no_echo is False:
  2995. self.shell.close_proccessing()
  2996. pass
  2997. return result
  2998. # """
  2999. # Code below is unsused. Saved for later.
  3000. # """
  3001. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3002. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3003. # self.log.debug(parts)
  3004. # try:
  3005. # if parts[0] not in commands:
  3006. # self.shell.append_error("Unknown command\n")
  3007. # return
  3008. #
  3009. # #import inspect
  3010. # #inspect.getargspec(someMethod)
  3011. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3012. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3013. # self.shell.append_error(
  3014. # "Command %s takes %d arguments. %d given.\n" %
  3015. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3016. # )
  3017. # return
  3018. #
  3019. # cmdfcn = commands[parts[0]]["fcn"]
  3020. # cmdconv = commands[parts[0]]["converters"]
  3021. # if len(parts) - 1 > 0:
  3022. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3023. # else:
  3024. # retval = cmdfcn()
  3025. # retfcn = commands[parts[0]]["retfcn"]
  3026. # if retval and retfcn(retval):
  3027. # self.shell.append_output(retfcn(retval) + "\n")
  3028. #
  3029. # except Exception as e:
  3030. # #self.shell.append_error(''.join(traceback.format_exc()))
  3031. # #self.shell.append_error("?\n")
  3032. # self.shell.append_error(str(e) + "\n")
  3033. def info(self, msg):
  3034. """
  3035. Informs the user. Normally on the status bar, optionally
  3036. also on the shell.
  3037. :param msg: Text to write.
  3038. :return: None
  3039. """
  3040. # Type of message in brackets at the beginning of the message.
  3041. match = re.search("\[([^\]]+)\](.*)", msg)
  3042. if match:
  3043. level = match.group(1)
  3044. msg_ = match.group(2)
  3045. self.ui.fcinfo.set_status(str(msg_), level=level)
  3046. if level.lower() == "error":
  3047. self.shell_message(msg, error=True, show=True)
  3048. elif level.lower() == "warning":
  3049. self.shell_message(msg, warning=True, show=True)
  3050. elif level.lower() == "error_notcl":
  3051. self.shell_message(msg, error=True, show=False)
  3052. elif level.lower() == "warning_notcl":
  3053. self.shell_message(msg, warning=True, show=False)
  3054. elif level.lower() == "success":
  3055. self.shell_message(msg, success=True, show=False)
  3056. elif level.lower() == "selected":
  3057. self.shell_message(msg, selected=True, show=False)
  3058. else:
  3059. self.shell_message(msg, show=False)
  3060. else:
  3061. self.ui.fcinfo.set_status(str(msg), level="info")
  3062. # make sure that if the message is to clear the infobar with a space
  3063. # is not printed over and over on the shell
  3064. if msg != '':
  3065. self.shell_message(msg)
  3066. def restore_toolbar_view(self):
  3067. """
  3068. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3069. was saved in the defaults dictionary.
  3070. :return: None
  3071. """
  3072. tb = self.defaults["global_toolbar_view"]
  3073. if tb & 1:
  3074. self.ui.toolbarfile.setVisible(True)
  3075. else:
  3076. self.ui.toolbarfile.setVisible(False)
  3077. if tb & 2:
  3078. self.ui.toolbargeo.setVisible(True)
  3079. else:
  3080. self.ui.toolbargeo.setVisible(False)
  3081. if tb & 4:
  3082. self.ui.toolbarview.setVisible(True)
  3083. else:
  3084. self.ui.toolbarview.setVisible(False)
  3085. if tb & 8:
  3086. self.ui.toolbartools.setVisible(True)
  3087. else:
  3088. self.ui.toolbartools.setVisible(False)
  3089. if tb & 16:
  3090. self.ui.exc_edit_toolbar.setVisible(True)
  3091. else:
  3092. self.ui.exc_edit_toolbar.setVisible(False)
  3093. if tb & 32:
  3094. self.ui.geo_edit_toolbar.setVisible(True)
  3095. else:
  3096. self.ui.geo_edit_toolbar.setVisible(False)
  3097. if tb & 64:
  3098. self.ui.grb_edit_toolbar.setVisible(True)
  3099. else:
  3100. self.ui.grb_edit_toolbar.setVisible(False)
  3101. if tb & 128:
  3102. self.ui.snap_toolbar.setVisible(True)
  3103. else:
  3104. self.ui.snap_toolbar.setVisible(False)
  3105. if tb & 256:
  3106. self.ui.toolbarshell.setVisible(True)
  3107. else:
  3108. self.ui.toolbarshell.setVisible(False)
  3109. def load_defaults(self, filename):
  3110. """
  3111. Loads the aplication's default settings from current_defaults.FlatConfig into
  3112. ``self.defaults``.
  3113. :return: None
  3114. """
  3115. try:
  3116. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3117. options = f.read()
  3118. f.close()
  3119. except IOError:
  3120. self.log.error("Could not load defaults file.")
  3121. self.inform.emit('[ERROR] %s' %
  3122. _("Could not load defaults file."))
  3123. # in case the defaults file can't be loaded, show all toolbars
  3124. self.defaults["global_toolbar_view"] = 511
  3125. return
  3126. try:
  3127. defaults = json.loads(options)
  3128. except:
  3129. # in case the defaults file can't be loaded, show all toolbars
  3130. self.defaults["global_toolbar_view"] = 511
  3131. e = sys.exc_info()[0]
  3132. App.log.error(str(e))
  3133. self.inform.emit('[ERROR] %s' %
  3134. _("Failed to parse defaults file."))
  3135. return
  3136. self.defaults.update(defaults)
  3137. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3138. # restore the toolbar view
  3139. self.restore_toolbar_view()
  3140. def on_import_preferences(self):
  3141. """
  3142. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3143. ``self.defaults``.
  3144. :return: None
  3145. """
  3146. self.report_usage("on_import_preferences")
  3147. App.log.debug("on_import_preferences()")
  3148. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3149. try:
  3150. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3151. directory=self.data_path,
  3152. filter=filter_)
  3153. except TypeError:
  3154. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3155. filter=filter_)
  3156. filename = str(filename)
  3157. if filename == "":
  3158. self.inform.emit('[WARNING_NOTCL] %s' %
  3159. _("FlatCAM preferences import cancelled."))
  3160. else:
  3161. try:
  3162. f = open(filename)
  3163. options = f.read()
  3164. f.close()
  3165. except IOError:
  3166. self.log.error("Could not load defaults file.")
  3167. self.inform.emit('[ERROR_NOTCL] %s' %
  3168. _("Could not load defaults file."))
  3169. return
  3170. try:
  3171. defaults_from_file = json.loads(options)
  3172. except Exception as e:
  3173. e = sys.exc_info()[0]
  3174. App.log.error(str(e))
  3175. self.inform.emit('[ERROR_NOTCL] %s' %
  3176. _("Failed to parse defaults file."))
  3177. return
  3178. self.defaults.update(defaults_from_file)
  3179. self.on_preferences_edited()
  3180. self.inform.emit('[success] %s: %s' %
  3181. (_("Imported Defaults from"), filename))
  3182. def on_export_preferences(self):
  3183. """
  3184. Save the defaults dictionary to a file.
  3185. :return: None
  3186. """
  3187. self.report_usage("on_export_preferences")
  3188. App.log.debug("on_export_preferences()")
  3189. defaults_file_content = None
  3190. self.date = str(datetime.today()).rpartition('.')[0]
  3191. self.date = ''.join(c for c in self.date if c not in ':-')
  3192. self.date = self.date.replace(' ', '_')
  3193. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3194. try:
  3195. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3196. caption=_("Export FlatCAM Preferences"),
  3197. directory=self.data_path + '/preferences_' + self.date,
  3198. filter=filter__
  3199. )
  3200. except TypeError:
  3201. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3202. filter=filter__)
  3203. filename = str(filename)
  3204. defaults_from_file = {}
  3205. if filename == "":
  3206. self.inform.emit('[WARNING_NOTCL] %s' %
  3207. _("FlatCAM preferences export cancelled."))
  3208. return
  3209. else:
  3210. try:
  3211. f = open(filename, 'w')
  3212. defaults_file_content = f.read()
  3213. f.close()
  3214. except PermissionError:
  3215. self.inform.emit('[WARNING] %s' %
  3216. _("Permission denied, saving not possible.\n"
  3217. "Most likely another app is holding the file open and not accessible."))
  3218. return
  3219. except IOError:
  3220. App.log.debug('Creating a new preferences file ...')
  3221. f = open(filename, 'w')
  3222. json.dump({}, f)
  3223. f.close()
  3224. except:
  3225. e = sys.exc_info()[0]
  3226. App.log.error("Could not load defaults file.")
  3227. App.log.error(str(e))
  3228. self.inform.emit('[ERROR_NOTCL] %s' %
  3229. _("Could not load preferences file."))
  3230. return
  3231. try:
  3232. defaults_from_file = json.loads(defaults_file_content)
  3233. except:
  3234. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3235. # Update options
  3236. self.defaults_read_form()
  3237. defaults_from_file.update(self.defaults)
  3238. self.propagate_defaults(silent=True)
  3239. # Save update options
  3240. try:
  3241. f = open(filename, "w")
  3242. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3243. f.close()
  3244. except:
  3245. self.inform.emit('[ERROR_NOTCL] %s' %
  3246. _("Failed to write defaults to file."))
  3247. return
  3248. if self.defaults["global_open_style"] is False:
  3249. self.file_opened.emit("preferences", filename)
  3250. self.file_saved.emit("preferences", filename)
  3251. self.inform.emit('[success] %s: %s' %
  3252. (_("Exported preferences to"), filename))
  3253. def on_preferences_open_folder(self):
  3254. """
  3255. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3256. :return: None
  3257. """
  3258. self.report_usage("on_preferences_open_folder()")
  3259. if sys.platform == 'win32':
  3260. subprocess.Popen('explorer %s' % self.data_path)
  3261. elif sys.platform == 'darwin':
  3262. os.system('open "%s"' % self.data_path)
  3263. else:
  3264. subprocess.Popen(['xdg-open', self.data_path])
  3265. self.inform.emit('[success] %s' %
  3266. _("FlatCAM Preferences Folder opened."))
  3267. def save_geometry(self, x, y, width, height, notebook_width):
  3268. """
  3269. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3270. launch of the application.
  3271. :param x: X position of the main window
  3272. :param y: Y position of the main window
  3273. :param width: width of the main window
  3274. :param height: height of the main window
  3275. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3276. :return: None
  3277. """
  3278. self.defaults["global_def_win_x"] = x
  3279. self.defaults["global_def_win_y"] = y
  3280. self.defaults["global_def_win_w"] = width
  3281. self.defaults["global_def_win_h"] = height
  3282. self.defaults["global_def_notebook_width"] = notebook_width
  3283. self.save_defaults()
  3284. def restore_main_win_geom(self):
  3285. try:
  3286. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3287. self.defaults["global_def_win_y"],
  3288. self.defaults["global_def_win_w"],
  3289. self.defaults["global_def_win_h"])
  3290. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3291. except KeyError as e:
  3292. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3293. def message_dialog(self, title, message, kind="info"):
  3294. """
  3295. Builds and show a custom QMessageBox to be used in FlatCAM.
  3296. :param title: title of the QMessageBox
  3297. :param message: message to be displayed
  3298. :param kind: type of QMessageBox; will display a specific icon.
  3299. :return:
  3300. """
  3301. icon = {"info": QtWidgets.QMessageBox.Information,
  3302. "warning": QtWidgets.QMessageBox.Warning,
  3303. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3304. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3305. dlg.setText(message)
  3306. dlg.exec_()
  3307. def register_recent(self, kind, filename):
  3308. """
  3309. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3310. dictionary.
  3311. :param kind: type of file that was opened
  3312. :param filename: the path and file name for the file that was opened
  3313. :return:
  3314. """
  3315. self.log.debug("register_recent()")
  3316. self.log.debug(" %s" % kind)
  3317. self.log.debug(" %s" % filename)
  3318. record = {'kind': str(kind), 'filename': str(filename)}
  3319. if record in self.recent:
  3320. return
  3321. if record in self.recent_projects:
  3322. return
  3323. if record['kind'] == 'project':
  3324. self.recent_projects.insert(0, record)
  3325. else:
  3326. self.recent.insert(0, record)
  3327. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3328. self.recent.pop()
  3329. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3330. self.recent_projects.pop()
  3331. try:
  3332. f = open(self.data_path + '/recent.json', 'w')
  3333. except IOError:
  3334. App.log.error("Failed to open recent items file for writing.")
  3335. self.inform.emit('[ERROR_NOTCL] %s' %
  3336. _('Failed to open recent files file for writing.'))
  3337. return
  3338. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3339. f.close()
  3340. try:
  3341. fp = open(self.data_path + '/recent_projects.json', 'w')
  3342. except IOError:
  3343. App.log.error("Failed to open recent items file for writing.")
  3344. self.inform.emit('[ERROR_NOTCL] %s' %
  3345. _('Failed to open recent projects file for writing.'))
  3346. return
  3347. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3348. fp.close()
  3349. # Re-build the recent items menu
  3350. self.setup_recent_items()
  3351. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3352. """
  3353. Creates a new specialized FlatCAMObj and attaches it to the application,
  3354. this is, updates the GUI accordingly, any other records and plots it.
  3355. This method is thread-safe.
  3356. Notes:
  3357. * If the name is in use, the self.collection will modify it
  3358. when appending it to the collection. There is no need to handle
  3359. name conflicts here.
  3360. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3361. :type kind: str
  3362. :param name: Name for the object.
  3363. :type name: str
  3364. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3365. The function is called with 2 parameters: the new object and the App instance.
  3366. :type initialize: function
  3367. :param active:
  3368. :param fit:
  3369. :param plot: If to plot the resulting object
  3370. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3371. self.colleaction
  3372. :return: None
  3373. :rtype: None
  3374. """
  3375. App.log.debug("new_object()")
  3376. obj_plot = plot
  3377. obj_autoselected = autoselected
  3378. t0 = time.time() # Debug
  3379. # ## Create object
  3380. classdict = {
  3381. "gerber": FlatCAMGerber,
  3382. "excellon": FlatCAMExcellon,
  3383. "cncjob": FlatCAMCNCjob,
  3384. "geometry": FlatCAMGeometry,
  3385. "script": FlatCAMScript,
  3386. "document": FlatCAMDocument
  3387. }
  3388. App.log.debug("Calling object constructor...")
  3389. obj = classdict[kind](name)
  3390. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3391. # Set options from "Project options" form
  3392. self.options_read_form()
  3393. # IMPORTANT
  3394. # The key names in defaults and options dictionary's are not random:
  3395. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3396. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3397. # the options from project options form into the self.options. After that, below, depending on the type of
  3398. # object that is created, it will strip the name of the object and the underline (if the original key was
  3399. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3400. # "toolchange"
  3401. for option in self.options:
  3402. if option.find(kind + "_") == 0:
  3403. oname = option[len(kind) + 1:]
  3404. obj.options[oname] = self.options[option]
  3405. obj.isHovering = False
  3406. obj.notHovering = True
  3407. # Initialize as per user request
  3408. # User must take care to implement initialize
  3409. # in a thread-safe way as is is likely that we
  3410. # have been invoked in a separate thread.
  3411. t1 = time.time()
  3412. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3413. try:
  3414. return_value = initialize(obj, self)
  3415. except Exception as e:
  3416. msg = '[ERROR_NOTCL] %s' % \
  3417. _("An internal error has ocurred. See shell.\n")
  3418. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3419. msg += traceback.format_exc()
  3420. self.inform.emit(msg)
  3421. # if str(e) == "Empty Geometry":
  3422. # self.inform.emit("[ERROR_NOTCL] )
  3423. # else:
  3424. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3425. return "fail"
  3426. t2 = time.time()
  3427. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3428. if return_value == 'fail':
  3429. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3430. return "fail"
  3431. # Check units and convert if necessary
  3432. # This condition CAN be true because initialize() can change obj.units
  3433. if self.options["units"].upper() != obj.units.upper():
  3434. self.inform.emit('%s: %s' %
  3435. (_("Converting units to "), self.options["units"]))
  3436. obj.convert_units(self.options["units"])
  3437. t3 = time.time()
  3438. self.log.debug("%f seconds converting units." % (t3 - t2))
  3439. # Create the bounding box for the object and then add the results to the obj.options
  3440. # But not for Scripts or for Documents
  3441. if kind != 'document' and kind != 'script':
  3442. try:
  3443. xmin, ymin, xmax, ymax = obj.bounds()
  3444. obj.options['xmin'] = xmin
  3445. obj.options['ymin'] = ymin
  3446. obj.options['xmax'] = xmax
  3447. obj.options['ymax'] = ymax
  3448. except Exception as e:
  3449. log.warning("The object has no bounds properties. %s" % str(e))
  3450. return "fail"
  3451. # update the KeyWords list with the name of the file
  3452. self.myKeywords.append(obj.options['name'])
  3453. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3454. # Move the object to the main thread and let the app know that it is available.
  3455. obj.moveToThread(self.main_thread)
  3456. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3457. return obj
  3458. def new_excellon_object(self):
  3459. """
  3460. Creates a new, blank Excellon object.
  3461. :return: None
  3462. """
  3463. self.report_usage("new_excellon_object()")
  3464. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3465. def new_geometry_object(self):
  3466. """
  3467. Creates a new, blank and single-tool Geometry object.
  3468. :return: None
  3469. """
  3470. self.report_usage("new_geometry_object()")
  3471. def initialize(obj, self):
  3472. obj.multitool = False
  3473. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3474. def new_gerber_object(self):
  3475. """
  3476. Creates a new, blank Gerber object.
  3477. :return: None
  3478. """
  3479. self.report_usage("new_gerber_object()")
  3480. def initialize(grb_obj, self):
  3481. grb_obj.multitool = False
  3482. grb_obj.source_file = []
  3483. grb_obj.multigeo = False
  3484. grb_obj.follow = False
  3485. grb_obj.apertures = {}
  3486. grb_obj.solid_geometry = []
  3487. try:
  3488. grb_obj.options['xmin'] = 0
  3489. grb_obj.options['ymin'] = 0
  3490. grb_obj.options['xmax'] = 0
  3491. grb_obj.options['ymax'] = 0
  3492. except KeyError:
  3493. pass
  3494. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3495. def new_script_object(self, name=None, text=None):
  3496. """
  3497. Creates a new, blank TCL Script object.
  3498. :param name: a name for the new object
  3499. :return: None
  3500. """
  3501. self.report_usage("new_script_object()")
  3502. if text is not None:
  3503. new_source_file = text
  3504. else:
  3505. new_source_file = _(
  3506. "#\n"
  3507. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  3508. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  3509. "#\n\n"
  3510. "# FlatCAM commands list:\n"
  3511. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, "
  3512. "ClearCopper,\n"
  3513. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, "
  3514. "GetNames,\n"
  3515. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  3516. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  3517. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, "
  3518. "SubtractPoly,\n"
  3519. "# SubtractRectangle, Version, WriteGCode\n"
  3520. "#\n\n"
  3521. )
  3522. def initialize(obj, self):
  3523. obj.source_file = deepcopy(new_source_file)
  3524. if name is None:
  3525. outname = 'new_script'
  3526. else:
  3527. outname = name
  3528. self.new_object('script', outname, initialize, plot=False)
  3529. def new_document_object(self):
  3530. """
  3531. Creates a new, blank Document object.
  3532. :return: None
  3533. """
  3534. self.report_usage("new_document_object()")
  3535. def initialize(obj, self):
  3536. obj.source_file = ""
  3537. self.new_object('document', 'new_document', initialize, plot=False)
  3538. def on_object_created(self, obj, plot, autoselect):
  3539. """
  3540. Event callback for object creation.
  3541. It will add the new object to the collection. After that it will plot the object in a threaded way
  3542. :param obj: The newly created FlatCAM object.
  3543. :param plot: if the newly create object t obe plotted
  3544. :param autoselect: if the newly created object to be autoselected after creation
  3545. :return: None
  3546. """
  3547. t0 = time.time() # DEBUG
  3548. self.log.debug("on_object_created()")
  3549. # The Collection might change the name if there is a collision
  3550. self.collection.append(obj)
  3551. # after adding the object to the collection always update the list of objects that are in the collection
  3552. self.all_objects_list = self.collection.get_list()
  3553. # self.inform.emit('[selected] %s created & selected: %s' %
  3554. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3555. if obj.kind == 'gerber':
  3556. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3557. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3558. elif obj.kind == 'excellon':
  3559. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3560. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3561. elif obj.kind == 'cncjob':
  3562. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3563. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3564. elif obj.kind == 'geometry':
  3565. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3566. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3567. elif obj.kind == 'script':
  3568. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3569. kind=obj.kind.capitalize(), color='orange', name=str(obj.options['name'])))
  3570. elif obj.kind == 'document':
  3571. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3572. kind=obj.kind.capitalize(), color='darkCyan', name=str(obj.options['name'])))
  3573. # update the SHELL auto-completer model with the name of the new object
  3574. self.shell._edit.set_model_data(self.myKeywords)
  3575. if autoselect:
  3576. # select the just opened object but deselect the previous ones
  3577. self.collection.set_all_inactive()
  3578. self.collection.set_active(obj.options["name"])
  3579. else:
  3580. self.collection.set_all_inactive()
  3581. # here it is done the object plotting
  3582. def worker_task(t_obj):
  3583. with self.proc_container.new(_("Plotting")):
  3584. if isinstance(t_obj, FlatCAMCNCjob):
  3585. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3586. else:
  3587. t_obj.plot()
  3588. t1 = time.time() # DEBUG
  3589. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3590. self.object_plotted.emit(t_obj)
  3591. # Send to worker
  3592. # self.worker.add_task(worker_task, [self])
  3593. if plot is True:
  3594. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3595. def on_object_changed(self, obj):
  3596. """
  3597. Called whenever the geometry of the object was changed in some way.
  3598. This require the update of it's bounding values so it can be the selected on canvas.
  3599. Update the bounding box data from obj.options
  3600. :param obj: the object that was changed
  3601. :return: None
  3602. """
  3603. xmin, ymin, xmax, ymax = obj.bounds()
  3604. obj.options['xmin'] = xmin
  3605. obj.options['ymin'] = ymin
  3606. obj.options['xmax'] = xmax
  3607. obj.options['ymax'] = ymax
  3608. log.debug("Object changed, updating the bounding box data on self.options")
  3609. # delete the old selection shape
  3610. self.delete_selection_shape()
  3611. self.should_we_save = True
  3612. def on_object_plotted(self, obj):
  3613. """
  3614. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3615. :param obj: object to be fit into view
  3616. :return: None
  3617. """
  3618. self.on_zoom_fit(None)
  3619. def options_read_form(self):
  3620. """
  3621. Same as it's equivalent from the defaults.
  3622. self.options use to store the preferences per project. No longer used.
  3623. :return: None
  3624. """
  3625. for option in self.options_form_fields:
  3626. self.options[option] = self.options_form_fields[option].get_value()
  3627. def options_write_form(self):
  3628. """
  3629. Same as it's equivalent from the defaults.
  3630. self.options use to store the preferences per project. No longer used.
  3631. :return: None
  3632. """
  3633. for option in self.options:
  3634. self.options_write_form_field(option)
  3635. def options_write_form_field(self, field):
  3636. """
  3637. Same as it's equivalent from the defaults.
  3638. self.options use to store the preferences per project. No longer used.
  3639. :return: None
  3640. """
  3641. try:
  3642. self.options_form_fields[field].set_value(self.options[field])
  3643. except KeyError:
  3644. # Changed from error to debug. This allows to have data stored
  3645. # which is not user-editable.
  3646. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3647. pass
  3648. def on_about(self):
  3649. """
  3650. Displays the "about" dialog found in the Menu --> Help.
  3651. :return: None
  3652. """
  3653. self.report_usage("on_about")
  3654. version = self.version
  3655. version_date = self.version_date
  3656. beta = self.beta
  3657. class AboutDialog(QtWidgets.QDialog):
  3658. def __init__(self, parent=None):
  3659. QtWidgets.QDialog.__init__(self, parent)
  3660. # Icon and title
  3661. self.setWindowIcon(parent.app_icon)
  3662. self.setWindowTitle(_("About FlatCAM"))
  3663. self.resize(600, 200)
  3664. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3665. # self.setStyleSheet(
  3666. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3667. # "background-attachment: fixed"
  3668. # )
  3669. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3670. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3671. # palette = QtGui.QPalette()
  3672. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3673. # self.setPalette(palette)
  3674. logo = QtWidgets.QLabel()
  3675. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3676. title = QtWidgets.QLabel(
  3677. "<font size=8><B>FlatCAM</B></font><BR>"
  3678. "{title}<BR>"
  3679. "<BR>"
  3680. "<BR>"
  3681. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3682. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3683. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3684. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3685. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3686. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3687. "<B>{issue}</B></a><BR>".format(
  3688. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3689. devel=_("Development"),
  3690. down=_("DOWNLOAD"),
  3691. issue=_("Issue tracker"))
  3692. )
  3693. title.setOpenExternalLinks(True)
  3694. closebtn = QtWidgets.QPushButton(_("Close"))
  3695. tab_widget = QtWidgets.QTabWidget()
  3696. description_label = QtWidgets.QLabel(
  3697. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3698. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3699. version=version,
  3700. beta=('BETA' if beta else ''),
  3701. date=version_date,
  3702. arch=platform.architecture()[0])
  3703. )
  3704. description_label.setOpenExternalLinks(True)
  3705. license_label = QtWidgets.QLabel(
  3706. _(
  3707. '\n'
  3708. 'Licensed under the MIT license:\n'
  3709. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3710. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3711. 'of this software and associated documentation files (the "Software"), to deal\n'
  3712. 'in the Software without restriction, including without limitation the rights\n'
  3713. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3714. 'copies of the Software, and to permit persons to whom the Software is\n'
  3715. 'furnished to do so, subject to the following conditions:\n\n'
  3716. 'The above copyright notice and this permission notice shall be included in\n'
  3717. 'all copies or substantial portions of the Software.\n\n'
  3718. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3719. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3720. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3721. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3722. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3723. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3724. 'THE SOFTWARE.'
  3725. )
  3726. )
  3727. license_label.setOpenExternalLinks(True)
  3728. attributions_label = QtWidgets.QLabel(
  3729. _(
  3730. 'Some of the icons used are from the following sources: <BR>'
  3731. '<div>Icons made by <a href="https://www.flaticon.com/authors/freepik" '
  3732. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3733. 'title="Flaticon">www.flaticon.com</a></div><br>'
  3734. 'Icons by <a target="_blank" href="https://icons8.com">Icons8</a>'
  3735. )
  3736. )
  3737. # layouts
  3738. layout1 = QtWidgets.QVBoxLayout()
  3739. layout1_1 = QtWidgets.QHBoxLayout()
  3740. layout1_2 = QtWidgets.QHBoxLayout()
  3741. layout2 = QtWidgets.QHBoxLayout()
  3742. layout3 = QtWidgets.QHBoxLayout()
  3743. self.setLayout(layout1)
  3744. layout1.addLayout(layout1_1)
  3745. layout1.addLayout(layout1_2)
  3746. layout1.addLayout(layout2)
  3747. layout1.addLayout(layout3)
  3748. layout1_1.addStretch()
  3749. layout1_1.addWidget(description_label)
  3750. layout1_2.addWidget(tab_widget)
  3751. self.splash_tab = QtWidgets.QWidget()
  3752. self.splash_tab.setObjectName("splash_about")
  3753. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3754. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3755. tab_widget.addTab(self.splash_tab, _("Splash"))
  3756. self.programmmers_tab = QtWidgets.QWidget()
  3757. self.programmmers_tab.setObjectName("programmers_about")
  3758. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3759. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3760. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3761. self.translators_tab = QtWidgets.QWidget()
  3762. self.translators_tab.setObjectName("translators_about")
  3763. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3764. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3765. tab_widget.addTab(self.translators_tab, _("Translators"))
  3766. self.license_tab = QtWidgets.QWidget()
  3767. self.license_tab.setObjectName("license_about")
  3768. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3769. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3770. tab_widget.addTab(self.license_tab, _("License"))
  3771. self.attributions_tab = QtWidgets.QWidget()
  3772. self.attributions_tab.setObjectName("attributions_about")
  3773. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3774. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3775. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3776. self.splash_tab_layout.addWidget(logo, stretch=0)
  3777. self.splash_tab_layout.addWidget(title, stretch=1)
  3778. pal = QtGui.QPalette()
  3779. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3780. self.prog_form_lay = QtWidgets.QFormLayout()
  3781. self.prog_form_lay.setHorizontalSpacing(20)
  3782. prog_widget = QtWidgets.QWidget()
  3783. prog_widget.setLayout(self.prog_form_lay)
  3784. prog_scroll = QtWidgets.QScrollArea()
  3785. prog_scroll.setWidget(prog_widget)
  3786. prog_scroll.setWidgetResizable(True)
  3787. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3788. prog_scroll.setPalette(pal)
  3789. self.programmmers_tab_layout.addWidget(prog_scroll)
  3790. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3791. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3792. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3793. QtWidgets.QLabel('%s' % _("Program Author")))
  3794. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3795. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3796. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3797. QtWidgets.QLabel('%s' % _("Maintainer >= 2019")))
  3798. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3799. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alex Lazar"))
  3800. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3801. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3802. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3803. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3804. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3805. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3806. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3807. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3808. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3809. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3810. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3811. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3812. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3813. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3814. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3815. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3816. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3817. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3818. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3819. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3820. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3821. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3822. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3823. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3824. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3825. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3826. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3827. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3828. self.translator_grid_lay = QtWidgets.QGridLayout()
  3829. # trans_widget = QtWidgets.QWidget()
  3830. # trans_widget.setLayout(self.translator_grid_lay)
  3831. # self.translators_tab_layout.addWidget(trans_widget)
  3832. # self.translators_tab_layout.addStretch()
  3833. trans_widget = QtWidgets.QWidget()
  3834. trans_widget.setLayout(self.translator_grid_lay)
  3835. trans_scroll = QtWidgets.QScrollArea()
  3836. trans_scroll.setWidget(trans_widget)
  3837. trans_scroll.setWidgetResizable(True)
  3838. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3839. trans_scroll.setPalette(pal)
  3840. self.translators_tab_layout.addWidget(trans_scroll)
  3841. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3842. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3843. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3844. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3845. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3846. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3847. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3848. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3849. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3850. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3851. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 3, 1)
  3852. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3853. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3854. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3855. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  3856. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3857. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3858. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 2)
  3859. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3860. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 6, 1)
  3861. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 2)
  3862. self.translator_grid_lay.setColumnStretch(0, 0)
  3863. self.translators_tab_layout.addStretch()
  3864. self.license_tab_layout.addWidget(license_label)
  3865. self.license_tab_layout.addStretch()
  3866. self.attributions_tab_layout.addWidget(attributions_label)
  3867. self.attributions_tab_layout.addStretch()
  3868. layout3.addStretch()
  3869. layout3.addWidget(closebtn)
  3870. closebtn.clicked.connect(self.accept)
  3871. AboutDialog(self.ui).exec_()
  3872. def on_file_savedefaults(self):
  3873. """
  3874. Callback for menu item File->Save Defaults. Saves application default options
  3875. ``self.defaults`` to current_defaults.FlatConfig.
  3876. :return: None
  3877. """
  3878. self.save_defaults()
  3879. # def on_app_exit(self):
  3880. # self.report_usage("on_app_exit()")
  3881. #
  3882. # if self.collection.get_list():
  3883. # msgbox = QtWidgets.QMessageBox()
  3884. # # msgbox.setText("<B>Save changes ...</B>")
  3885. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3886. # "\n"
  3887. # "Do you want to Save the project?")
  3888. # msgbox.setWindowTitle("Save changes")
  3889. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3890. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3891. # QtWidgets.QMessageBox.Cancel)
  3892. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3893. #
  3894. # response = msgbox.exec_()
  3895. #
  3896. # if response == QtWidgets.QMessageBox.Yes:
  3897. # self.on_file_saveprojectas(thread=False)
  3898. # elif response == QtWidgets.QMessageBox.Cancel:
  3899. # return
  3900. # self.save_defaults()
  3901. # else:
  3902. # self.save_defaults()
  3903. # log.debug("Application defaults saved ... Exit event.")
  3904. # QtWidgets.qApp.quit()
  3905. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3906. """
  3907. Saves application default options
  3908. ``self.defaults`` to current_defaults.FlatConfig file.
  3909. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3910. used at the next launch of the application.
  3911. :param silent: whether to display a message in status bar or not; boolean
  3912. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3913. When the application is portable it should be a mobile location.
  3914. :return: None
  3915. """
  3916. self.report_usage("save_defaults")
  3917. if data_path is None:
  3918. data_path = self.data_path
  3919. # Read options from file
  3920. try:
  3921. f = open(data_path + "/current_defaults.FlatConfig")
  3922. defaults_file_content = f.read()
  3923. f.close()
  3924. except:
  3925. e = sys.exc_info()[0]
  3926. App.log.error("Could not load defaults file.")
  3927. App.log.error(str(e))
  3928. self.inform.emit('[ERROR_NOTCL] %s' %
  3929. _("Could not load defaults file."))
  3930. return
  3931. try:
  3932. defaults = json.loads(defaults_file_content)
  3933. except:
  3934. e = sys.exc_info()[0]
  3935. App.log.error("Failed to parse defaults file.")
  3936. App.log.error(str(e))
  3937. self.inform.emit('[ERROR_NOTCL] %s' %
  3938. _("Failed to parse defaults file."))
  3939. return
  3940. # Update options
  3941. self.defaults_read_form()
  3942. defaults.update(self.defaults)
  3943. self.propagate_defaults(silent=True)
  3944. # Save the toolbar view
  3945. tb_status = 0
  3946. if self.ui.toolbarfile.isVisible():
  3947. tb_status += 1
  3948. if self.ui.toolbargeo.isVisible():
  3949. tb_status += 2
  3950. if self.ui.toolbarview.isVisible():
  3951. tb_status += 4
  3952. if self.ui.toolbartools.isVisible():
  3953. tb_status += 8
  3954. if self.ui.exc_edit_toolbar.isVisible():
  3955. tb_status += 16
  3956. if self.ui.geo_edit_toolbar.isVisible():
  3957. tb_status += 32
  3958. if self.ui.grb_edit_toolbar.isVisible():
  3959. tb_status += 64
  3960. if self.ui.snap_toolbar.isVisible():
  3961. tb_status += 128
  3962. if self.ui.toolbarshell.isVisible():
  3963. tb_status += 256
  3964. if first_time is False:
  3965. self.defaults["global_toolbar_view"] = tb_status
  3966. # Save update options
  3967. try:
  3968. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3969. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3970. f.close()
  3971. except:
  3972. self.inform.emit('[ERROR_NOTCL] %s' %
  3973. _("Failed to write defaults to file."))
  3974. return
  3975. if not silent:
  3976. self.inform.emit('[success] %s' %
  3977. _("Preferences saved."))
  3978. def save_factory_defaults(self, silent=False, data_path=None):
  3979. """
  3980. Saves application factory default options
  3981. ``self.defaults`` to factory_defaults.FlatConfig.
  3982. It's a one time job done just after the first install.
  3983. :param silent: whether to display a message in status bar or not; boolean
  3984. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3985. When the application is portable it should be a mobile location.
  3986. :return: None
  3987. """
  3988. self.report_usage("save_factory_defaults")
  3989. if data_path is None:
  3990. data_path = self.data_path
  3991. # Read options from file
  3992. try:
  3993. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3994. factory_defaults_file_content = f_f_def.read()
  3995. f_f_def.close()
  3996. except:
  3997. e = sys.exc_info()[0]
  3998. App.log.error("Could not load factory defaults file.")
  3999. App.log.error(str(e))
  4000. self.inform.emit('[ERROR_NOTCL] %s' %
  4001. _("Could not load factory defaults file."))
  4002. return
  4003. try:
  4004. factory_defaults = json.loads(factory_defaults_file_content)
  4005. except:
  4006. e = sys.exc_info()[0]
  4007. App.log.error("Failed to parse factory defaults file.")
  4008. App.log.error(str(e))
  4009. self.inform.emit('[ERROR_NOTCL] %s' %
  4010. _("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:
  4022. self.inform.emit('[ERROR_NOTCL] %s' %
  4023. _("Failed to write factory defaults to file."))
  4024. return
  4025. if silent is False:
  4026. self.inform.emit(_("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('[WARNING_NOTCL] %s' %
  4035. _("Application is saving the project. Please wait ..."))
  4036. return
  4037. if self.should_we_save and self.collection.get_list():
  4038. msgbox = QtWidgets.QMessageBox()
  4039. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4040. "\n"
  4041. "Do you want to Save the project?"))
  4042. msgbox.setWindowTitle(_("Save changes"))
  4043. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4044. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4045. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4046. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4047. msgbox.setDefaultButton(bt_yes)
  4048. msgbox.exec_()
  4049. response = msgbox.clickedButton()
  4050. if response == bt_yes:
  4051. try:
  4052. self.trayIcon.hide()
  4053. except:
  4054. pass
  4055. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4056. elif response == bt_no:
  4057. try:
  4058. self.trayIcon.hide()
  4059. except:
  4060. pass
  4061. self.quit_application()
  4062. elif response == bt_cancel:
  4063. return
  4064. else:
  4065. try:
  4066. self.trayIcon.hide()
  4067. except:
  4068. pass
  4069. self.quit_application()
  4070. def quit_application(self):
  4071. """
  4072. Called (as a pyslot or not) when the application is quit.
  4073. :return: None
  4074. """
  4075. self.save_defaults()
  4076. log.debug("App.final_save() --> App Defaults saved.")
  4077. if self.cmd_line_headless != 1:
  4078. # save app state to file
  4079. settings = QSettings("Open Source", "FlatCAM")
  4080. settings.setValue('saved_gui_state', self.ui.saveState())
  4081. settings.setValue('maximized_gui', self.ui.isMaximized())
  4082. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  4083. settings.setValue(
  4084. 'notebook_font_size',
  4085. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4086. )
  4087. settings.setValue('axis_font_size',
  4088. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  4089. settings.setValue(
  4090. 'textbox_font_size',
  4091. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4092. )
  4093. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4094. # This will write the setting to the platform specific storage.
  4095. del settings
  4096. log.debug("App.final_save() --> App UI state saved.")
  4097. QtWidgets.qApp.quit()
  4098. def on_portable_checked(self, state):
  4099. """
  4100. Callback called when the checkbox in Preferences GUI is checked.
  4101. It will set the application as portable by creating the preferences and recent files in the
  4102. 'config' folder found in the FlatCAM installation folder.
  4103. :param state: boolean, the state of the checkbox when clicked/checked
  4104. :return:
  4105. """
  4106. line_no = 0
  4107. data = None
  4108. if sys.platform != 'win32':
  4109. # this won't work in Linux or MacOS
  4110. return
  4111. # test if the app was frozen and choose the path for the configuration file
  4112. if getattr(sys, "frozen", False) is True:
  4113. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4114. else:
  4115. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4116. config_file = current_data_path + '\\configuration.txt'
  4117. try:
  4118. with open(config_file, 'r') as f:
  4119. try:
  4120. data = f.readlines()
  4121. except Exception as e:
  4122. log.debug('App.__init__() -->%s' % str(e))
  4123. return
  4124. except FileNotFoundError:
  4125. pass
  4126. for line in data:
  4127. line = line.strip('\n')
  4128. param = str(line).rpartition('=')
  4129. if param[0] == 'portable':
  4130. break
  4131. line_no += 1
  4132. if state:
  4133. data[line_no] = 'portable=True\n'
  4134. # create the new defauults files
  4135. # create current_defaults.FlatConfig file if there is none
  4136. try:
  4137. f = open(current_data_path + '/current_defaults.FlatConfig')
  4138. f.close()
  4139. except IOError:
  4140. App.log.debug('Creating empty current_defaults.FlatConfig')
  4141. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4142. json.dump({}, f)
  4143. f.close()
  4144. # create factory_defaults.FlatConfig file if there is none
  4145. try:
  4146. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4147. f.close()
  4148. except IOError:
  4149. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4150. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4151. json.dump({}, f)
  4152. f.close()
  4153. try:
  4154. f = open(current_data_path + '/recent.json')
  4155. f.close()
  4156. except IOError:
  4157. App.log.debug('Creating empty recent.json')
  4158. f = open(current_data_path + '/recent.json', 'w')
  4159. json.dump([], f)
  4160. f.close()
  4161. try:
  4162. fp = open(current_data_path + '/recent_projects.json')
  4163. fp.close()
  4164. except IOError:
  4165. App.log.debug('Creating empty recent_projects.json')
  4166. fp = open(current_data_path + '/recent_projects.json', 'w')
  4167. json.dump([], fp)
  4168. fp.close()
  4169. # save the current defaults to the new defaults file
  4170. self.save_defaults(silent=True, data_path=current_data_path)
  4171. self.save_factory_defaults(silent=True, data_path=current_data_path)
  4172. else:
  4173. data[line_no] = 'portable=False\n'
  4174. with open(config_file, 'w') as f:
  4175. f.writelines(data)
  4176. def on_toggle_shell(self):
  4177. """
  4178. Toggle shell: if is visible close it, if it is closed then open it
  4179. :return:
  4180. """
  4181. self.report_usage("on_toggle_shell()")
  4182. if self.ui.shell_dock.isVisible():
  4183. self.ui.shell_dock.hide()
  4184. else:
  4185. self.ui.shell_dock.show()
  4186. def on_register_files(self, obj_type=None):
  4187. """
  4188. Called whenever there is a need to register file extensions with FlatCAM.
  4189. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4190. :param obj_type: the type of object to be register for.
  4191. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4192. :return: None
  4193. """
  4194. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4195. new_reg_path = 'Software\\Classes\\'
  4196. # find if the current user is admin
  4197. try:
  4198. is_admin = os.getuid() == 0
  4199. except AttributeError:
  4200. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4201. if is_admin is True:
  4202. root_path = winreg.HKEY_LOCAL_MACHINE
  4203. else:
  4204. root_path = winreg.HKEY_CURRENT_USER
  4205. # create the keys
  4206. def set_reg(name, root_path, new_reg_path, value):
  4207. try:
  4208. winreg.CreateKey(root_path, new_reg_path)
  4209. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4210. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4211. return True
  4212. except WindowsError:
  4213. return False
  4214. # delete key in registry
  4215. def delete_reg(root_path, reg_path, key_to_del):
  4216. key_to_del_path = reg_path + key_to_del
  4217. try:
  4218. winreg.DeleteKey(root_path, key_to_del_path)
  4219. return True
  4220. except WindowsError:
  4221. return False
  4222. if obj_type is None or obj_type == 'excellon':
  4223. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4224. exc_list = [x for x in exc_list if x != '']
  4225. # register all keys in the Preferences window
  4226. for ext in exc_list:
  4227. new_k = new_reg_path + '.%s' % ext
  4228. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4229. # and unregister those that are no longer in the Preferences windows but are in the file
  4230. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4231. if ext not in exc_list:
  4232. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4233. # now write the updated extensions to the self.defaults
  4234. # new_ext = ''
  4235. # for ext in exc_list:
  4236. # new_ext = new_ext + ext + ', '
  4237. # self.defaults["fa_excellon"] = new_ext
  4238. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4239. if obj_type is None or obj_type == 'gcode':
  4240. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4241. gco_list = [x for x in gco_list if x != '']
  4242. # register all keys in the Preferences window
  4243. for ext in gco_list:
  4244. new_k = new_reg_path + '.%s' % ext
  4245. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4246. # and unregister those that are no longer in the Preferences windows but are in the file
  4247. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4248. if ext not in gco_list:
  4249. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4250. # now write the updated extensions to the self.defaults
  4251. # new_ext = ''
  4252. # for ext in gco_list:
  4253. # new_ext = new_ext + ext + ', '
  4254. # self.defaults["fa_gcode"] = new_ext
  4255. self.inform.emit('[success] %s' %
  4256. _("Selected GCode file extensions registered with FlatCAM."))
  4257. if obj_type is None or obj_type == 'gerber':
  4258. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4259. grb_list = [x for x in grb_list if x != '']
  4260. # register all keys in the Preferences window
  4261. for ext in grb_list:
  4262. new_k = new_reg_path + '.%s' % ext
  4263. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4264. # and unregister those that are no longer in the Preferences windows but are in the file
  4265. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4266. if ext not in grb_list:
  4267. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4268. # now write the updated extensions to the self.defaults
  4269. # new_ext = ''
  4270. # for ext in grb_list:
  4271. # new_ext = new_ext + ext + ', '
  4272. # self.defaults["fa_gerber"] = new_ext
  4273. self.inform.emit('[success] %s' %
  4274. _("Selected Gerber file extensions registered with FlatCAM."))
  4275. def add_extension(self, ext_type):
  4276. if ext_type == 'excellon':
  4277. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4278. if new_ext == '':
  4279. return
  4280. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4281. if new_ext in old_val:
  4282. return
  4283. old_val.append(new_ext)
  4284. old_val.sort()
  4285. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4286. if ext_type == 'gcode':
  4287. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4288. if new_ext == '':
  4289. return
  4290. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4291. if new_ext in old_val:
  4292. return
  4293. old_val.append(new_ext)
  4294. old_val.sort()
  4295. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4296. if ext_type == 'gerber':
  4297. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4298. if new_ext == '':
  4299. return
  4300. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4301. if new_ext in old_val:
  4302. return
  4303. old_val.append(new_ext)
  4304. old_val.sort()
  4305. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4306. if ext_type == 'keyword':
  4307. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4308. if new_kw == '':
  4309. return
  4310. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4311. if new_kw in old_val:
  4312. return
  4313. old_val.append(new_kw)
  4314. old_val.sort()
  4315. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4316. # update the self.myKeywords so the model is updated
  4317. self.autocomplete_kw_list = \
  4318. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4319. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4320. self.shell._edit.set_model_data(self.myKeywords)
  4321. def del_extension(self, ext_type):
  4322. if ext_type == 'excellon':
  4323. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4324. if new_ext == '':
  4325. return
  4326. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4327. if new_ext not in old_val:
  4328. return
  4329. old_val.remove(new_ext)
  4330. old_val.sort()
  4331. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4332. if ext_type == 'gcode':
  4333. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4334. if new_ext == '':
  4335. return
  4336. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4337. if new_ext not in old_val:
  4338. return
  4339. old_val.remove(new_ext)
  4340. old_val.sort()
  4341. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4342. if ext_type == 'gerber':
  4343. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4344. if new_ext == '':
  4345. return
  4346. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4347. if new_ext not in old_val:
  4348. return
  4349. old_val.remove(new_ext)
  4350. old_val.sort()
  4351. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4352. if ext_type == 'keyword':
  4353. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4354. if new_kw == '':
  4355. return
  4356. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4357. if new_kw not in old_val:
  4358. return
  4359. old_val.remove(new_kw)
  4360. old_val.sort()
  4361. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4362. # update the self.myKeywords so the model is updated
  4363. self.autocomplete_kw_list = \
  4364. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4365. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4366. self.shell._edit.set_model_data(self.myKeywords)
  4367. def restore_extensions(self, ext_type):
  4368. if ext_type == 'excellon':
  4369. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4370. # for the ability to open Excellon files with .txt extension
  4371. new_exc_list = deepcopy(self.exc_list)
  4372. try:
  4373. new_exc_list.remove('txt')
  4374. except ValueError:
  4375. pass
  4376. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4377. if ext_type == 'gcode':
  4378. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4379. if ext_type == 'gerber':
  4380. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4381. if ext_type == 'keyword':
  4382. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4383. # update the self.myKeywords so the model is updated
  4384. self.autocomplete_kw_list = self.default_keywords
  4385. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4386. self.shell._edit.set_model_data(self.myKeywords)
  4387. def delete_all_extensions(self, ext_type):
  4388. if ext_type == 'excellon':
  4389. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4390. if ext_type == 'gcode':
  4391. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4392. if ext_type == 'gerber':
  4393. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4394. if ext_type == 'keyword':
  4395. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4396. # update the self.myKeywords so the model is updated
  4397. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4398. self.shell._edit.set_model_data(self.myKeywords)
  4399. def on_edit_join(self, name=None):
  4400. """
  4401. Callback for Edit->Join. Joins the selected geometry objects into
  4402. a new one.
  4403. :return: None
  4404. """
  4405. self.report_usage("on_edit_join()")
  4406. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4407. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4408. geo_type_list = set()
  4409. objs = self.collection.get_selected()
  4410. if len(objs) < 2:
  4411. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4412. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4413. return 'fail'
  4414. for obj in objs:
  4415. geo_type_list.add(obj.multigeo)
  4416. # if len(geo_type_list) == 1 means that all list elements are the same
  4417. if len(geo_type_list) != 1:
  4418. self.inform.emit('[ERROR] %s' %
  4419. _("Failed join. The Geometry objects are of different types.\n"
  4420. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4421. "convert from one to another and retry joining \n"
  4422. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4423. "the result may not be what was expected. \n"
  4424. "Check the generated GCODE."))
  4425. return
  4426. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4427. if True in geo_type_list:
  4428. def initialize(obj, app):
  4429. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4430. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4431. for v in obj.tools.values():
  4432. v['data']['name'] = obj_name_multi
  4433. self.new_object("geometry", obj_name_multi, initialize)
  4434. else:
  4435. def initialize(obj, app):
  4436. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4437. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4438. for v in obj.tools.values():
  4439. v['data']['name'] = obj_name_single
  4440. self.new_object("geometry", obj_name_single, initialize)
  4441. self.should_we_save = True
  4442. def on_edit_join_exc(self):
  4443. """
  4444. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4445. a new Excellon.
  4446. :return: None
  4447. """
  4448. self.report_usage("on_edit_join_exc()")
  4449. objs = self.collection.get_selected()
  4450. for obj in objs:
  4451. if not isinstance(obj, FlatCAMExcellon):
  4452. self.inform.emit('[ERROR_NOTCL] %s' %
  4453. _("Failed. Excellon joining works only on Excellon objects."))
  4454. return
  4455. if len(objs) < 2:
  4456. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4457. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4458. return 'fail'
  4459. def initialize(obj, app):
  4460. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4461. self.new_object("excellon", 'Combo_Excellon', initialize)
  4462. self.should_we_save = True
  4463. def on_edit_join_grb(self):
  4464. """
  4465. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4466. a new Gerber object.
  4467. :return: None
  4468. """
  4469. self.report_usage("on_edit_join_grb()")
  4470. objs = self.collection.get_selected()
  4471. for obj in objs:
  4472. if not isinstance(obj, FlatCAMGerber):
  4473. self.inform.emit('[ERROR_NOTCL] %s' %
  4474. _("Failed. Gerber joining works only on Gerber objects."))
  4475. return
  4476. if len(objs) < 2:
  4477. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4478. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4479. return 'fail'
  4480. def initialize(obj, app):
  4481. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4482. self.new_object("gerber", 'Combo_Gerber', initialize)
  4483. self.should_we_save = True
  4484. def on_convert_singlegeo_to_multigeo(self):
  4485. """
  4486. Called for converting a Geometry object from single-geo to multi-geo.
  4487. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4488. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4489. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4490. the solid-geometry of that tool.
  4491. :return: None
  4492. """
  4493. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4494. obj = self.collection.get_active()
  4495. if obj is None:
  4496. self.inform.emit('[ERROR_NOTCL] %s' %
  4497. _("Failed. Select a Geometry Object and try again."))
  4498. return
  4499. if not isinstance(obj, FlatCAMGeometry):
  4500. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4501. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4502. return
  4503. obj.multigeo = True
  4504. for tooluid, dict_value in obj.tools.items():
  4505. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4506. if not isinstance(obj.solid_geometry, list):
  4507. obj.solid_geometry = [obj.solid_geometry]
  4508. obj.solid_geometry[:] = []
  4509. obj.plot()
  4510. self.should_we_save = True
  4511. self.inform.emit('[success] %s' %
  4512. _("A Geometry object was converted to MultiGeo type."))
  4513. def on_convert_multigeo_to_singlegeo(self):
  4514. """
  4515. Called for converting a Geometry object from multi-geo to single-geo.
  4516. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4517. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4518. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4519. the solid-geometry of that tool.
  4520. :return: None
  4521. """
  4522. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4523. obj = self.collection.get_active()
  4524. if obj is None:
  4525. self.inform.emit('[ERROR_NOTCL] %s' %
  4526. _("Failed. Select a Geometry Object and try again."))
  4527. return
  4528. if not isinstance(obj, FlatCAMGeometry):
  4529. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4530. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4531. return
  4532. obj.multigeo = False
  4533. total_solid_geometry = []
  4534. for tooluid, dict_value in obj.tools.items():
  4535. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4536. # clear the original geometry
  4537. dict_value['solid_geometry'][:] = []
  4538. obj.solid_geometry = deepcopy(total_solid_geometry)
  4539. obj.plot()
  4540. self.should_we_save = True
  4541. self.inform.emit('[success] %s' %
  4542. _("A Geometry object was converted to SingleGeo type."))
  4543. def on_options_dict_change(self, field):
  4544. """
  4545. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4546. current project. This feature is no longer used.
  4547. :param field:
  4548. :return:
  4549. """
  4550. self.options_write_form_field(field)
  4551. if field == "units":
  4552. self.set_screen_units(self.options['units'])
  4553. def on_defaults_dict_change(self, field):
  4554. """
  4555. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4556. Edit -> Preferences tab window.
  4557. :param field: the key of the self.defaults dictionary that was changed.
  4558. :return: None
  4559. """
  4560. self.defaults_write_form_field(field)
  4561. if field == "units":
  4562. self.set_screen_units(self.defaults['units'])
  4563. def set_screen_units(self, units):
  4564. """
  4565. Set the FlatCAM units on the status bar.
  4566. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4567. :return: None
  4568. """
  4569. self.ui.units_label.setText("[" + units.lower() + "]")
  4570. def on_toggle_units(self, no_pref=False):
  4571. """
  4572. Callback for the Units radio-button change in the Preferences tab.
  4573. Changes the application's default units adn for the project too.
  4574. If changing the project's units, the change propagates to all of
  4575. the objects in the project.
  4576. :return: None
  4577. """
  4578. self.report_usage("on_toggle_units")
  4579. if self.toggle_units_ignore:
  4580. return
  4581. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4582. # If option is the same, then ignore
  4583. if new_units == self.defaults["units"].upper():
  4584. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4585. return
  4586. # Options to scale
  4587. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4588. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4589. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4590. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4591. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4592. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4593. "excellon_editor_slot_lin_pitch",
  4594. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4595. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4596. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4597. "geometry_feedrate_probe", "geometry_startz",
  4598. 'cncjob_tooldia',
  4599. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4600. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4601. "tools_2sided_drilldia", "tools_film_boundary",
  4602. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4603. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4604. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4605. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4606. "tools_transform_offset_y",
  4607. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4608. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4609. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4610. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4611. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4612. def scale_options(sfactor):
  4613. for dim in dimensions:
  4614. if dim == 'excellon_toolchangexy':
  4615. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4616. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4617. coords_xy[0] *= sfactor
  4618. coords_xy[1] *= sfactor
  4619. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4620. elif dim == 'geometry_toolchangexy':
  4621. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4622. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4623. coords_xy[0] *= sfactor
  4624. coords_xy[1] *= sfactor
  4625. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4626. elif dim == 'geometry_cnctooldia':
  4627. tools_diameters = []
  4628. try:
  4629. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4630. tools_diameters = [eval(a) for a in tools_string if a != '']
  4631. except Exception as e:
  4632. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4633. self.options['geometry_cnctooldia'] = ''
  4634. for t in range(len(tools_diameters)):
  4635. tools_diameters[t] *= sfactor
  4636. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4637. elif dim == 'tools_ncctools':
  4638. ncctools = []
  4639. try:
  4640. tools_string = self.defaults["tools_ncctools"].split(",")
  4641. ncctools = [eval(a) for a in tools_string if a != '']
  4642. except Exception as e:
  4643. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4644. self.options['tools_ncctools'] = ''
  4645. for t in range(len(ncctools)):
  4646. ncctools[t] *= sfactor
  4647. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4648. elif dim == 'tools_solderpaste_tools':
  4649. sptools = []
  4650. try:
  4651. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4652. sptools = [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.options['tools_solderpaste_tools'] = ""
  4656. for t in range(len(sptools)):
  4657. sptools[t] *= sfactor
  4658. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4659. elif dim == 'tools_solderpaste_xy_toolchange':
  4660. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4661. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4662. sp_coords[0] *= sfactor
  4663. sp_coords[1] *= sfactor
  4664. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4665. elif dim == 'global_gridx' or dim == 'global_gridy':
  4666. if new_units == 'IN':
  4667. val = 0.1
  4668. try:
  4669. val = float(self.defaults[dim]) * sfactor
  4670. except Exception as e:
  4671. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4672. self.options[dim] = float('%.6f' % val)
  4673. else:
  4674. val = 0.1
  4675. try:
  4676. val = float(self.defaults[dim]) * sfactor
  4677. except Exception as e:
  4678. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4679. self.options[dim] = float('%.4f' % val)
  4680. else:
  4681. val = 0.1
  4682. if self.options[dim]:
  4683. try:
  4684. val = float(self.options[dim]) * sfactor
  4685. except Exception as e:
  4686. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4687. self.options[dim] = val
  4688. def scale_defaults(sfactor):
  4689. for dim in dimensions:
  4690. if dim == 'excellon_toolchangexy':
  4691. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4692. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4693. coords_xy[0] *= sfactor
  4694. coords_xy[1] *= sfactor
  4695. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4696. elif dim == 'geometry_toolchangexy':
  4697. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4698. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4699. coords_xy[0] *= sfactor
  4700. coords_xy[1] *= sfactor
  4701. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4702. elif dim == 'geometry_cnctooldia':
  4703. tools_diameters = []
  4704. try:
  4705. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4706. tools_diameters = [eval(a) for a in tools_string if a != '']
  4707. except Exception as e:
  4708. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4709. self.defaults['geometry_cnctooldia'] = ''
  4710. for t in range(len(tools_diameters)):
  4711. tools_diameters[t] *= sfactor
  4712. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4713. elif dim == 'tools_ncctools':
  4714. ncctools = []
  4715. try:
  4716. tools_string = self.defaults["tools_ncctools"].split(",")
  4717. ncctools = [eval(a) for a in tools_string if a != '']
  4718. except Exception as e:
  4719. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4720. self.defaults['tools_ncctools'] = ''
  4721. for t in range(len(ncctools)):
  4722. ncctools[t] *= sfactor
  4723. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4724. elif dim == 'tools_solderpaste_tools':
  4725. sptools = []
  4726. try:
  4727. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4728. sptools = [eval(a) for a in tools_string if a != '']
  4729. except Exception as e:
  4730. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4731. self.defaults['tools_solderpaste_tools'] = ""
  4732. for t in range(len(sptools)):
  4733. sptools[t] *= sfactor
  4734. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4735. elif dim == 'tools_solderpaste_xy_toolchange':
  4736. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4737. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4738. sp_coords[0] *= sfactor
  4739. sp_coords[1] *= sfactor
  4740. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4741. elif dim == 'global_gridx' or dim == 'global_gridy':
  4742. if new_units == 'IN':
  4743. val = 0.1
  4744. try:
  4745. val = float(self.defaults[dim]) * sfactor
  4746. except Exception as e:
  4747. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4748. self.defaults[dim] = float('%.6f' % val)
  4749. else:
  4750. val = 0.1
  4751. try:
  4752. val = float(self.defaults[dim]) * sfactor
  4753. except Exception as e:
  4754. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4755. self.defaults[dim] = float('%.4f' % val)
  4756. else:
  4757. val = 0.1
  4758. if self.defaults[dim]:
  4759. try:
  4760. val = float(self.defaults[dim]) * sfactor
  4761. except Exception as e:
  4762. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4763. self.defaults[dim] = val
  4764. # The scaling factor depending on choice of units.
  4765. factor = 1/25.4
  4766. if new_units == 'MM':
  4767. factor = 25.4
  4768. # Changing project units. Warn user.
  4769. msgbox = QtWidgets.QMessageBox()
  4770. msgbox.setWindowTitle(_("Toggle Units"))
  4771. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4772. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4773. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4774. "properties of all objects to be scaled accordingly.\nContinue?"))
  4775. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4776. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4777. msgbox.setDefaultButton(bt_ok)
  4778. msgbox.exec_()
  4779. response = msgbox.clickedButton()
  4780. if response == bt_ok:
  4781. if no_pref is False:
  4782. self.options_read_form()
  4783. scale_options(factor)
  4784. self.options_write_form()
  4785. self.defaults_read_form()
  4786. scale_defaults(factor)
  4787. self.defaults_write_form(fl_units=new_units)
  4788. # save the defaults to file, some may assume that the conversion is enough and it's not
  4789. self.on_save_button()
  4790. self.should_we_save = True
  4791. # change this only if the workspace is active
  4792. if self.defaults['global_workspace'] is True:
  4793. self.plotcanvas.draw_workspace()
  4794. # adjust the grid values on the main toolbar
  4795. dec = 6 if new_units == 'IN'else 4
  4796. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4797. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4798. if not self.ui.grid_gap_link_cb.isChecked():
  4799. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4800. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4801. for obj in self.collection.get_list():
  4802. obj.convert_units(new_units)
  4803. # make that the properties stored in the object are also updated
  4804. self.object_changed.emit(obj)
  4805. obj.build_ui()
  4806. current = self.collection.get_active()
  4807. if current is not None:
  4808. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4809. if not isinstance(current, FlatCAMGeometry):
  4810. current.to_form()
  4811. self.plot_all()
  4812. self.inform.emit('[success] %s: %s' %
  4813. (_("Converted units to"), new_units))
  4814. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4815. self.set_screen_units(new_units)
  4816. else:
  4817. # Undo toggling
  4818. self.toggle_units_ignore = True
  4819. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4820. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4821. else:
  4822. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4823. self.toggle_units_ignore = False
  4824. self.inform.emit('[WARNING_NOTCL]%s' %
  4825. _(" Units conversion cancelled."))
  4826. self.options_read_form()
  4827. self.defaults_read_form()
  4828. def on_toggle_units_click(self):
  4829. try:
  4830. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4831. except (TypeError, AttributeError):
  4832. pass
  4833. if self.defaults["units"] == 'MM':
  4834. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4835. else:
  4836. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4837. self.on_toggle_units(no_pref=True)
  4838. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4839. lambda: self.on_toggle_units(no_pref=False))
  4840. def on_fullscreen(self, disable=False):
  4841. self.report_usage("on_fullscreen()")
  4842. if self.toggle_fscreen is False and disable is False:
  4843. # self.ui.showFullScreen()
  4844. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4845. a = self.ui.geometry()
  4846. self.x_pos = a.x()
  4847. self.y_pos = a.y()
  4848. self.width = a.width()
  4849. self.height = a.height()
  4850. # set new geometry to full desktop rect
  4851. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4852. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4853. # everything else will not work without this hack. This happen in Windows.
  4854. # https://bugreports.qt.io/browse/QTBUG-41309
  4855. desktop = QtWidgets.QApplication.desktop()
  4856. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4857. rec = desktop.screenGeometry(screen)
  4858. x = rec.x() - 1
  4859. y = rec.y() - 1
  4860. h = rec.height() + 2
  4861. w = rec.width() + 2
  4862. self.ui.setGeometry(x, y, w, h)
  4863. self.ui.show()
  4864. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4865. tb.setVisible(False)
  4866. self.ui.splitter_left.setVisible(False)
  4867. self.toggle_fscreen = True
  4868. elif self.toggle_fscreen is True or disable is True:
  4869. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4870. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4871. self.ui.showNormal()
  4872. self.restore_toolbar_view()
  4873. self.ui.splitter_left.setVisible(True)
  4874. self.toggle_fscreen = False
  4875. def on_toggle_plotarea(self):
  4876. self.report_usage("on_toggle_plotarea()")
  4877. try:
  4878. name = self.ui.plot_tab_area.widget(0).objectName()
  4879. except AttributeError:
  4880. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4881. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4882. self.ui.plot_tab_area.protectTab(0)
  4883. return
  4884. if name != 'plotarea':
  4885. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4886. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4887. self.ui.plot_tab_area.protectTab(0)
  4888. else:
  4889. self.ui.plot_tab_area.closeTab(0)
  4890. def on_toggle_notebook(self):
  4891. if self.ui.splitter.sizes()[0] == 0:
  4892. self.ui.splitter.setSizes([1, 1])
  4893. self.ui.menu_toggle_nb.setChecked(True)
  4894. else:
  4895. self.ui.splitter.setSizes([0, 1])
  4896. self.ui.menu_toggle_nb.setChecked(False)
  4897. def on_toggle_axis(self):
  4898. self.report_usage("on_toggle_axis()")
  4899. if self.toggle_axis is False:
  4900. if self.is_legacy is False:
  4901. # self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4902. # self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4903. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4904. parent=self.plotcanvas.view.scene)
  4905. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4906. parent=self.plotcanvas.view.scene)
  4907. # self.plotcanvas.redraw()
  4908. else:
  4909. self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4910. self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4911. self.plotcanvas.canvas.draw()
  4912. pass
  4913. self.toggle_axis = True
  4914. else:
  4915. if self.is_legacy is False:
  4916. # self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4917. # self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4918. # self.plotcanvas.redraw()
  4919. self.plotcanvas.v_line.parent = None
  4920. self.plotcanvas.h_line.parent = None
  4921. else:
  4922. self.plotcanvas.axes.lines[:] = []
  4923. self.plotcanvas.canvas.draw()
  4924. self.toggle_axis = False
  4925. def on_toggle_grid(self):
  4926. self.report_usage("on_toggle_grid()")
  4927. self.ui.grid_snap_btn.trigger()
  4928. def on_options_combo_change(self, sel):
  4929. """
  4930. Called when the combo box to choose between application defaults and
  4931. project option changes value. The corresponding variables are
  4932. copied to the UI.
  4933. :param sel: The option index that was chosen.
  4934. :return: None
  4935. """
  4936. # combo_sel = self.ui.notebook.combo_options.get_active()
  4937. App.log.debug("Options --> %s" % sel)
  4938. # form = [self.defaults_form, self.options_form][sel]
  4939. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4940. if sel == 0:
  4941. self.gen_form = self.ui.general_defaults_form
  4942. self.ger_form = self.ui.gerber_defaults_form
  4943. self.exc_form = self.ui.excellon_defaults_form
  4944. self.geo_form = self.ui.geometry_defaults_form
  4945. self.cnc_form = self.ui.cncjob_defaults_form
  4946. self.tools_form = self.ui.tools_defaults_form
  4947. self.fa_form = self.ui.util_defaults_form
  4948. elif sel == 1:
  4949. self.gen_form = self.ui.general_options_form
  4950. self.ger_form = self.ui.gerber_options_form
  4951. self.exc_form = self.ui.excellon_options_form
  4952. self.geo_form = self.ui.geometry_options_form
  4953. self.cnc_form = self.ui.cncjob_options_form
  4954. self.tools_form = self.ui.tools_options_form
  4955. self.fa_form = self.ui.util_options_form
  4956. else:
  4957. return
  4958. try:
  4959. self.ui.general_scroll_area.takeWidget()
  4960. except:
  4961. self.log.debug("Nothing to remove")
  4962. self.ui.general_scroll_area.setWidget(self.gen_form)
  4963. self.gen_form.show()
  4964. try:
  4965. self.ui.gerber_scroll_area.takeWidget()
  4966. except:
  4967. self.log.debug("Nothing to remove")
  4968. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4969. self.ger_form.show()
  4970. try:
  4971. self.ui.excellon_scroll_area.takeWidget()
  4972. except:
  4973. self.log.debug("Nothing to remove")
  4974. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4975. self.exc_form.show()
  4976. try:
  4977. self.ui.geometry_scroll_area.takeWidget()
  4978. except:
  4979. self.log.debug("Nothing to remove")
  4980. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4981. self.geo_form.show()
  4982. try:
  4983. self.ui.cncjob_scroll_area.takeWidget()
  4984. except:
  4985. self.log.debug("Nothing to remove")
  4986. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4987. self.cnc_form.show()
  4988. try:
  4989. self.ui.tools_scroll_area.takeWidget()
  4990. except:
  4991. self.log.debug("Nothing to remove")
  4992. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4993. self.tools_form.show()
  4994. try:
  4995. self.ui.fa_scroll_area.takeWidget()
  4996. except:
  4997. self.log.debug("Nothing to remove")
  4998. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4999. self.fa_form.show()
  5000. self.log.debug("Finished GUI form initialization.")
  5001. # self.options2form()
  5002. def on_excellon_defaults_button(self):
  5003. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  5004. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  5005. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  5006. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  5007. self.defaults_form_fields["excellon_zeros"].set_value('L')
  5008. self.defaults_form_fields["excellon_units"].set_value('INCH')
  5009. log.debug("Excellon app defaults loaded ...")
  5010. def on_excellon_options_button(self):
  5011. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  5012. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  5013. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  5014. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  5015. self.options_form_fields["excellon_zeros"].set_value('L')
  5016. self.options_form_fields["excellon_units"].set_value('INCH')
  5017. log.debug("Excellon options defaults loaded ...")
  5018. def on_update_exc_export(self, state):
  5019. """
  5020. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5021. if the update_excellon_cb checkbox is checked
  5022. :param state: state of the checkbox whose signals is tied to his slot
  5023. :return:
  5024. """
  5025. if state:
  5026. # first try to disconnect
  5027. try:
  5028. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.editingFinished.\
  5029. disconnect(self.on_excellon_format_changed)
  5030. except TypeError:
  5031. pass
  5032. try:
  5033. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.editingFinished.\
  5034. disconnect(self.on_excellon_format_changed)
  5035. except TypeError:
  5036. pass
  5037. try:
  5038. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.editingFinished.\
  5039. disconnect(self.on_excellon_format_changed)
  5040. except TypeError:
  5041. pass
  5042. try:
  5043. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.editingFinished.\
  5044. disconnect(self.on_excellon_format_changed)
  5045. except TypeError:
  5046. pass
  5047. try:
  5048. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5049. disconnect(self.on_excellon_zeros_changed)
  5050. except TypeError:
  5051. pass
  5052. try:
  5053. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5054. disconnect(self.on_excellon_zeros_changed)
  5055. except TypeError:
  5056. pass
  5057. # the connect them
  5058. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.editingFinished.connect(
  5059. self.on_excellon_format_changed)
  5060. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.editingFinished.connect(
  5061. self.on_excellon_format_changed)
  5062. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.editingFinished.connect(
  5063. self.on_excellon_format_changed)
  5064. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.editingFinished.connect(
  5065. self.on_excellon_format_changed)
  5066. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5067. self.on_excellon_zeros_changed)
  5068. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5069. self.on_excellon_units_changed)
  5070. else:
  5071. # disconnect the signals
  5072. try:
  5073. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.editingFinished. \
  5074. disconnect(self.on_excellon_format_changed)
  5075. except TypeError:
  5076. pass
  5077. try:
  5078. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.editingFinished. \
  5079. disconnect(self.on_excellon_format_changed)
  5080. except TypeError:
  5081. pass
  5082. try:
  5083. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.editingFinished. \
  5084. disconnect(self.on_excellon_format_changed)
  5085. except TypeError:
  5086. pass
  5087. try:
  5088. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.editingFinished. \
  5089. disconnect(self.on_excellon_format_changed)
  5090. except TypeError:
  5091. pass
  5092. try:
  5093. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5094. disconnect(self.on_excellon_zeros_changed)
  5095. except TypeError:
  5096. pass
  5097. try:
  5098. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5099. disconnect(self.on_excellon_zeros_changed)
  5100. except TypeError:
  5101. pass
  5102. def on_excellon_format_changed(self):
  5103. """
  5104. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5105. :return: None
  5106. """
  5107. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5108. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5109. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5110. )
  5111. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5112. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5113. )
  5114. else:
  5115. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5116. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5117. )
  5118. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5119. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5120. )
  5121. def on_excellon_zeros_changed(self):
  5122. """
  5123. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5124. :return: None
  5125. """
  5126. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5127. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5128. )
  5129. def on_excellon_units_changed(self):
  5130. """
  5131. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5132. :return: None
  5133. """
  5134. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5135. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5136. )
  5137. self.on_excellon_format_changed()
  5138. # Setting plot colors handlers
  5139. def on_pf_color_entry(self):
  5140. self.defaults['global_plot_fill'] = \
  5141. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5142. self.defaults['global_plot_fill'][7:9]
  5143. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5144. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5145. def on_pf_color_button(self):
  5146. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5147. c_dialog = QtWidgets.QColorDialog()
  5148. plot_fill_color = c_dialog.getColor(initial=current_color)
  5149. if plot_fill_color.isValid() is False:
  5150. return
  5151. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5152. "background-color:%s" % str(plot_fill_color.name()))
  5153. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5154. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5155. self.defaults['global_plot_fill'] = new_val
  5156. def on_pf_color_spinner(self):
  5157. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5158. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5159. self.defaults['global_plot_fill'] = \
  5160. self.defaults['global_plot_fill'][:7] + \
  5161. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5162. self.defaults['global_plot_line'] = \
  5163. self.defaults['global_plot_line'][:7] + \
  5164. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5165. def on_pf_color_slider(self):
  5166. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5167. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5168. def on_pl_color_entry(self):
  5169. self.defaults['global_plot_line'] = \
  5170. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5171. self.defaults['global_plot_line'][7:9]
  5172. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5173. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5174. def on_pl_color_button(self):
  5175. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5176. # print(current_color)
  5177. c_dialog = QtWidgets.QColorDialog()
  5178. plot_line_color = c_dialog.getColor(initial=current_color)
  5179. if plot_line_color.isValid() is False:
  5180. return
  5181. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5182. "background-color:%s" % str(plot_line_color.name()))
  5183. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5184. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5185. self.defaults['global_plot_line'] = new_val_line
  5186. # Setting selection colors (left - right) handlers
  5187. def on_sf_color_entry(self):
  5188. self.defaults['global_sel_fill'] = \
  5189. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5190. self.defaults['global_sel_fill'][7:9]
  5191. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5192. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5193. def on_sf_color_button(self):
  5194. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5195. c_dialog = QtWidgets.QColorDialog()
  5196. plot_fill_color = c_dialog.getColor(initial=current_color)
  5197. if plot_fill_color.isValid() is False:
  5198. return
  5199. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5200. "background-color:%s" % str(plot_fill_color.name()))
  5201. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5202. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5203. self.defaults['global_sel_fill'] = new_val
  5204. def on_sf_color_spinner(self):
  5205. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5206. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5207. self.defaults['global_sel_fill'] = \
  5208. self.defaults['global_sel_fill'][:7] + \
  5209. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5210. self.defaults['global_sel_line'] = \
  5211. self.defaults['global_sel_line'][:7] + \
  5212. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5213. def on_sf_color_slider(self):
  5214. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5215. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5216. def on_sl_color_entry(self):
  5217. self.defaults['global_sel_line'] = \
  5218. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5219. self.defaults['global_sel_line'][7:9]
  5220. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5221. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5222. def on_sl_color_button(self):
  5223. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5224. c_dialog = QtWidgets.QColorDialog()
  5225. plot_line_color = c_dialog.getColor(initial=current_color)
  5226. if plot_line_color.isValid() is False:
  5227. return
  5228. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5229. "background-color:%s" % str(plot_line_color.name()))
  5230. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5231. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5232. self.defaults['global_sel_line'] = new_val_line
  5233. # Setting selection colors (right - left) handlers
  5234. def on_alt_sf_color_entry(self):
  5235. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5236. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5237. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5238. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5239. def on_alt_sf_color_button(self):
  5240. current_color = QtGui.QColor(self.defaults['global_alt_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.alt_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_alt_sel_fill'][7:9])
  5248. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5249. self.defaults['global_alt_sel_fill'] = new_val
  5250. def on_alt_sf_color_spinner(self):
  5251. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5252. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5253. self.defaults['global_alt_sel_fill'] = \
  5254. self.defaults['global_alt_sel_fill'][:7] + \
  5255. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5256. self.defaults['global_alt_sel_line'] = \
  5257. self.defaults['global_alt_sel_line'][:7] + \
  5258. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5259. def on_alt_sf_color_slider(self):
  5260. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5261. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5262. def on_alt_sl_color_entry(self):
  5263. self.defaults['global_alt_sel_line'] = \
  5264. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5265. self.defaults['global_alt_sel_line'][7:9]
  5266. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5267. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5268. def on_alt_sl_color_button(self):
  5269. current_color = QtGui.QColor(self.defaults['global_alt_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.alt_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_alt_sel_line'][7:9])
  5277. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5278. self.defaults['global_alt_sel_line'] = new_val_line
  5279. # Setting Editor colors
  5280. def on_draw_color_entry(self):
  5281. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5282. .draw_color_entry.get_value()
  5283. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5284. "background-color:%s" % str(self.defaults['global_draw_color']))
  5285. def on_draw_color_button(self):
  5286. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5287. c_dialog = QtWidgets.QColorDialog()
  5288. draw_color = c_dialog.getColor(initial=current_color)
  5289. if draw_color.isValid() is False:
  5290. return
  5291. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5292. "background-color:%s" % str(draw_color.name()))
  5293. new_val = str(draw_color.name())
  5294. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5295. self.defaults['global_draw_color'] = new_val
  5296. def on_sel_draw_color_entry(self):
  5297. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5298. .sel_draw_color_entry.get_value()
  5299. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5300. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5301. def on_sel_draw_color_button(self):
  5302. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5303. c_dialog = QtWidgets.QColorDialog()
  5304. sel_draw_color = c_dialog.getColor(initial=current_color)
  5305. if sel_draw_color.isValid() is False:
  5306. return
  5307. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5308. "background-color:%s" % str(sel_draw_color.name()))
  5309. new_val_sel = str(sel_draw_color.name())
  5310. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5311. self.defaults['global_sel_draw_color'] = new_val_sel
  5312. def on_proj_color_entry(self):
  5313. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5314. .proj_color_entry.get_value()
  5315. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5316. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5317. def on_proj_color_button(self):
  5318. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5319. c_dialog = QtWidgets.QColorDialog()
  5320. proj_color = c_dialog.getColor(initial=current_color)
  5321. if proj_color.isValid() is False:
  5322. return
  5323. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5324. "background-color:%s" % str(proj_color.name()))
  5325. new_val_sel = str(proj_color.name())
  5326. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5327. self.defaults['global_proj_item_color'] = new_val_sel
  5328. def on_proj_color_dis_entry(self):
  5329. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5330. .proj_color_dis_entry.get_value()
  5331. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5332. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5333. def on_proj_color_dis_button(self):
  5334. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5335. c_dialog = QtWidgets.QColorDialog()
  5336. proj_color = c_dialog.getColor(initial=current_color)
  5337. if proj_color.isValid() is False:
  5338. return
  5339. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5340. "background-color:%s" % str(proj_color.name()))
  5341. new_val_sel = str(proj_color.name())
  5342. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5343. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5344. def on_annotation_fontcolor_entry(self):
  5345. self.defaults['cncjob_annotation_fontcolor'] = \
  5346. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5347. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5348. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5349. def on_annotation_fontcolor_button(self):
  5350. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5351. c_dialog = QtWidgets.QColorDialog()
  5352. annotation_color = c_dialog.getColor(initial=current_color)
  5353. if annotation_color.isValid() is False:
  5354. return
  5355. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5356. "background-color:%s" % str(annotation_color.name()))
  5357. new_val_sel = str(annotation_color.name())
  5358. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5359. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5360. def on_film_color_entry(self):
  5361. self.defaults['tools_film_color'] = \
  5362. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5363. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5364. "background-color:%s" % str(self.defaults['tools_film_color']))
  5365. def on_film_color_button(self):
  5366. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5367. c_dialog = QtWidgets.QColorDialog()
  5368. film_color = c_dialog.getColor(initial=current_color)
  5369. if film_color.isValid() is False:
  5370. return
  5371. # if new color is different then mark that the Preferences are changed
  5372. if film_color != current_color:
  5373. self.on_preferences_edited()
  5374. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5375. "background-color:%s" % str(film_color.name()))
  5376. new_val_sel = str(film_color.name())
  5377. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5378. self.defaults['tools_film_color'] = new_val_sel
  5379. def on_splash_changed(self, state):
  5380. settings = QSettings("Open Source", "FlatCAM")
  5381. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5382. # This will write the setting to the platform specific storage.
  5383. del settings
  5384. def on_notebook_tab_rmb_click(self, checked):
  5385. self.ui.notebook.set_detachable(val=checked)
  5386. self.defaults["global_tabs_detachable"] = checked
  5387. self.ui.plot_tab_area.set_detachable(val=checked)
  5388. self.defaults["global_tabs_detachable"] = checked
  5389. def on_deselect_all(self):
  5390. self.collection.set_all_inactive()
  5391. self.delete_selection_shape()
  5392. def on_workspace_modified(self):
  5393. self.save_defaults(silent=True)
  5394. self.plotcanvas.draw_workspace()
  5395. def on_workspace(self):
  5396. self.report_usage("on_workspace()")
  5397. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5398. self.plotcanvas.restore_workspace()
  5399. else:
  5400. self.plotcanvas.delete_workspace()
  5401. self.save_defaults(silent=True)
  5402. def on_workspace_menu(self):
  5403. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5404. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5405. else:
  5406. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5407. self.on_workspace()
  5408. def on_layout(self, index=None, lay=None):
  5409. """
  5410. Set the toolbars layout (location)
  5411. :param index:
  5412. :param lay: type of layout to be set on the toolbard
  5413. :return: None
  5414. """
  5415. self.report_usage("on_layout()")
  5416. if lay:
  5417. current_layout = lay
  5418. else:
  5419. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5420. settings = QSettings("Open Source", "FlatCAM")
  5421. settings.setValue('layout', current_layout)
  5422. # This will write the setting to the platform specific storage.
  5423. del settings
  5424. # first remove the toolbars:
  5425. try:
  5426. self.ui.removeToolBar(self.ui.toolbarfile)
  5427. self.ui.removeToolBar(self.ui.toolbargeo)
  5428. self.ui.removeToolBar(self.ui.toolbarview)
  5429. self.ui.removeToolBar(self.ui.toolbarshell)
  5430. self.ui.removeToolBar(self.ui.toolbartools)
  5431. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5432. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5433. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5434. self.ui.removeToolBar(self.ui.snap_toolbar)
  5435. self.ui.removeToolBar(self.ui.toolbarshell)
  5436. except Exception as e:
  5437. pass
  5438. if current_layout == 'standard':
  5439. # ## TOOLBAR INSTALLATION # ##
  5440. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5441. self.ui.toolbarfile.setObjectName('File_TB')
  5442. self.ui.addToolBar(self.ui.toolbarfile)
  5443. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5444. self.ui.toolbargeo.setObjectName('Edit_TB')
  5445. self.ui.addToolBar(self.ui.toolbargeo)
  5446. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5447. self.ui.toolbarview.setObjectName('View_TB')
  5448. self.ui.addToolBar(self.ui.toolbarview)
  5449. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5450. self.ui.toolbarshell.setObjectName('Shell_TB')
  5451. self.ui.addToolBar(self.ui.toolbarshell)
  5452. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5453. self.ui.toolbartools.setObjectName('Tools_TB')
  5454. self.ui.addToolBar(self.ui.toolbartools)
  5455. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5456. # self.ui.exc_edit_toolbar.setVisible(False)
  5457. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5458. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5459. self.ui.addToolBarBreak()
  5460. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5461. # self.ui.geo_edit_toolbar.setVisible(False)
  5462. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5463. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5464. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5465. # self.ui.grb_edit_toolbar.setVisible(False)
  5466. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5467. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5468. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5469. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5470. # self.ui.snap_toolbar.setMaximumHeight(30)
  5471. self.ui.addToolBar(self.ui.snap_toolbar)
  5472. self.ui.corner_snap_btn.setVisible(False)
  5473. self.ui.snap_magnet.setVisible(False)
  5474. elif current_layout == 'compact':
  5475. # ## TOOLBAR INSTALLATION # ##
  5476. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5477. self.ui.toolbarfile.setObjectName('File_TB')
  5478. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5479. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5480. self.ui.toolbargeo.setObjectName('Edit_TB')
  5481. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5482. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5483. self.ui.toolbarshell.setObjectName('Shell_TB')
  5484. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5485. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5486. self.ui.toolbartools.setObjectName('Tools_TB')
  5487. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5488. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5489. # self.ui.geo_edit_toolbar.setVisible(False)
  5490. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5491. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5492. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5493. self.ui.toolbarview.setObjectName('View_TB')
  5494. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5495. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5496. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5497. # self.ui.grb_edit_toolbar.setVisible(False)
  5498. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5499. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5500. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5501. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5502. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5503. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5504. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5505. self.ui.snap_toolbar.setMaximumHeight(30)
  5506. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5507. self.ui.corner_snap_btn.setVisible(True)
  5508. self.ui.snap_magnet.setVisible(True)
  5509. # add all the actions to the toolbars
  5510. self.ui.populate_toolbars()
  5511. # reconnect all the signals to the toolbar actions
  5512. self.connect_toolbar_signals()
  5513. self.ui.grid_snap_btn.setChecked(True)
  5514. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5515. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5516. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5517. self.ui.grid_gap_link_cb.setChecked(True)
  5518. def on_cursor_type(self, val):
  5519. """
  5520. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5521. :return: None
  5522. """
  5523. self.app_cursor.enabled = False
  5524. if val == 'small':
  5525. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5526. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5527. self.app_cursor = self.plotcanvas.new_cursor()
  5528. else:
  5529. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5530. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5531. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5532. if self.ui.grid_snap_btn.isChecked():
  5533. self.app_cursor.enabled = True
  5534. else:
  5535. self.app_cursor.enabled = False
  5536. def on_cnc_custom_parameters(self, signal_text):
  5537. if signal_text == 'Parameters':
  5538. return
  5539. else:
  5540. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5541. def on_save_button(self):
  5542. log.debug("App.on_save_button() --> Saving preferences to file.")
  5543. self.preferences_changed_flag = False
  5544. self.save_defaults(silent=False)
  5545. # load the defaults so they are updated into the app
  5546. self.load_defaults(filename='current_defaults')
  5547. # Re-fresh project options
  5548. self.on_options_app2project()
  5549. settings = QSettings("Open Source", "FlatCAM")
  5550. # save the notebook font size
  5551. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5552. settings.setValue('notebook_font_size', fsize)
  5553. # save the axis font size
  5554. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5555. settings.setValue('axis_font_size', g_fsize)
  5556. # save the textbox font size
  5557. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5558. settings.setValue('textbox_font_size', tb_fsize)
  5559. # This will write the setting to the platform specific storage.
  5560. del settings
  5561. def on_tool_add_keypress(self):
  5562. # ## Current application units in Upper Case
  5563. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5564. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5565. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5566. if notebook_widget_name == 'selected_tab':
  5567. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5568. # Tool add works for Geometry only if Advanced is True in Preferences
  5569. if self.defaults["global_app_level"] == 'a':
  5570. tool_add_popup = FCInputDialog(title="New Tool ...",
  5571. text='Enter a Tool Diameter:',
  5572. min=0.0000, max=99.9999, decimals=4)
  5573. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5574. val, ok = tool_add_popup.get_value()
  5575. if ok:
  5576. if float(val) == 0:
  5577. self.inform.emit('[WARNING_NOTCL] %s' %
  5578. _("Please enter a tool diameter with non-zero value, in Float format."))
  5579. return
  5580. self.collection.get_active().on_tool_add(dia=float(val))
  5581. else:
  5582. self.inform.emit('[WARNING_NOTCL] %s...' %
  5583. _("Adding Tool cancelled"))
  5584. else:
  5585. msgbox = QtWidgets.QMessageBox()
  5586. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5587. "Go to Preferences -> General - Show Advanced Options."))
  5588. msgbox.setWindowTitle("Tool adding ...")
  5589. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5590. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5591. msgbox.setDefaultButton(bt_ok)
  5592. msgbox.exec_()
  5593. # work only if the notebook tab on focus is the Tools_Tab
  5594. if notebook_widget_name == 'tool_tab':
  5595. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5596. # and only if the tool is NCC Tool
  5597. if tool_widget == self.ncclear_tool.toolName:
  5598. self.ncclear_tool.on_add_tool_by_key()
  5599. # and only if the tool is Paint Area Tool
  5600. elif tool_widget == self.paint_tool.toolName:
  5601. self.paint_tool.on_add_tool_by_key()
  5602. # and only if the tool is Solder Paste Dispensing Tool
  5603. elif tool_widget == self.paste_tool.toolName:
  5604. self.paste_tool.on_add_tool_by_key()
  5605. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5606. # See description bellow.
  5607. def on_delete_keypress(self):
  5608. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5609. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5610. if notebook_widget_name == 'selected_tab':
  5611. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5612. self.collection.get_active().on_tool_delete()
  5613. # work only if the notebook tab on focus is the Tools_Tab
  5614. elif notebook_widget_name == 'tool_tab':
  5615. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5616. # and only if the tool is NCC Tool
  5617. if tool_widget == self.ncclear_tool.toolName:
  5618. self.ncclear_tool.on_tool_delete()
  5619. # and only if the tool is Paint Tool
  5620. elif tool_widget == self.paint_tool.toolName:
  5621. self.paint_tool.on_tool_delete()
  5622. # and only if the tool is Solder Paste Dispensing Tool
  5623. elif tool_widget == self.paste_tool.toolName:
  5624. self.paste_tool.on_tool_delete()
  5625. else:
  5626. self.on_delete()
  5627. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5628. # some screens you have to be careful where you hover with your mouse.
  5629. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5630. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5631. # Complicated, I know :)
  5632. def on_delete(self):
  5633. """
  5634. Delete the currently selected FlatCAMObjs.
  5635. :return: None
  5636. """
  5637. self.report_usage("on_delete()")
  5638. response = None
  5639. bt_ok = None
  5640. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5641. # a geometry object before we update it.
  5642. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5643. and self.grb_editor.editor_active is False:
  5644. if self.defaults["global_delete_confirmation"] is True:
  5645. msgbox = QtWidgets.QMessageBox()
  5646. msgbox.setWindowTitle(_("Delete objects"))
  5647. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5648. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5649. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5650. "the selected objects?"))
  5651. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5652. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5653. msgbox.setDefaultButton(bt_ok)
  5654. msgbox.exec_()
  5655. response = msgbox.clickedButton()
  5656. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5657. if self.collection.get_active():
  5658. self.log.debug("App.on_delete()")
  5659. while self.collection.get_active():
  5660. obj_active = self.collection.get_active()
  5661. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5662. if isinstance(obj_active, FlatCAMGerber):
  5663. for el in obj_active.mark_shapes:
  5664. obj_active.mark_shapes[el].clear(update=True)
  5665. obj_active.mark_shapes[el].enabled = False
  5666. # obj_active.mark_shapes[el] = None
  5667. del el
  5668. elif isinstance(obj_active, FlatCAMCNCjob):
  5669. try:
  5670. obj_active.annotation.clear(update=True)
  5671. obj_active.annotation.enabled = False
  5672. except AttributeError:
  5673. pass
  5674. self.delete_first_selected()
  5675. self.inform.emit('%s...' %
  5676. _("Object(s) deleted"))
  5677. # make sure that the selection shape is deleted, too
  5678. self.delete_selection_shape()
  5679. else:
  5680. self.inform.emit(_("Failed. No object(s) selected..."))
  5681. else:
  5682. self.inform.emit(_("Save the work in Editor and try again ..."))
  5683. def delete_first_selected(self):
  5684. # Keep this for later
  5685. try:
  5686. sel_obj = self.collection.get_active()
  5687. name = sel_obj.options["name"]
  5688. isPlotted = sel_obj.options["plot"]
  5689. except AttributeError:
  5690. self.log.debug("Nothing selected for deletion")
  5691. return
  5692. if self.is_legacy is True:
  5693. # Remove plot only if the object was plotted otherwise delaxes will fail
  5694. if isPlotted:
  5695. try:
  5696. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5697. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5698. except Exception as e:
  5699. log.debug("App.delete_first_selected() --> %s" % str(e))
  5700. self.plotcanvas.auto_adjust_axes()
  5701. # Remove from dictionary
  5702. self.collection.delete_active()
  5703. # Clear form
  5704. self.setup_component_editor()
  5705. self.inform.emit('%s: %s' %
  5706. (_("Object deleted"), name))
  5707. def on_set_origin(self):
  5708. """
  5709. Set the origin to the left mouse click position
  5710. :return: None
  5711. """
  5712. # display the message for the user
  5713. # and ask him to click on the desired position
  5714. self.report_usage("on_set_origin()")
  5715. def origin_replot():
  5716. def worker_task():
  5717. with self.proc_container.new('%s...' % _("Plotting")):
  5718. for obj in self.collection.get_list():
  5719. obj.plot()
  5720. self.plotcanvas.fit_view()
  5721. if self.is_legacy:
  5722. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5723. else:
  5724. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5725. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5726. self.inform.emit(_('Click to set the origin ...'))
  5727. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5728. # first disconnect it as it may have been used by something else
  5729. try:
  5730. self.replot_signal.disconnect()
  5731. except TypeError:
  5732. pass
  5733. self.replot_signal[list].connect(origin_replot)
  5734. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  5735. """
  5736. :param event:
  5737. :param location:
  5738. :param noplot:
  5739. :param use_thread:
  5740. :return:
  5741. """
  5742. noplot_sig = noplot
  5743. def worker_task():
  5744. with self.proc_container.new(_("Setting Origin...")):
  5745. for obj in self.collection.get_list():
  5746. obj.offset((x, y))
  5747. self.object_changed.emit(obj)
  5748. # Update the object bounding box options
  5749. a, b, c, d = obj.bounds()
  5750. obj.options['xmin'] = a
  5751. obj.options['ymin'] = b
  5752. obj.options['xmax'] = c
  5753. obj.options['ymax'] = d
  5754. self.inform.emit('[success] %s...' %
  5755. _('Origin set'))
  5756. if noplot_sig is False:
  5757. self.replot_signal.emit([])
  5758. if location is not None:
  5759. if len(location) != 2:
  5760. self.inform.emit('[ERROR_NOTCL] %s...' %
  5761. _("Origin coordinates specified but incomplete."))
  5762. return 'fail'
  5763. x, y = location
  5764. if use_thread is True:
  5765. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5766. else:
  5767. worker_task()
  5768. self.should_we_save = True
  5769. return
  5770. if event.button == 1:
  5771. if self.is_legacy is False:
  5772. event_pos = event.pos
  5773. else:
  5774. event_pos = (event.xdata, event.ydata)
  5775. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5776. if self.grid_status() == True:
  5777. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5778. else:
  5779. pos = pos_canvas
  5780. x = 0 - pos[0]
  5781. y = 0 - pos[1]
  5782. if use_thread is True:
  5783. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5784. else:
  5785. worker_task()
  5786. self.should_we_save = True
  5787. def on_jump_to(self, custom_location=None, fit_center=True):
  5788. """
  5789. Jump to a location by setting the mouse cursor location
  5790. :return:
  5791. """
  5792. self.report_usage("on_jump_to()")
  5793. # if self.is_legacy is True:
  5794. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  5795. # return
  5796. if not custom_location:
  5797. dia_box_location = None
  5798. try:
  5799. dia_box_location = eval(self.clipboard.text())
  5800. except Exception as e:
  5801. pass
  5802. if type(dia_box_location) == tuple:
  5803. dia_box_location = str(dia_box_location)
  5804. else:
  5805. dia_box_location = None
  5806. dia_box = Dialog_box(title=_("Jump to ..."),
  5807. label=_("Enter the coordinates in format X,Y:"),
  5808. icon=QtGui.QIcon('share/jump_to16.png'),
  5809. initial_text=dia_box_location)
  5810. if dia_box.ok is True:
  5811. try:
  5812. location = eval(dia_box.location)
  5813. if not isinstance(location, tuple):
  5814. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5815. return
  5816. except:
  5817. return
  5818. else:
  5819. return
  5820. else:
  5821. location = custom_location
  5822. if fit_center:
  5823. self.plotcanvas.fit_center(loc=location)
  5824. cursor = QtGui.QCursor()
  5825. if self.is_legacy is False:
  5826. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5827. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5828. j_pos = (canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5829. cursor.setPos(j_pos[0], j_pos[1])
  5830. else:
  5831. # find the canvas origin which is in the top left corner
  5832. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5833. # determine the coordinates for the lowest left point of the canvas
  5834. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5835. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  5836. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  5837. # canvas) and the point (width, height) is in the top-right location
  5838. loc = self.plotcanvas.axes.transData.transform_point(location)
  5839. j_pos = (x0 + loc[0], y0 - loc[1])
  5840. cursor.setPos(j_pos[0], j_pos[1])
  5841. if self.grid_status() == True:
  5842. # Update cursor
  5843. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  5844. symbol='++', edge_color=self.cursor_color_3D,
  5845. size=self.defaults["global_cursor_size"])
  5846. # Set the position label
  5847. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5848. "<b>Y</b>: %.4f" % (location[0], location[1]))
  5849. # Set the relative position label
  5850. dx = location[0] - float(self.rel_point1[0])
  5851. dy = location[1] - float(self.rel_point1[1])
  5852. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5853. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5854. self.inform.emit('[success] %s' %
  5855. _("Done."))
  5856. return location
  5857. def on_copy_object(self):
  5858. self.report_usage("on_copy_object()")
  5859. def initialize(obj_init, app):
  5860. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5861. try:
  5862. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5863. except AttributeError:
  5864. pass
  5865. try:
  5866. obj_init.apertures = deepcopy(obj.apertures)
  5867. except AttributeError:
  5868. pass
  5869. try:
  5870. if obj.tools:
  5871. obj_init.tools = deepcopy(obj.tools)
  5872. except Exception as e:
  5873. log.debug("App.on_copy_object() --> %s" % str(e))
  5874. def initialize_excellon(obj_init, app):
  5875. obj_init.tools = deepcopy(obj.tools)
  5876. # drills are offset, so they need to be deep copied
  5877. obj_init.drills = deepcopy(obj.drills)
  5878. # slots are offset, so they need to be deep copied
  5879. obj_init.slots = deepcopy(obj.slots)
  5880. obj_init.create_geometry()
  5881. def initialize_script(obj_init, app_obj):
  5882. obj_init.source_file = deepcopy(obj.source_file)
  5883. def initialize_document(obj_init, app_obj):
  5884. obj_init.source_file = deepcopy(obj.source_file)
  5885. for obj in self.collection.get_selected():
  5886. obj_name = obj.options["name"]
  5887. try:
  5888. if isinstance(obj, FlatCAMExcellon):
  5889. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5890. elif isinstance(obj, FlatCAMGerber):
  5891. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5892. elif isinstance(obj, FlatCAMGeometry):
  5893. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5894. elif isinstance(obj, FlatCAMScript):
  5895. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  5896. elif isinstance(obj, FlatCAMDocument):
  5897. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  5898. except Exception as e:
  5899. return "Operation failed: %s" % str(e)
  5900. def on_copy_object2(self, custom_name):
  5901. def initialize_geometry(obj_init, app):
  5902. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5903. try:
  5904. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5905. except AttributeError:
  5906. pass
  5907. try:
  5908. obj_init.apertures = deepcopy(obj.apertures)
  5909. except AttributeError:
  5910. pass
  5911. try:
  5912. if obj.tools:
  5913. obj_init.tools = deepcopy(obj.tools)
  5914. except Exception as e:
  5915. log.debug("on_copy_object2() --> %s" % str(e))
  5916. def initialize_gerber(obj_init, app):
  5917. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5918. obj_init.apertures = deepcopy(obj.apertures)
  5919. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5920. def initialize_excellon(obj_init, app):
  5921. obj_init.tools = deepcopy(obj.tools)
  5922. # drills are offset, so they need to be deep copied
  5923. obj_init.drills = deepcopy(obj.drills)
  5924. # slots are offset, so they need to be deep copied
  5925. obj_init.slots = deepcopy(obj.slots)
  5926. obj_init.create_geometry()
  5927. for obj in self.collection.get_selected():
  5928. obj_name = obj.options["name"]
  5929. try:
  5930. if isinstance(obj, FlatCAMExcellon):
  5931. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5932. elif isinstance(obj, FlatCAMGerber):
  5933. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5934. elif isinstance(obj, FlatCAMGeometry):
  5935. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5936. except Exception as e:
  5937. return "Operation failed: %s" % str(e)
  5938. def on_rename_object(self, text):
  5939. self.report_usage("on_rename_object()")
  5940. named_obj = self.collection.get_active()
  5941. for obj in named_obj:
  5942. if obj is list:
  5943. self.on_rename_object(text)
  5944. else:
  5945. try:
  5946. obj.options['name'] = text
  5947. except Exception as e:
  5948. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5949. def convert_any2geo(self):
  5950. self.report_usage("convert_any2geo()")
  5951. def initialize(obj_init, app):
  5952. obj_init.solid_geometry = obj.solid_geometry
  5953. try:
  5954. obj_init.follow_geometry = obj.follow_geometry
  5955. except AttributeError:
  5956. pass
  5957. try:
  5958. obj_init.apertures = obj.apertures
  5959. except AttributeError:
  5960. pass
  5961. try:
  5962. if obj.tools:
  5963. obj_init.tools = obj.tools
  5964. except AttributeError:
  5965. pass
  5966. def initialize_excellon(obj_init, app):
  5967. # objs = self.collection.get_selected()
  5968. # FlatCAMGeometry.merge(objs, obj)
  5969. solid_geo = []
  5970. for tool in obj.tools:
  5971. for geo in obj.tools[tool]['solid_geometry']:
  5972. solid_geo.append(geo)
  5973. obj_init.solid_geometry = deepcopy(solid_geo)
  5974. if not self.collection.get_selected():
  5975. log.warning("App.convert_any2geo --> No object selected")
  5976. self.inform.emit('[WARNING_NOTCL] %s' %
  5977. _("No object is selected. Select an object and try again."))
  5978. return
  5979. for obj in self.collection.get_selected():
  5980. obj_name = obj.options["name"]
  5981. try:
  5982. if isinstance(obj, FlatCAMExcellon):
  5983. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5984. else:
  5985. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5986. except Exception as e:
  5987. return "Operation failed: %s" % str(e)
  5988. def convert_any2gerber(self):
  5989. self.report_usage("convert_any2gerber()")
  5990. def initialize_geometry(obj_init, app):
  5991. apertures = {}
  5992. apid = 0
  5993. apertures[str(apid)] = {}
  5994. apertures[str(apid)]['geometry'] = []
  5995. for obj_orig in obj.solid_geometry:
  5996. new_elem = dict()
  5997. new_elem['solid'] = obj_orig
  5998. new_elem['follow'] = obj_orig.exterior
  5999. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6000. apertures[str(apid)]['size'] = 0.0
  6001. apertures[str(apid)]['type'] = 'C'
  6002. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6003. obj_init.apertures = deepcopy(apertures)
  6004. def initialize_excellon(obj_init, app):
  6005. apertures = {}
  6006. apid = 10
  6007. for tool in obj.tools:
  6008. apertures[str(apid)] = {}
  6009. apertures[str(apid)]['geometry'] = []
  6010. for geo in obj.tools[tool]['solid_geometry']:
  6011. new_el = dict()
  6012. new_el['solid'] = geo
  6013. new_el['follow'] = geo.exterior
  6014. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6015. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6016. apertures[str(apid)]['type'] = 'C'
  6017. apid += 1
  6018. # create solid_geometry
  6019. solid_geometry = []
  6020. for apid in apertures:
  6021. for geo_el in apertures[apid]['geometry']:
  6022. solid_geometry.append(geo_el['solid'])
  6023. solid_geometry = MultiPolygon(solid_geometry)
  6024. solid_geometry = solid_geometry.buffer(0.0000001)
  6025. obj_init.solid_geometry = deepcopy(solid_geometry)
  6026. obj_init.apertures = deepcopy(apertures)
  6027. # clear the working objects (perhaps not necessary due of Python GC)
  6028. apertures.clear()
  6029. if not self.collection.get_selected():
  6030. log.warning("App.convert_any2gerber --> No object selected")
  6031. self.inform.emit('[WARNING_NOTCL] %s' %
  6032. _("No object is selected. Select an object and try again."))
  6033. return
  6034. for obj in self.collection.get_selected():
  6035. obj_name = obj.options["name"]
  6036. try:
  6037. if isinstance(obj, FlatCAMExcellon):
  6038. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6039. elif isinstance(obj, FlatCAMGeometry):
  6040. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6041. else:
  6042. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6043. except Exception as e:
  6044. return "Operation failed: %s" % str(e)
  6045. def abort_all_tasks(self):
  6046. if self.abort_flag is False:
  6047. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6048. self.abort_flag = True
  6049. def app_is_idle(self):
  6050. if self.abort_flag:
  6051. self.inform.emit('[WARNING_NOTCL] %s' %
  6052. _("The current task was gracefully closed on user request..."))
  6053. self.abort_flag = False
  6054. def on_selectall(self):
  6055. self.report_usage("on_selectall()")
  6056. # delete the possible selection box around a possible selected object
  6057. self.delete_selection_shape()
  6058. for name in self.collection.get_names():
  6059. self.collection.set_active(name)
  6060. curr_sel_obj = self.collection.get_by_name(name)
  6061. # create the selection box around the selected object
  6062. if self.defaults['global_selection_shape'] is True:
  6063. self.draw_selection_shape(curr_sel_obj)
  6064. def on_preferences(self):
  6065. # add the tab if it was closed
  6066. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6067. # delete the absolute and relative position and messages in the infobar
  6068. self.ui.position_label.setText("")
  6069. self.ui.rel_position_label.setText("")
  6070. # Switch plot_area to preferences page
  6071. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6072. # self.ui.show()
  6073. # detect changes in the preferences
  6074. for idx in range(self.ui.pref_tab_area.count()):
  6075. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6076. try:
  6077. try:
  6078. tb.textEdited.disconnect(self.on_preferences_edited)
  6079. except (TypeError, AttributeError):
  6080. pass
  6081. tb.textEdited.connect(self.on_preferences_edited)
  6082. except AttributeError:
  6083. pass
  6084. try:
  6085. try:
  6086. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6087. except (TypeError, AttributeError):
  6088. pass
  6089. tb.modificationChanged.connect(self.on_preferences_edited)
  6090. except AttributeError:
  6091. pass
  6092. try:
  6093. try:
  6094. tb.toggled.disconnect(self.on_preferences_edited)
  6095. except (TypeError, AttributeError):
  6096. pass
  6097. tb.toggled.connect(self.on_preferences_edited)
  6098. except AttributeError:
  6099. pass
  6100. try:
  6101. try:
  6102. tb.valueChanged.disconnect(self.on_preferences_edited)
  6103. except (TypeError, AttributeError):
  6104. pass
  6105. tb.valueChanged.connect(self.on_preferences_edited)
  6106. except AttributeError:
  6107. pass
  6108. try:
  6109. try:
  6110. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6111. except (TypeError, AttributeError):
  6112. pass
  6113. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6114. except AttributeError:
  6115. pass
  6116. def on_preferences_edited(self):
  6117. self.inform.emit('[WARNING_NOTCL] %s' %
  6118. _("Preferences edited but not saved."))
  6119. self.preferences_changed_flag = True
  6120. def on_plot_area_tab_closed(self, title):
  6121. if title == _("Preferences"):
  6122. # disconnect
  6123. for idx in range(self.ui.pref_tab_area.count()):
  6124. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6125. try:
  6126. tb.textEdited.disconnect(self.on_preferences_edited)
  6127. except (TypeError, AttributeError):
  6128. pass
  6129. try:
  6130. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6131. except (TypeError, AttributeError):
  6132. pass
  6133. try:
  6134. tb.toggled.disconnect(self.on_preferences_edited)
  6135. except (TypeError, AttributeError):
  6136. pass
  6137. try:
  6138. tb.valueChanged.disconnect(self.on_preferences_edited)
  6139. except (TypeError, AttributeError):
  6140. pass
  6141. try:
  6142. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6143. except (TypeError, AttributeError):
  6144. pass
  6145. if self.preferences_changed_flag is True:
  6146. msgbox = QtWidgets.QMessageBox()
  6147. msgbox.setText(_("One or more values are changed.\n"
  6148. "Do you want to save the Preferences?"))
  6149. msgbox.setWindowTitle(_("Save Preferences"))
  6150. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6151. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6152. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6153. msgbox.setDefaultButton(bt_yes)
  6154. msgbox.exec_()
  6155. response = msgbox.clickedButton()
  6156. if response == bt_yes:
  6157. self.on_save_button()
  6158. self.inform.emit('[success] %s' %
  6159. _("Preferences saved."))
  6160. else:
  6161. self.preferences_changed_flag = False
  6162. return
  6163. if title == _("Code Editor"):
  6164. self.toggle_codeeditor = False
  6165. def on_flipy(self):
  6166. self.report_usage("on_flipy()")
  6167. obj_list = self.collection.get_selected()
  6168. xminlist = []
  6169. yminlist = []
  6170. xmaxlist = []
  6171. ymaxlist = []
  6172. if not obj_list:
  6173. self.inform.emit('[WARNING_NOTCL] %s' %
  6174. _("No object selected to Flip on Y axis."))
  6175. else:
  6176. try:
  6177. # first get a bounding box to fit all
  6178. for obj in obj_list:
  6179. xmin, ymin, xmax, ymax = obj.bounds()
  6180. xminlist.append(xmin)
  6181. yminlist.append(ymin)
  6182. xmaxlist.append(xmax)
  6183. ymaxlist.append(ymax)
  6184. # get the minimum x,y and maximum x,y for all objects selected
  6185. xminimal = min(xminlist)
  6186. yminimal = min(yminlist)
  6187. xmaximal = max(xmaxlist)
  6188. ymaximal = max(ymaxlist)
  6189. px = 0.5 * (xminimal + xmaximal)
  6190. py = 0.5 * (yminimal + ymaximal)
  6191. # execute mirroring
  6192. for obj in obj_list:
  6193. obj.mirror('X', [px, py])
  6194. obj.plot()
  6195. self.object_changed.emit(obj)
  6196. self.inform.emit('[success] %s' %
  6197. _("Flip on Y axis done."))
  6198. except Exception as e:
  6199. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6200. (_("Flip action was not executed."), str(e)))
  6201. return
  6202. def on_flipx(self):
  6203. self.report_usage("on_flipx()")
  6204. obj_list = self.collection.get_selected()
  6205. xminlist = []
  6206. yminlist = []
  6207. xmaxlist = []
  6208. ymaxlist = []
  6209. if not obj_list:
  6210. self.inform.emit('[WARNING_NOTCL] %s' %
  6211. _("No object selected to Flip on X axis."))
  6212. else:
  6213. try:
  6214. # first get a bounding box to fit all
  6215. for obj in obj_list:
  6216. xmin, ymin, xmax, ymax = obj.bounds()
  6217. xminlist.append(xmin)
  6218. yminlist.append(ymin)
  6219. xmaxlist.append(xmax)
  6220. ymaxlist.append(ymax)
  6221. # get the minimum x,y and maximum x,y for all objects selected
  6222. xminimal = min(xminlist)
  6223. yminimal = min(yminlist)
  6224. xmaximal = max(xmaxlist)
  6225. ymaximal = max(ymaxlist)
  6226. px = 0.5 * (xminimal + xmaximal)
  6227. py = 0.5 * (yminimal + ymaximal)
  6228. # execute mirroring
  6229. for obj in obj_list:
  6230. obj.mirror('Y', [px, py])
  6231. obj.plot()
  6232. self.object_changed.emit(obj)
  6233. self.inform.emit('[success] %s' %
  6234. _("Flip on X axis done."))
  6235. except Exception as e:
  6236. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6237. (_("Flip action was not executed."), str(e)))
  6238. return
  6239. def on_rotate(self, silent=False, preset=None):
  6240. self.report_usage("on_rotate()")
  6241. obj_list = self.collection.get_selected()
  6242. xminlist = []
  6243. yminlist = []
  6244. xmaxlist = []
  6245. ymaxlist = []
  6246. if not obj_list:
  6247. self.inform.emit('[WARNING_NOTCL] %s' %
  6248. _("No object selected to Rotate."))
  6249. else:
  6250. if silent is False:
  6251. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6252. min=-360, max=360, decimals=4,
  6253. init_val=float(self.defaults['tools_transform_rotate']))
  6254. num, ok = rotatebox.get_value()
  6255. else:
  6256. num = preset
  6257. ok = True
  6258. if ok:
  6259. try:
  6260. # first get a bounding box to fit all
  6261. for obj in obj_list:
  6262. xmin, ymin, xmax, ymax = obj.bounds()
  6263. xminlist.append(xmin)
  6264. yminlist.append(ymin)
  6265. xmaxlist.append(xmax)
  6266. ymaxlist.append(ymax)
  6267. # get the minimum x,y and maximum x,y for all objects selected
  6268. xminimal = min(xminlist)
  6269. yminimal = min(yminlist)
  6270. xmaximal = max(xmaxlist)
  6271. ymaximal = max(ymaxlist)
  6272. px = 0.5 * (xminimal + xmaximal)
  6273. py = 0.5 * (yminimal + ymaximal)
  6274. for sel_obj in obj_list:
  6275. sel_obj.rotate(-float(num), point=(px, py))
  6276. sel_obj.plot()
  6277. self.object_changed.emit(sel_obj)
  6278. self.inform.emit('[success] %s' %
  6279. _("Rotation done."))
  6280. except Exception as e:
  6281. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6282. (_("Rotation movement was not executed."), str(e)))
  6283. return
  6284. def on_skewx(self):
  6285. self.report_usage("on_skewx()")
  6286. obj_list = self.collection.get_selected()
  6287. xminlist = []
  6288. yminlist = []
  6289. if not obj_list:
  6290. self.inform.emit('[WARNING_NOTCL] %s' %
  6291. _("No object selected to Skew/Shear on X axis."))
  6292. else:
  6293. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6294. min=-360, max=360, decimals=4,
  6295. init_val=float(self.defaults['tools_transform_skew_x']))
  6296. num, ok = skewxbox.get_value()
  6297. if ok:
  6298. # first get a bounding box to fit all
  6299. for obj in obj_list:
  6300. xmin, ymin, xmax, ymax = obj.bounds()
  6301. xminlist.append(xmin)
  6302. yminlist.append(ymin)
  6303. # get the minimum x,y and maximum x,y for all objects selected
  6304. xminimal = min(xminlist)
  6305. yminimal = min(yminlist)
  6306. for obj in obj_list:
  6307. obj.skew(num, 0, point=(xminimal, yminimal))
  6308. obj.plot()
  6309. self.object_changed.emit(obj)
  6310. self.inform.emit('[success] %s' %
  6311. _("Skew on X axis done."))
  6312. def on_skewy(self):
  6313. self.report_usage("on_skewy()")
  6314. obj_list = self.collection.get_selected()
  6315. xminlist = []
  6316. yminlist = []
  6317. if not obj_list:
  6318. self.inform.emit('[WARNING_NOTCL] %s' %
  6319. _("No object selected to Skew/Shear on Y axis."))
  6320. else:
  6321. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6322. min=-360, max=360, decimals=4,
  6323. init_val=float(self.defaults['tools_transform_skew_y']))
  6324. num, ok = skewybox.get_value()
  6325. if ok:
  6326. # first get a bounding box to fit all
  6327. for obj in obj_list:
  6328. xmin, ymin, xmax, ymax = obj.bounds()
  6329. xminlist.append(xmin)
  6330. yminlist.append(ymin)
  6331. # get the minimum x,y and maximum x,y for all objects selected
  6332. xminimal = min(xminlist)
  6333. yminimal = min(yminlist)
  6334. for obj in obj_list:
  6335. obj.skew(0, num, point=(xminimal, yminimal))
  6336. obj.plot()
  6337. self.object_changed.emit(obj)
  6338. self.inform.emit('[success] %s' %
  6339. _("Skew on Y axis done."))
  6340. def on_plots_updated(self):
  6341. """
  6342. Callback used to report when the plots have changed.
  6343. Adjust axes and zooms to fit.
  6344. :return: None
  6345. """
  6346. if self.is_legacy is False:
  6347. self.plotcanvas.update() # TODO: Need update canvas?
  6348. else:
  6349. self.plotcanvas.auto_adjust_axes()
  6350. self.on_zoom_fit(None)
  6351. self.collection.update_view()
  6352. # self.inform.emit(_("Plots updated ..."))
  6353. # TODO: Rework toolbar 'clear', 'replot' functions
  6354. def on_toolbar_replot(self):
  6355. """
  6356. Callback for toolbar button. Re-plots all objects.
  6357. :return: None
  6358. """
  6359. self.report_usage("on_toolbar_replot")
  6360. self.log.debug("on_toolbar_replot()")
  6361. try:
  6362. self.collection.get_active().read_form()
  6363. except AttributeError:
  6364. self.log.debug("on_toolbar_replot(): AttributeError")
  6365. pass
  6366. self.plot_all()
  6367. def on_row_activated(self, index):
  6368. if index.isValid():
  6369. if index.internalPointer().parent_item != self.collection.root_item:
  6370. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6371. self.collection.on_item_activated(index)
  6372. def on_collection_updated(self, obj, state, old_name):
  6373. """
  6374. Create a menu from the object loaded in the collection.
  6375. TODO: should use the collection model to do this
  6376. :param obj: object that was changd (added, deleted, renamed)
  6377. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6378. :param old_name: the old name of the object before the action that triggered this slot happened
  6379. :return: None
  6380. """
  6381. icon_files = {
  6382. "gerber": "share/flatcam_icon16.png",
  6383. "excellon": "share/drill16.png",
  6384. "cncjob": "share/cnc16.png",
  6385. "geometry": "share/geometry16.png",
  6386. "script": "share/script_new16.png",
  6387. "document": "share/notes16_1.png"
  6388. }
  6389. if state == 'append':
  6390. for act in self.ui.menuobjects.actions():
  6391. try:
  6392. act.triggered.disconnect()
  6393. except TypeError:
  6394. pass
  6395. self.ui.menuobjects.clear()
  6396. gerber_list = list()
  6397. exc_list = list()
  6398. cncjob_list = list()
  6399. geo_list = list()
  6400. script_list = list()
  6401. doc_list = list()
  6402. for name in self.collection.get_names():
  6403. obj_named = self.collection.get_by_name(name)
  6404. if obj_named.kind == 'gerber':
  6405. gerber_list.append(name)
  6406. elif obj_named.kind == 'excellon':
  6407. exc_list.append(name)
  6408. elif obj_named.kind == 'cncjob':
  6409. cncjob_list.append(name)
  6410. elif obj_named.kind == 'geometry':
  6411. geo_list.append(name)
  6412. elif obj_named.kind == 'script':
  6413. script_list.append(name)
  6414. elif obj_named.kind == 'document':
  6415. doc_list.append(name)
  6416. def add_act(name):
  6417. obj_for_icon = self.collection.get_by_name(name)
  6418. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6419. add_action.setText(name)
  6420. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6421. add_action.triggered.connect(lambda: self.collection.set_exclusive_active(name))
  6422. self.ui.menuobjects.addAction(add_action)
  6423. for name in gerber_list:
  6424. add_act(name)
  6425. self.ui.menuobjects.addSeparator()
  6426. for name in exc_list:
  6427. add_act(name)
  6428. self.ui.menuobjects.addSeparator()
  6429. for name in cncjob_list:
  6430. add_act(name)
  6431. self.ui.menuobjects.addSeparator()
  6432. for name in geo_list:
  6433. add_act(name)
  6434. self.ui.menuobjects.addSeparator()
  6435. for name in script_list:
  6436. add_act(name)
  6437. self.ui.menuobjects.addSeparator()
  6438. for name in doc_list:
  6439. add_act(name)
  6440. elif state == 'delete':
  6441. for act in self.ui.menuobjects.actions():
  6442. if act.text() == obj.options['name']:
  6443. try:
  6444. act.triggered.disconnect()
  6445. except TypeError:
  6446. pass
  6447. self.ui.menuobjects.removeAction(act)
  6448. break
  6449. elif state == 'rename':
  6450. for act in self.ui.menuobjects.actions():
  6451. if act.text() == old_name:
  6452. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6453. add_action.setText(obj.options['name'])
  6454. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6455. add_action.triggered.connect(lambda: self.collection.set_exclusive_active(obj.options['name']))
  6456. self.ui.menuobjects.insertAction(act, add_action)
  6457. try:
  6458. act.triggered.disconnect()
  6459. except TypeError:
  6460. pass
  6461. self.ui.menuobjects.removeAction(act)
  6462. break
  6463. elif state =='delete_all':
  6464. for act in self.ui.menuobjects.actions():
  6465. try:
  6466. act.triggered.disconnect()
  6467. except TypeError:
  6468. pass
  6469. self.ui.menuobjects.clear()
  6470. def grid_status(self):
  6471. if self.ui.grid_snap_btn.isChecked():
  6472. return True
  6473. else:
  6474. return False
  6475. def populate_cmenu_grids(self):
  6476. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6477. self.ui.cmenu_gridmenu.clear()
  6478. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6479. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6480. grid_toggle.setCheckable(True)
  6481. if self.grid_status() == True:
  6482. grid_toggle.setChecked(True)
  6483. else:
  6484. grid_toggle.setChecked(False)
  6485. self.ui.cmenu_gridmenu.addSeparator()
  6486. for grid in sorted_list:
  6487. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6488. action.triggered.connect(self.set_grid)
  6489. self.ui.cmenu_gridmenu.addSeparator()
  6490. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6491. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6492. grid_add.triggered.connect(self.on_grid_add)
  6493. grid_delete.triggered.connect(self.on_grid_delete)
  6494. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6495. def set_grid(self):
  6496. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6497. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6498. def on_grid_add(self):
  6499. # ## Current application units in lower Case
  6500. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6501. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6502. text=_('Enter a Grid Value:'),
  6503. min=0.0000, max=99.9999, decimals=4)
  6504. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6505. val, ok = grid_add_popup.get_value()
  6506. if ok:
  6507. if float(val) == 0:
  6508. self.inform.emit('[WARNING_NOTCL] %s' %
  6509. _("Please enter a grid value with non-zero value, in Float format."))
  6510. return
  6511. else:
  6512. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6513. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6514. self.inform.emit('[success] %s...' %
  6515. _("New Grid added"))
  6516. else:
  6517. self.inform.emit('[WARNING_NOTCL] %s...' %
  6518. _("Grid already exists"))
  6519. else:
  6520. self.inform.emit('[WARNING_NOTCL] %s...' %
  6521. _("Adding New Grid cancelled"))
  6522. def on_grid_delete(self):
  6523. # ## Current application units in lower Case
  6524. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6525. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6526. text='Enter a Grid Value:',
  6527. min=0.0000, max=99.9999, decimals=4)
  6528. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6529. val, ok = grid_del_popup.get_value()
  6530. if ok:
  6531. if float(val) == 0:
  6532. self.inform.emit('[WARNING_NOTCL] %s' %
  6533. _("Please enter a grid value with non-zero value, in Float format."))
  6534. return
  6535. else:
  6536. try:
  6537. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6538. except ValueError:
  6539. self.inform.emit('[ERROR_NOTCL]%s...' %
  6540. _(" Grid Value does not exist"))
  6541. return
  6542. self.inform.emit('[success] %s...' %
  6543. _("Grid Value deleted"))
  6544. else:
  6545. self.inform.emit('[WARNING_NOTCL] %s...' %
  6546. _("Delete Grid value cancelled"))
  6547. def on_shortcut_list(self):
  6548. self.report_usage("on_shortcut_list()")
  6549. # add the tab if it was closed
  6550. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6551. # delete the absolute and relative position and messages in the infobar
  6552. self.ui.position_label.setText("")
  6553. self.ui.rel_position_label.setText("")
  6554. # Switch plot_area to preferences page
  6555. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6556. # self.ui.show()
  6557. def on_select_tab(self, name):
  6558. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6559. if self.ui.splitter.sizes()[0] == 0:
  6560. self.ui.splitter.setSizes([1, 1])
  6561. else:
  6562. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6563. self.ui.splitter.setSizes([0, 1])
  6564. if name == 'project':
  6565. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6566. elif name == 'selected':
  6567. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6568. elif name == 'tool':
  6569. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6570. def on_copy_name(self):
  6571. self.report_usage("on_copy_name()")
  6572. obj = self.collection.get_active()
  6573. try:
  6574. name = obj.options["name"]
  6575. except AttributeError:
  6576. log.debug("on_copy_name() --> No object selected to copy it's name")
  6577. self.inform.emit('[WARNING_NOTCL]%s' %
  6578. _(" No object selected to copy it's name"))
  6579. return
  6580. self.clipboard.setText(name)
  6581. self.inform.emit(_("Name copied on clipboard ..."))
  6582. def on_mouse_click_over_plot(self, event):
  6583. """
  6584. Default actions are:
  6585. :param event: Contains information about the event, like which button
  6586. was clicked, the pixel coordinates and the axes coordinates.
  6587. :return: None
  6588. """
  6589. self.pos = []
  6590. if self.is_legacy is False:
  6591. event_pos = event.pos
  6592. if self.defaults["global_pan_button"] == '2':
  6593. pan_button = 2
  6594. else:
  6595. pan_button = 3
  6596. # Set the mouse button for panning
  6597. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6598. else:
  6599. event_pos = (event.xdata, event.ydata)
  6600. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6601. if self.defaults["global_pan_button"] == '2':
  6602. pan_button = 3
  6603. else:
  6604. pan_button = 2
  6605. # So it can receive key presses
  6606. self.plotcanvas.native.setFocus()
  6607. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6608. if self.grid_status() == True:
  6609. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6610. else:
  6611. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6612. try:
  6613. if event.button == 1:
  6614. # Reset here the relative coordinates so there is a new reference on the click position
  6615. if self.rel_point1 is None:
  6616. self.rel_point1 = self.pos
  6617. else:
  6618. self.rel_point2 = copy(self.rel_point1)
  6619. self.rel_point1 = self.pos
  6620. self.on_mouse_move_over_plot(event, origin_click=True)
  6621. except Exception as e:
  6622. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6623. def on_double_click_over_plot(self, event):
  6624. if event.button == 1:
  6625. self.doubleclick = True
  6626. def on_mouse_move_over_plot(self, event, origin_click=None):
  6627. """
  6628. Callback for the mouse motion event over the plot.
  6629. :param event: Contains information about the event.
  6630. :param origin_click
  6631. :return: None
  6632. """
  6633. if self.is_legacy is False:
  6634. event_pos = event.pos
  6635. if self.defaults["global_pan_button"] == '2':
  6636. pan_button = 2
  6637. else:
  6638. pan_button = 3
  6639. event_is_dragging = event.is_dragging
  6640. else:
  6641. event_pos = (event.xdata, event.ydata)
  6642. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6643. if self.defaults["global_pan_button"] == '2':
  6644. pan_button = 3
  6645. else:
  6646. pan_button = 2
  6647. event_is_dragging = self.plotcanvas.is_dragging
  6648. # So it can receive key presses
  6649. self.plotcanvas.native.setFocus()
  6650. self.pos_jump = event_pos
  6651. self.ui.popMenu.mouse_is_panning = False
  6652. if not origin_click:
  6653. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6654. if event.button == pan_button and event_is_dragging == 1:
  6655. self.ui.popMenu.mouse_is_panning = True
  6656. return
  6657. if self.rel_point1 is not None:
  6658. try: # May fail in case mouse not within axes
  6659. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6660. if self.grid_status() == True:
  6661. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6662. # Update cursor
  6663. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6664. symbol='++', edge_color=self.cursor_color_3D,
  6665. size=self.defaults["global_cursor_size"])
  6666. else:
  6667. pos = (pos_canvas[0], pos_canvas[1])
  6668. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6669. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6670. dx = pos[0] - float(self.rel_point1[0])
  6671. dy = pos[1] - float(self.rel_point1[1])
  6672. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6673. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6674. self.mouse = [pos[0], pos[1]]
  6675. # if the mouse is moved and the LMB is clicked then the action is a selection
  6676. if event_is_dragging == 1 and event.button == 1:
  6677. self.delete_selection_shape()
  6678. if dx < 0:
  6679. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6680. face_color=self.defaults['global_alt_sel_fill'])
  6681. self.selection_type = False
  6682. elif dx > 0:
  6683. self.draw_moving_selection_shape(self.pos, pos)
  6684. self.selection_type = True
  6685. else:
  6686. self.selection_type = None
  6687. # hover effect - enabled in Preferences -> General -> GUI Settings
  6688. if self.defaults['global_hover']:
  6689. for obj in self.collection.get_list():
  6690. try:
  6691. # select the object(s) only if it is enabled (plotted)
  6692. if obj.options['plot']:
  6693. if obj not in self.collection.get_selected():
  6694. poly_obj = Polygon(
  6695. [(obj.options['xmin'], obj.options['ymin']),
  6696. (obj.options['xmax'], obj.options['ymin']),
  6697. (obj.options['xmax'], obj.options['ymax']),
  6698. (obj.options['xmin'], obj.options['ymax'])]
  6699. )
  6700. if Point(pos).within(poly_obj):
  6701. if obj.isHovering is False:
  6702. obj.isHovering = True
  6703. obj.notHovering = True
  6704. # create the selection box around the selected object
  6705. self.draw_hover_shape(obj, color='#d1e0e0FF')
  6706. else:
  6707. if obj.notHovering is True:
  6708. obj.notHovering = False
  6709. obj.isHovering = False
  6710. self.delete_hover_shape()
  6711. except:
  6712. # the Exception here will happen if we try to select on screen and we have an
  6713. # newly (and empty) just created Geometry or Excellon object that do not have the
  6714. # xmin, xmax, ymin, ymax options.
  6715. # In this case poly_obj creation (see above) will fail
  6716. pass
  6717. except:
  6718. self.ui.position_label.setText("")
  6719. self.ui.rel_position_label.setText("")
  6720. self.mouse = None
  6721. def on_mouse_click_release_over_plot(self, event):
  6722. """
  6723. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6724. and has been registered in ''self.__init__()''.
  6725. :param event: contains information about the event.
  6726. :return:
  6727. """
  6728. pos = 0, 0
  6729. if self.is_legacy is False:
  6730. event_pos = event.pos
  6731. right_button = 2
  6732. else:
  6733. event_pos = (event.xdata, event.ydata)
  6734. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6735. right_button = 3
  6736. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6737. if self.grid_status() == True:
  6738. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6739. else:
  6740. pos = (pos_canvas[0], pos_canvas[1])
  6741. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6742. # canvas menu
  6743. if event.button == right_button: # right click
  6744. if self.ui.popMenu.mouse_is_panning is False:
  6745. self.cursor = QtGui.QCursor()
  6746. self.populate_cmenu_grids()
  6747. self.ui.popMenu.popup(self.cursor.pos())
  6748. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6749. # selection and then select a type of selection ("enclosing" or "touching")
  6750. try:
  6751. if event.button == 1: # left click
  6752. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6753. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6754. if modifiers == QtCore.Qt.ShiftModifier:
  6755. # do not auto open the Project Tab
  6756. self.click_noproject = True
  6757. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6758. self.inform.emit('[success] %s' %
  6759. _("Coordinates copied to clipboard."))
  6760. return
  6761. if self.doubleclick is True:
  6762. self.doubleclick = False
  6763. if self.collection.get_selected():
  6764. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6765. if self.ui.splitter.sizes()[0] == 0:
  6766. self.ui.splitter.setSizes([1, 1])
  6767. # delete the selection shape(S) as it may be in the way
  6768. self.delete_selection_shape()
  6769. self.delete_hover_shape()
  6770. else:
  6771. if self.selection_type is not None:
  6772. self.selection_area_handler(self.pos, pos, self.selection_type)
  6773. self.selection_type = None
  6774. else:
  6775. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6776. if key_modifier == QtCore.Qt.ShiftModifier:
  6777. mod_key = 'Shift'
  6778. elif key_modifier == QtCore.Qt.ControlModifier:
  6779. mod_key = 'Control'
  6780. else:
  6781. mod_key = None
  6782. if mod_key == self.defaults["global_mselect_key"]:
  6783. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6784. # deselect, and if it's not selected then it will be selected
  6785. # If there is no active command (self.command_active is None) then we check if we clicked
  6786. # on a object by checking the bounding limits against mouse click position
  6787. if self.command_active is None:
  6788. self.select_objects(key='CTRL')
  6789. self.delete_hover_shape()
  6790. else:
  6791. # If there is no active command (self.command_active is None) then we check if we clicked
  6792. # on a object by checking the bounding limits against mouse click position
  6793. if self.command_active is None:
  6794. self.select_objects()
  6795. self.delete_hover_shape()
  6796. except Exception as e:
  6797. log.warning("Error: %s" % str(e))
  6798. return
  6799. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6800. """
  6801. :param start_pos: mouse position when the selection LMB click was done
  6802. :param end_pos: mouse position when the left mouse button is released
  6803. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6804. :return:
  6805. """
  6806. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6807. self.delete_selection_shape()
  6808. for obj in self.collection.get_list():
  6809. try:
  6810. # select the object(s) only if it is enabled (plotted)
  6811. if obj.options['plot']:
  6812. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6813. (obj.options['xmax'], obj.options['ymin']),
  6814. (obj.options['xmax'], obj.options['ymax']),
  6815. (obj.options['xmin'], obj.options['ymax'])])
  6816. if sel_type is True:
  6817. if poly_obj.within(poly_selection):
  6818. # create the selection box around the selected object
  6819. if self.defaults['global_selection_shape'] is True:
  6820. self.draw_selection_shape(obj)
  6821. self.collection.set_active(obj.options['name'])
  6822. else:
  6823. if poly_selection.intersects(poly_obj):
  6824. # create the selection box around the selected object
  6825. if self.defaults['global_selection_shape'] is True:
  6826. self.draw_selection_shape(obj)
  6827. self.collection.set_active(obj.options['name'])
  6828. except Exception as e:
  6829. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6830. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6831. # In this case poly_obj creation (see above) will fail
  6832. log.debug("App.selection_area_handler() --> %s" % str(e))
  6833. def select_objects(self, key=None):
  6834. # list where we store the overlapped objects under our mouse left click position
  6835. objects_under_the_click_list = []
  6836. # Populate the list with the overlapped objects on the click position
  6837. curr_x, curr_y = self.pos
  6838. for obj in self.all_objects_list:
  6839. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6840. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6841. if obj.options['name'] not in objects_under_the_click_list:
  6842. if obj.options['plot']:
  6843. # add objects to the objects_under_the_click list only if the object is plotted
  6844. # (active and not disabled)
  6845. objects_under_the_click_list.append(obj.options['name'])
  6846. try:
  6847. # If there is no element in the overlapped objects list then make everyone inactive
  6848. # because we selected "nothing"
  6849. if not objects_under_the_click_list:
  6850. self.collection.set_all_inactive()
  6851. # delete the possible selection box around a possible selected object
  6852. self.delete_selection_shape()
  6853. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6854. # only when working on App
  6855. if self.call_source == 'app':
  6856. if self.click_noproject is False:
  6857. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6858. else:
  6859. # restore auto open the Project Tab
  6860. self.click_noproject = False
  6861. # delete any text in the status bar, implicitly the last object name that was selected
  6862. self.inform.emit("")
  6863. else:
  6864. self.call_source = 'app'
  6865. else:
  6866. # case when there is only an object under the click and we toggle it
  6867. if len(objects_under_the_click_list) == 1:
  6868. if self.collection.get_active() is None:
  6869. self.collection.set_active(objects_under_the_click_list[0])
  6870. # create the selection box around the selected object
  6871. curr_sel_obj = self.collection.get_active()
  6872. if self.defaults['global_selection_shape'] is True:
  6873. self.draw_selection_shape(curr_sel_obj)
  6874. # self.inform.emit('[selected] %s: %s selected' %
  6875. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6876. if curr_sel_obj.kind == 'gerber':
  6877. self.inform.emit(
  6878. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6879. color='green', name=str(curr_sel_obj.options['name'])))
  6880. elif curr_sel_obj.kind == 'excellon':
  6881. self.inform.emit(
  6882. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6883. color='brown', name=str(curr_sel_obj.options['name'])))
  6884. elif curr_sel_obj.kind == 'cncjob':
  6885. self.inform.emit(
  6886. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6887. color='blue', name=str(curr_sel_obj.options['name'])))
  6888. elif curr_sel_obj.kind == 'geometry':
  6889. self.inform.emit(
  6890. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6891. color='red', name=str(curr_sel_obj.options['name'])))
  6892. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6893. self.collection.set_all_inactive()
  6894. self.delete_selection_shape()
  6895. self.collection.set_active(objects_under_the_click_list[0])
  6896. # create the selection box around the selected object
  6897. curr_sel_obj = self.collection.get_active()
  6898. if self.defaults['global_selection_shape'] is True:
  6899. self.draw_selection_shape(curr_sel_obj)
  6900. # self.inform.emit('[selected] %s: %s selected' %
  6901. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6902. if curr_sel_obj.kind == 'gerber':
  6903. self.inform.emit(
  6904. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6905. color='green', name=str(curr_sel_obj.options['name'])))
  6906. elif curr_sel_obj.kind == 'excellon':
  6907. self.inform.emit(
  6908. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6909. color='brown', name=str(curr_sel_obj.options['name'])))
  6910. elif curr_sel_obj.kind == 'cncjob':
  6911. self.inform.emit(
  6912. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6913. color='blue', name=str(curr_sel_obj.options['name'])))
  6914. elif curr_sel_obj.kind == 'geometry':
  6915. self.inform.emit(
  6916. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6917. color='red', name=str(curr_sel_obj.options['name'])))
  6918. else:
  6919. self.collection.set_all_inactive()
  6920. self.delete_selection_shape()
  6921. if self.call_source == 'app':
  6922. # delete any text in the status bar, implicitly the last object name that was selected
  6923. self.inform.emit("")
  6924. else:
  6925. self.call_source = 'app'
  6926. else:
  6927. # If there is no selected object
  6928. # make active the first element of the overlapped objects list
  6929. if self.collection.get_active() is None:
  6930. self.collection.set_active(objects_under_the_click_list[0])
  6931. name_sel_obj = self.collection.get_active().options['name']
  6932. # In case that there is a selected object but it is not in the overlapped object list
  6933. # make that object inactive and activate the first element in the overlapped object list
  6934. if name_sel_obj not in objects_under_the_click_list:
  6935. self.collection.set_inactive(name_sel_obj)
  6936. name_sel_obj = objects_under_the_click_list[0]
  6937. self.collection.set_active(name_sel_obj)
  6938. else:
  6939. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6940. self.collection.set_all_inactive()
  6941. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6942. len(objects_under_the_click_list)])
  6943. curr_sel_obj = self.collection.get_active()
  6944. # delete the possible selection box around a possible selected object
  6945. self.delete_selection_shape()
  6946. # create the selection box around the selected object
  6947. if self.defaults['global_selection_shape'] is True:
  6948. self.draw_selection_shape(curr_sel_obj)
  6949. # self.inform.emit('[selected] %s: %s selected' %
  6950. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6951. if curr_sel_obj.kind == 'gerber':
  6952. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6953. color='green', name=str(curr_sel_obj.options['name'])))
  6954. elif curr_sel_obj.kind == 'excellon':
  6955. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6956. color='brown', name=str(curr_sel_obj.options['name'])))
  6957. elif curr_sel_obj.kind == 'cncjob':
  6958. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6959. color='blue', name=str(curr_sel_obj.options['name'])))
  6960. elif curr_sel_obj.kind == 'geometry':
  6961. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6962. color='red', name=str(curr_sel_obj.options['name'])))
  6963. # for obj in self.collection.get_list():
  6964. # obj.plot()
  6965. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6966. # TODO: on selected objects change the object colors and do not draw the selection box
  6967. # self.plotcanvas.update() # this updates the canvas
  6968. except Exception as e:
  6969. log.error("[ERROR] Something went bad. %s" % str(e))
  6970. return
  6971. def delete_hover_shape(self):
  6972. self.hover_shapes.clear()
  6973. self.hover_shapes.redraw()
  6974. def draw_hover_shape(self, sel_obj, color=None):
  6975. """
  6976. :param sel_obj: the object for which the hover shape must be drawn
  6977. :return:
  6978. """
  6979. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6980. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6981. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6982. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6983. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6984. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6985. hover_rect = hover_rect.buffer(-0.1)
  6986. hover_rect = hover_rect.buffer(0.2)
  6987. else:
  6988. hover_rect = hover_rect.buffer(-0.00393)
  6989. hover_rect = hover_rect.buffer(0.00787)
  6990. # if color:
  6991. # face = Color(color)
  6992. # face.alpha = 0.2
  6993. # outline = Color(color, alpha=0.8)
  6994. # else:
  6995. # face = Color(self.defaults['global_sel_fill'])
  6996. # face.alpha = 0.2
  6997. # outline = self.defaults['global_sel_line']
  6998. if color:
  6999. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7000. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7001. else:
  7002. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7003. outline = self.defaults['global_sel_line']
  7004. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7005. if self.is_legacy is True:
  7006. self.hover_shapes.redraw()
  7007. def delete_selection_shape(self):
  7008. self.move_tool.sel_shapes.clear()
  7009. self.move_tool.sel_shapes.redraw()
  7010. def draw_selection_shape(self, sel_obj, color=None):
  7011. """
  7012. :param sel_obj: the object for which the selection shape must be drawn
  7013. :return:
  7014. """
  7015. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7016. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7017. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7018. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7019. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7020. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  7021. sel_rect = sel_rect.buffer(-0.1)
  7022. sel_rect = sel_rect.buffer(0.2)
  7023. else:
  7024. sel_rect = sel_rect.buffer(-0.00393)
  7025. sel_rect = sel_rect.buffer(0.00787)
  7026. # if color:
  7027. # face = Color(color, alpha=0.2)
  7028. # outline = Color(color, alpha=0.8)
  7029. # else:
  7030. # face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  7031. # outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  7032. if color:
  7033. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7034. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7035. else:
  7036. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7037. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7038. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7039. color=outline,
  7040. face_color=face,
  7041. update=True,
  7042. layer=0,
  7043. tolerance=None))
  7044. if self.is_legacy is True:
  7045. self.move_tool.sel_shapes.redraw()
  7046. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7047. """
  7048. :param old_coords: old coordinates
  7049. :param coords: new coordinates
  7050. :return:
  7051. """
  7052. if 'color' in kwargs:
  7053. color = kwargs['color']
  7054. else:
  7055. color = self.defaults['global_sel_line']
  7056. if 'face_color' in kwargs:
  7057. face_color = kwargs['face_color']
  7058. else:
  7059. face_color = self.defaults['global_sel_fill']
  7060. if 'face_alpha' in kwargs:
  7061. face_alpha = kwargs['face_alpha']
  7062. else:
  7063. face_alpha = 0.3
  7064. x0, y0 = old_coords
  7065. x1, y1 = coords
  7066. pt1 = (x0, y0)
  7067. pt2 = (x1, y0)
  7068. pt3 = (x1, y1)
  7069. pt4 = (x0, y1)
  7070. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7071. # color_t = Color(face_color)
  7072. # color_t.alpha = face_alpha
  7073. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7074. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7075. layer=0, tolerance=None)
  7076. if self.is_legacy is True:
  7077. self.move_tool.sel_shapes.redraw()
  7078. def on_file_new_click(self):
  7079. if self.collection.get_list() and self.should_we_save:
  7080. msgbox = QtWidgets.QMessageBox()
  7081. # msgbox.setText("<B>Save changes ...</B>")
  7082. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7083. "Creating a New project will delete them.\n"
  7084. "Do you want to Save the project?"))
  7085. msgbox.setWindowTitle(_("Save changes"))
  7086. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7087. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7088. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7089. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7090. msgbox.setDefaultButton(bt_yes)
  7091. msgbox.exec_()
  7092. response = msgbox.clickedButton()
  7093. if response == bt_yes:
  7094. self.on_file_saveprojectas()
  7095. elif response == bt_cancel:
  7096. return
  7097. elif response == bt_no:
  7098. self.on_file_new()
  7099. else:
  7100. self.on_file_new()
  7101. self.inform.emit('[success] %s...' %
  7102. _("New Project created"))
  7103. def on_file_new(self, cli=None):
  7104. """
  7105. Callback for menu item File->New. Returns the application to its
  7106. startup state. This method is thread-safe.
  7107. :return: None
  7108. """
  7109. self.report_usage("on_file_new")
  7110. # Remove everything from memory
  7111. App.log.debug("on_file_new()")
  7112. if self.call_source != 'app':
  7113. self.editor2object(cleanup=True)
  7114. # ## EDITOR section
  7115. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7116. self.exc_editor = FlatCAMExcEditor(self)
  7117. self.grb_editor = FlatCAMGrbEditor(self)
  7118. # Clear pool
  7119. self.clear_pool()
  7120. for obj in self.collection.get_list():
  7121. # delete shapes left drawn from mark shape_collections, if any
  7122. if isinstance(obj, FlatCAMGerber):
  7123. try:
  7124. obj.mark_shapes.enabled = False
  7125. obj.mark_shapes.clear(update=True)
  7126. except AttributeError:
  7127. pass
  7128. # also delete annotation shapes, if any
  7129. elif isinstance(obj, FlatCAMCNCjob):
  7130. try:
  7131. obj.annotation.enabled = False
  7132. obj.annotation.clear(update=True)
  7133. except AttributeError:
  7134. pass
  7135. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7136. self.init_tcl()
  7137. self.delete_selection_shape()
  7138. self.collection.delete_all()
  7139. self.setup_component_editor()
  7140. # Clear project filename
  7141. self.project_filename = None
  7142. # Load the application defaults
  7143. self.load_defaults(filename='current_defaults')
  7144. # Re-fresh project options
  7145. self.on_options_app2project()
  7146. # Init Tools
  7147. self.init_tools()
  7148. if cli is None:
  7149. # Close any Tabs opened in the Plot Tab Area section
  7150. for index in range(self.ui.plot_tab_area.count()):
  7151. self.ui.plot_tab_area.closeTab(index)
  7152. # for whatever reason previous command does not close the last tab so I do it manually
  7153. self.ui.plot_tab_area.closeTab(0)
  7154. # # And then add again the Plot Area
  7155. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7156. self.ui.plot_tab_area.protectTab(0)
  7157. # take the focus of the Notebook on Project Tab.
  7158. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7159. self.set_ui_title(name=_("New Project - Not saved"))
  7160. def obj_properties(self):
  7161. self.report_usage("obj_properties()")
  7162. self.properties_tool.run(toggle=False)
  7163. def on_project_context_save(self):
  7164. obj = self.collection.get_active()
  7165. if type(obj) == FlatCAMGeometry:
  7166. self.on_file_exportdxf()
  7167. elif type(obj) == FlatCAMExcellon:
  7168. self.on_file_saveexcellon()
  7169. elif type(obj) == FlatCAMCNCjob:
  7170. obj.on_exportgcode_button_click()
  7171. elif type(obj) == FlatCAMGerber:
  7172. self.on_file_savegerber()
  7173. elif type(obj) == FlatCAMScript:
  7174. self.on_file_savescript()
  7175. elif type(obj) == FlatCAMDocument:
  7176. self.on_file_savedocument()
  7177. def obj_move(self):
  7178. self.report_usage("obj_move()")
  7179. self.move_tool.run(toggle=False)
  7180. def on_fileopengerber(self, checked=None, name=None):
  7181. """
  7182. File menu callback for opening a Gerber.
  7183. :return: None
  7184. """
  7185. self.report_usage("on_fileopengerber")
  7186. App.log.debug("on_fileopengerber()")
  7187. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7188. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7189. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7190. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7191. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7192. "*.mil);;" \
  7193. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7194. "Allegro Files (*.art);;" \
  7195. "Mentor Files (*.pho *.gdo);;" \
  7196. "All Files (*.*)"
  7197. if name is None:
  7198. try:
  7199. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7200. directory=self.get_last_folder(),
  7201. filter=_filter_)
  7202. except TypeError:
  7203. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7204. filenames = [str(filename) for filename in filenames]
  7205. else:
  7206. filenames = [name]
  7207. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7208. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7209. _("Opening Gerber file.")),
  7210. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7211. color=QtGui.QColor("gray"))
  7212. if len(filenames) == 0:
  7213. self.inform.emit('[WARNING_NOTCL] %s' %
  7214. _("Open Gerber cancelled."))
  7215. else:
  7216. for filename in filenames:
  7217. if filename != '':
  7218. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7219. def on_fileopenexcellon(self, checked=None, name=None):
  7220. """
  7221. File menu callback for opening an Excellon file.
  7222. :return: None
  7223. """
  7224. self.report_usage("on_fileopenexcellon")
  7225. App.log.debug("on_fileopenexcellon()")
  7226. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7227. "All Files (*.*)"
  7228. if name is None:
  7229. try:
  7230. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7231. directory=self.get_last_folder(),
  7232. filter=_filter_)
  7233. except TypeError:
  7234. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7235. filenames = [str(filename) for filename in filenames]
  7236. else:
  7237. filenames = [str(name)]
  7238. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7239. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7240. _("Opening Excellon file.")),
  7241. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7242. color=QtGui.QColor("gray"))
  7243. if len(filenames) == 0:
  7244. self.inform.emit('[WARNING_NOTCL]%s' %
  7245. _(" Open Excellon cancelled."))
  7246. else:
  7247. for filename in filenames:
  7248. if filename != '':
  7249. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7250. def on_fileopengcode(self, checked=None, name=None):
  7251. """
  7252. File menu call back for opening gcode.
  7253. :return: None
  7254. """
  7255. self.report_usage("on_fileopengcode")
  7256. App.log.debug("on_fileopengcode()")
  7257. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7258. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7259. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7260. "All Files (*.*)"
  7261. if name is None:
  7262. try:
  7263. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7264. directory=self.get_last_folder(),
  7265. filter=_filter_)
  7266. except TypeError:
  7267. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7268. filenames = [str(filename) for filename in filenames]
  7269. else:
  7270. filenames = [name]
  7271. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7272. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7273. _("Opening G-Code file.")),
  7274. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7275. color=QtGui.QColor("gray"))
  7276. if len(filenames) == 0:
  7277. self.inform.emit('[WARNING_NOTCL] %s' %
  7278. _("Open G-Code cancelled."))
  7279. else:
  7280. for filename in filenames:
  7281. if filename != '':
  7282. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  7283. def on_file_openproject(self, checked=None):
  7284. """
  7285. File menu callback for opening a project.
  7286. :return: None
  7287. """
  7288. self.report_usage("on_file_openproject")
  7289. App.log.debug("on_file_openproject()")
  7290. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7291. try:
  7292. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7293. directory=self.get_last_folder(), filter=_filter_)
  7294. except TypeError:
  7295. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7296. # The Qt methods above will return a QString which can cause problems later.
  7297. # So far json.dump() will fail to serialize it.
  7298. # TODO: Improve the serialization methods and remove this fix.
  7299. filename = str(filename)
  7300. if filename == "":
  7301. self.inform.emit('[WARNING_NOTCL] %s' %
  7302. _("Open Project cancelled."))
  7303. else:
  7304. # self.worker_task.emit({'fcn': self.open_project,
  7305. # 'params': [filename]})
  7306. # The above was failing because open_project() is not
  7307. # thread safe. The new_project()
  7308. self.open_project(filename)
  7309. def on_file_openconfig(self, checked=None):
  7310. """
  7311. File menu callback for opening a config file.
  7312. :return: None
  7313. """
  7314. self.report_usage("on_file_openconfig")
  7315. App.log.debug("on_file_openconfig()")
  7316. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7317. try:
  7318. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7319. directory=self.data_path, filter=_filter_)
  7320. except TypeError:
  7321. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7322. filter=_filter_)
  7323. if filename == "":
  7324. self.inform.emit('[WARNING_NOTCL] %s' %
  7325. _("Open Config cancelled."))
  7326. else:
  7327. self.open_config_file(filename)
  7328. def on_file_exportsvg(self):
  7329. """
  7330. Callback for menu item File->Export SVG.
  7331. :return: None
  7332. """
  7333. self.report_usage("on_file_exportsvg")
  7334. App.log.debug("on_file_exportsvg()")
  7335. obj = self.collection.get_active()
  7336. if obj is None:
  7337. self.inform.emit('[WARNING_NOTCL] %s' %
  7338. _("No object selected."))
  7339. msg = _("Please Select a Geometry object to export")
  7340. msgbox = QtWidgets.QMessageBox()
  7341. msgbox.setInformativeText(msg)
  7342. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7343. msgbox.setDefaultButton(bt_ok)
  7344. msgbox.exec_()
  7345. return
  7346. # Check for more compatible types and add as required
  7347. if (not isinstance(obj, FlatCAMGeometry)
  7348. and not isinstance(obj, FlatCAMGerber)
  7349. and not isinstance(obj, FlatCAMCNCjob)
  7350. and not isinstance(obj, FlatCAMExcellon)):
  7351. msg = '[ERROR_NOTCL] %s' % \
  7352. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7353. msgbox = QtWidgets.QMessageBox()
  7354. msgbox.setInformativeText(msg)
  7355. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7356. msgbox.setDefaultButton(bt_ok)
  7357. msgbox.exec_()
  7358. return
  7359. name = obj.options["name"]
  7360. _filter = "SVG File (*.svg);;All Files (*.*)"
  7361. try:
  7362. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7363. caption=_("Export SVG"),
  7364. directory=self.get_last_save_folder() + '/' + str(name),
  7365. filter=_filter)
  7366. except TypeError:
  7367. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7368. filename = str(filename)
  7369. if filename == "":
  7370. self.inform.emit('[WARNING_NOTCL]%s' %
  7371. _(" Export SVG cancelled."))
  7372. return
  7373. else:
  7374. self.export_svg(name, filename)
  7375. if self.defaults["global_open_style"] is False:
  7376. self.file_opened.emit("SVG", filename)
  7377. self.file_saved.emit("SVG", filename)
  7378. def on_file_exportpng(self):
  7379. self.report_usage("on_file_exportpng")
  7380. App.log.debug("on_file_exportpng()")
  7381. self.date = str(datetime.today()).rpartition('.')[0]
  7382. self.date = ''.join(c for c in self.date if c not in ':-')
  7383. self.date = self.date.replace(' ', '_')
  7384. image = _screenshot()
  7385. data = np.asarray(image)
  7386. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7387. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7388. _('Data must be a 3D array with last dimension 3 or 4'))
  7389. return
  7390. filter_ = "PNG File (*.png);;All Files (*.*)"
  7391. try:
  7392. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7393. caption=_("Export PNG Image"),
  7394. directory=self.get_last_save_folder() + '/png_' + self.date,
  7395. filter=filter_)
  7396. except TypeError:
  7397. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7398. filename = str(filename)
  7399. if filename == "":
  7400. self.inform.emit(_("Export PNG cancelled."))
  7401. return
  7402. else:
  7403. write_png(filename, data)
  7404. if self.defaults["global_open_style"] is False:
  7405. self.file_opened.emit("png", filename)
  7406. self.file_saved.emit("png", filename)
  7407. def on_file_savegerber(self):
  7408. """
  7409. Callback for menu item in Project context menu.
  7410. :return: None
  7411. """
  7412. self.report_usage("on_file_savegerber")
  7413. App.log.debug("on_file_savegerber()")
  7414. obj = self.collection.get_active()
  7415. if obj is None:
  7416. self.inform.emit('[WARNING_NOTCL] %s' %
  7417. _("No object selected. Please select an Gerber object to export."))
  7418. return
  7419. # Check for more compatible types and add as required
  7420. if not isinstance(obj, FlatCAMGerber):
  7421. self.inform.emit('[ERROR_NOTCL] %s' %
  7422. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7423. return
  7424. name = self.collection.get_active().options["name"]
  7425. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7426. try:
  7427. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7428. caption="Save Gerber source file",
  7429. directory=self.get_last_save_folder() + '/' + name,
  7430. filter=_filter)
  7431. except TypeError:
  7432. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7433. filename = str(filename)
  7434. if filename == "":
  7435. self.inform.emit('[WARNING_NOTCL] %s' %
  7436. _("Save Gerber source file cancelled."))
  7437. return
  7438. else:
  7439. self.save_source_file(name, filename)
  7440. if self.defaults["global_open_style"] is False:
  7441. self.file_opened.emit("Gerber", filename)
  7442. self.file_saved.emit("Gerber", filename)
  7443. def on_file_savescript(self):
  7444. """
  7445. Callback for menu item in Project context menu.
  7446. :return: None
  7447. """
  7448. self.report_usage("on_file_savescript")
  7449. App.log.debug("on_file_savescript()")
  7450. obj = self.collection.get_active()
  7451. if obj is None:
  7452. self.inform.emit('[WARNING_NOTCL] %s' %
  7453. _("No object selected. Please select an Script object to export."))
  7454. return
  7455. # Check for more compatible types and add as required
  7456. if not isinstance(obj, FlatCAMScript):
  7457. self.inform.emit('[ERROR_NOTCL] %s' %
  7458. _("Failed. Only Script objects can be saved as TCL Script files..."))
  7459. return
  7460. name = self.collection.get_active().options["name"]
  7461. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7462. try:
  7463. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7464. caption="Save Script source file",
  7465. directory=self.get_last_save_folder() + '/' + name,
  7466. filter=_filter)
  7467. except TypeError:
  7468. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  7469. filename = str(filename)
  7470. if filename == "":
  7471. self.inform.emit('[WARNING_NOTCL] %s' %
  7472. _("Save Script source file cancelled."))
  7473. return
  7474. else:
  7475. self.save_source_file(name, filename)
  7476. if self.defaults["global_open_style"] is False:
  7477. self.file_opened.emit("Script", filename)
  7478. self.file_saved.emit("Script", filename)
  7479. def on_file_savedocument(self):
  7480. """
  7481. Callback for menu item in Project context menu.
  7482. :return: None
  7483. """
  7484. self.report_usage("on_file_savedocument")
  7485. App.log.debug("on_file_savedocument()")
  7486. obj = self.collection.get_active()
  7487. if obj is None:
  7488. self.inform.emit('[WARNING_NOTCL] %s' %
  7489. _("No object selected. Please select an Document object to export."))
  7490. return
  7491. # Check for more compatible types and add as required
  7492. if not isinstance(obj, FlatCAMScript):
  7493. self.inform.emit('[ERROR_NOTCL] %s' %
  7494. _("Failed. Only Document objects can be saved as Document files..."))
  7495. return
  7496. name = self.collection.get_active().options["name"]
  7497. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7498. try:
  7499. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7500. caption="Save Document source file",
  7501. directory=self.get_last_save_folder() + '/' + name,
  7502. filter=_filter)
  7503. except TypeError:
  7504. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  7505. filename = str(filename)
  7506. if filename == "":
  7507. self.inform.emit('[WARNING_NOTCL] %s' %
  7508. _("Save Document source file cancelled."))
  7509. return
  7510. else:
  7511. self.save_source_file(name, filename)
  7512. if self.defaults["global_open_style"] is False:
  7513. self.file_opened.emit("Document", filename)
  7514. self.file_saved.emit("Document", filename)
  7515. def on_file_saveexcellon(self):
  7516. """
  7517. Callback for menu item in project context menu.
  7518. :return: None
  7519. """
  7520. self.report_usage("on_file_saveexcellon")
  7521. App.log.debug("on_file_saveexcellon()")
  7522. obj = self.collection.get_active()
  7523. if obj is None:
  7524. self.inform.emit('[WARNING_NOTCL] %s' %
  7525. _("No object selected. Please select an Excellon object to export."))
  7526. return
  7527. # Check for more compatible types and add as required
  7528. if not isinstance(obj, FlatCAMExcellon):
  7529. self.inform.emit('[ERROR_NOTCL] %s' %
  7530. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7531. return
  7532. name = self.collection.get_active().options["name"]
  7533. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7534. try:
  7535. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7536. caption=_("Save Excellon source file"),
  7537. directory=self.get_last_save_folder() + '/' + name,
  7538. filter=_filter)
  7539. except TypeError:
  7540. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7541. filename = str(filename)
  7542. if filename == "":
  7543. self.inform.emit('[WARNING_NOTCL] %s' %
  7544. _("Saving Excellon source file cancelled."))
  7545. return
  7546. else:
  7547. self.save_source_file(name, filename)
  7548. if self.defaults["global_open_style"] is False:
  7549. self.file_opened.emit("Excellon", filename)
  7550. self.file_saved.emit("Excellon", filename)
  7551. def on_file_exportexcellon(self):
  7552. """
  7553. Callback for menu item File->Export->Excellon.
  7554. :return: None
  7555. """
  7556. self.report_usage("on_file_exportexcellon")
  7557. App.log.debug("on_file_exportexcellon()")
  7558. obj = self.collection.get_active()
  7559. if obj is None:
  7560. self.inform.emit('[WARNING_NOTCL] %s' %
  7561. _("No object selected. Please Select an Excellon object to export."))
  7562. return
  7563. # Check for more compatible types and add as required
  7564. if not isinstance(obj, FlatCAMExcellon):
  7565. self.inform.emit('[ERROR_NOTCL] %s' %
  7566. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7567. return
  7568. name = self.collection.get_active().options["name"]
  7569. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7570. try:
  7571. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7572. caption=_("Export Excellon"),
  7573. directory=self.get_last_save_folder() + '/' + name,
  7574. filter=_filter)
  7575. except TypeError:
  7576. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7577. filename = str(filename)
  7578. if filename == "":
  7579. self.inform.emit('[WARNING_NOTCL] %s' %
  7580. _("Export Excellon cancelled."))
  7581. return
  7582. else:
  7583. self.export_excellon(name, filename)
  7584. if self.defaults["global_open_style"] is False:
  7585. self.file_opened.emit("Excellon", filename)
  7586. self.file_saved.emit("Excellon", filename)
  7587. def on_file_exportgerber(self):
  7588. """
  7589. Callback for menu item File->Export->Gerber.
  7590. :return: None
  7591. """
  7592. self.report_usage("on_file_exportgerber")
  7593. App.log.debug("on_file_exportgerber()")
  7594. obj = self.collection.get_active()
  7595. if obj is None:
  7596. self.inform.emit('[WARNING_NOTCL] %s' %
  7597. _("No object selected. Please Select an Gerber object to export."))
  7598. return
  7599. # Check for more compatible types and add as required
  7600. if not isinstance(obj, FlatCAMGerber):
  7601. self.inform.emit('[ERROR_NOTCL] %s' %
  7602. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7603. return
  7604. name = self.collection.get_active().options["name"]
  7605. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7606. try:
  7607. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7608. caption=_("Export Gerber"),
  7609. directory=self.get_last_save_folder() + '/' + name,
  7610. filter=_filter_)
  7611. except TypeError:
  7612. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7613. filename = str(filename)
  7614. if filename == "":
  7615. self.inform.emit('[WARNING_NOTCL] %s' %
  7616. _("Export Gerber cancelled."))
  7617. return
  7618. else:
  7619. self.export_gerber(name, filename)
  7620. if self.defaults["global_open_style"] is False:
  7621. self.file_opened.emit("Gerber", filename)
  7622. self.file_saved.emit("Gerber", filename)
  7623. def on_file_exportdxf(self):
  7624. """
  7625. Callback for menu item File->Export DXF.
  7626. :return: None
  7627. """
  7628. self.report_usage("on_file_exportdxf")
  7629. App.log.debug("on_file_exportdxf()")
  7630. obj = self.collection.get_active()
  7631. if obj is None:
  7632. self.inform.emit('[WARNING_NOTCL] %s' %
  7633. _("No object selected."))
  7634. msg = _("Please Select a Geometry object to export")
  7635. msgbox = QtWidgets.QMessageBox()
  7636. msgbox.setInformativeText(msg)
  7637. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7638. msgbox.setDefaultButton(bt_ok)
  7639. msgbox.exec_()
  7640. return
  7641. # Check for more compatible types and add as required
  7642. if not isinstance(obj, FlatCAMGeometry):
  7643. msg = '[ERROR_NOTCL] %s' % \
  7644. _("Only Geometry objects can be used.")
  7645. msgbox = QtWidgets.QMessageBox()
  7646. msgbox.setInformativeText(msg)
  7647. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7648. msgbox.setDefaultButton(bt_ok)
  7649. msgbox.exec_()
  7650. return
  7651. name = self.collection.get_active().options["name"]
  7652. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7653. try:
  7654. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7655. caption=_("Export DXF"),
  7656. directory=self.get_last_save_folder() + '/' + name,
  7657. filter=_filter_)
  7658. except TypeError:
  7659. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7660. filter=_filter_)
  7661. filename = str(filename)
  7662. if filename == "":
  7663. self.inform.emit('[WARNING_NOTCL] %s' %
  7664. _("Export DXF cancelled."))
  7665. return
  7666. else:
  7667. self.export_dxf(name, filename)
  7668. if self.defaults["global_open_style"] is False:
  7669. self.file_opened.emit("DXF", filename)
  7670. self.file_saved.emit("DXF", filename)
  7671. def on_file_importsvg(self, type_of_obj):
  7672. """
  7673. Callback for menu item File->Import SVG.
  7674. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7675. :type type_of_obj: str
  7676. :return: None
  7677. """
  7678. self.report_usage("on_file_importsvg")
  7679. App.log.debug("on_file_importsvg()")
  7680. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7681. try:
  7682. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7683. directory=self.get_last_folder(), filter=_filter_)
  7684. except TypeError:
  7685. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7686. filter=_filter_)
  7687. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7688. type_of_obj = "geometry"
  7689. filenames = [str(filename) for filename in filenames]
  7690. if len(filenames) == 0:
  7691. self.inform.emit('[WARNING_NOTCL] %s' %
  7692. _("Open SVG cancelled."))
  7693. else:
  7694. for filename in filenames:
  7695. if filename != '':
  7696. self.worker_task.emit({'fcn': self.import_svg,
  7697. 'params': [filename, type_of_obj]})
  7698. def on_file_importdxf(self, type_of_obj):
  7699. """
  7700. Callback for menu item File->Import DXF.
  7701. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7702. :type type_of_obj: str
  7703. :return: None
  7704. """
  7705. self.report_usage("on_file_importdxf")
  7706. App.log.debug("on_file_importdxf()")
  7707. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7708. try:
  7709. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7710. directory=self.get_last_folder(),
  7711. filter=_filter_)
  7712. except TypeError:
  7713. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7714. filter=_filter_)
  7715. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7716. type_of_obj = "geometry"
  7717. filenames = [str(filename) for filename in filenames]
  7718. if len(filenames) == 0:
  7719. self.inform.emit('[WARNING_NOTCL] %s' %
  7720. _("Open DXF cancelled."))
  7721. else:
  7722. for filename in filenames:
  7723. if filename != '':
  7724. self.worker_task.emit({'fcn': self.import_dxf,
  7725. 'params': [filename, type_of_obj]})
  7726. # ###############################################################################################################
  7727. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7728. # ###############################################################################################################
  7729. def init_code_editor(self, name):
  7730. self.text_editor_tab = TextEditor(app=self)
  7731. # add the tab if it was closed
  7732. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  7733. self.text_editor_tab.setObjectName('text_editor_tab')
  7734. # delete the absolute and relative position and messages in the infobar
  7735. self.ui.position_label.setText("")
  7736. self.ui.rel_position_label.setText("")
  7737. # first clear previous text in text editor (if any)
  7738. self.text_editor_tab.code_editor.clear()
  7739. self.text_editor_tab.code_editor.setReadOnly(False)
  7740. self.toggle_codeeditor = True
  7741. self.text_editor_tab.code_editor.completer_enable = False
  7742. self.text_editor_tab.buttonRun.hide()
  7743. # make sure to keep a reference to the code editor
  7744. self.reference_code_editor = self.text_editor_tab.code_editor
  7745. # Switch plot_area to CNCJob tab
  7746. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  7747. def on_view_source(self):
  7748. self.inform.emit('%s' %
  7749. _("Viewing the source code of the selected object."))
  7750. self.proc_container.view.set_busy(_("Loading..."))
  7751. try:
  7752. obj = self.collection.get_active()
  7753. except Exception as e:
  7754. log.debug("App.on_view_source() --> %s" % str(e))
  7755. self.inform.emit('[WARNING_NOTCL] %s' %
  7756. _("Select an Gerber or Excellon file to view it's source file."))
  7757. return 'fail'
  7758. if obj.kind == 'gerber':
  7759. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7760. elif obj.kind == 'excellon':
  7761. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7762. elif obj.kind == 'cncjob':
  7763. "GCode Files (*.NC);;All Files (*.*)"
  7764. else:
  7765. flt = "All Files (*.*)"
  7766. self.source_editor_tab = TextEditor(app=self)
  7767. # add the tab if it was closed
  7768. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  7769. self.source_editor_tab.setObjectName('source_editor_tab')
  7770. # delete the absolute and relative position and messages in the infobar
  7771. self.ui.position_label.setText("")
  7772. self.ui.rel_position_label.setText("")
  7773. # first clear previous text in text editor (if any)
  7774. self.source_editor_tab.code_editor.clear()
  7775. self.source_editor_tab.code_editor.setReadOnly(False)
  7776. self.source_editor_tab.code_editor.completer_enable = False
  7777. self.source_editor_tab.buttonRun.hide()
  7778. # Switch plot_area to CNCJob tab
  7779. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  7780. self.source_editor_tab.buttonOpen.clicked.disconnect()
  7781. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  7782. self.source_editor_tab.buttonSave.clicked.disconnect()
  7783. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  7784. # then append the text from GCode to the text editor
  7785. if obj.kind == 'cncjob':
  7786. try:
  7787. file = obj.export_gcode(
  7788. preamble=self.defaults["cncjob_prepend"],
  7789. postamble=self.defaults["cncjob_append"],
  7790. to_file=True)
  7791. if file == 'fail':
  7792. return 'fail'
  7793. except AttributeError:
  7794. self.inform.emit('[WARNING_NOTCL] %s' %
  7795. _("There is no selected object for which to see it's source file code."))
  7796. return 'fail'
  7797. else:
  7798. try:
  7799. file = StringIO(obj.source_file)
  7800. except AttributeError:
  7801. self.inform.emit('[WARNING_NOTCL] %s' %
  7802. _("There is no selected object for which to see it's source file code."))
  7803. return 'fail'
  7804. self.source_editor_tab.t_frame.hide()
  7805. try:
  7806. for line in file:
  7807. QtWidgets.QApplication.processEvents()
  7808. proc_line = str(line).strip('\n')
  7809. self.source_editor_tab.code_editor.append(proc_line)
  7810. except Exception as e:
  7811. log.debug('App.on_view_source() -->%s' % str(e))
  7812. self.inform.emit('[ERROR] %s: %s' %
  7813. (_('Failed to load the source code for the selected object'), str(e)))
  7814. return
  7815. self.source_editor_tab.handleTextChanged()
  7816. self.source_editor_tab.t_frame.show()
  7817. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7818. self.proc_container.view.set_idle()
  7819. # self.ui.show()
  7820. def on_toggle_code_editor(self):
  7821. self.report_usage("on_toggle_code_editor()")
  7822. if self.toggle_codeeditor is False:
  7823. self.init_code_editor(name=_("Code Editor"))
  7824. self.text_editor_tab.buttonOpen.clicked.disconnect()
  7825. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  7826. self.text_editor_tab.buttonSave.clicked.disconnect()
  7827. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  7828. else:
  7829. for idx in range(self.ui.plot_tab_area.count()):
  7830. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  7831. self.ui.plot_tab_area.closeTab(idx)
  7832. break
  7833. self.toggle_codeeditor = False
  7834. def on_code_editor_close(self):
  7835. print("closed")
  7836. self.toggle_codeeditor = False
  7837. def on_filenewscript(self, silent=False, name=None, text=None):
  7838. """
  7839. Will create a new script file and open it in the Code Editor
  7840. :param silent: if True will not display status messages
  7841. :return: None
  7842. """
  7843. if silent is False:
  7844. self.inform.emit('[success] %s' %
  7845. _("New TCL script file created in Code Editor."))
  7846. # delete the absolute and relative position and messages in the infobar
  7847. self.ui.position_label.setText("")
  7848. self.ui.rel_position_label.setText("")
  7849. if name is not None:
  7850. self.new_script_object(name=name, text=text)
  7851. else:
  7852. self.new_script_object(text=text)
  7853. # script_text = script_obj.source_file
  7854. #
  7855. # self.proc_container.view.set_busy(_("Loading..."))
  7856. # script_obj.script_editor_tab.t_frame.hide()
  7857. #
  7858. # script_obj.script_editor_tab.t_frame.show()
  7859. # self.proc_container.view.set_idle()
  7860. def on_fileopenscript(self, name=None, silent=False):
  7861. """
  7862. Will open a Tcl script file into the Code Editor
  7863. :param silent: if True will not display status messages
  7864. :param name: name of a Tcl script file to open
  7865. :return:
  7866. """
  7867. self.report_usage("on_fileopenscript")
  7868. App.log.debug("on_fileopenscript()")
  7869. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7870. if name:
  7871. filenames = [name]
  7872. else:
  7873. try:
  7874. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7875. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  7876. except TypeError:
  7877. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7878. if len(filenames) == 0:
  7879. if silent is False:
  7880. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  7881. else:
  7882. for filename in filenames:
  7883. if filename != '':
  7884. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7885. def on_filerunscript(self, name=None, silent=False):
  7886. """
  7887. File menu callback for loading and running a TCL script.
  7888. :param silent: if True will not display status messages
  7889. :param name: name of a Tcl script file to be run by FlatCAM
  7890. :return: None
  7891. """
  7892. self.report_usage("on_filerunscript")
  7893. App.log.debug("on_file_runscript()")
  7894. if name:
  7895. filename = name
  7896. if self.cmd_line_headless != 1:
  7897. self.splash.showMessage('%s: %ssec\n%s' %
  7898. (_("Canvas initialization started.\n"
  7899. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7900. _("Executing FlatCAMScript file.")
  7901. ),
  7902. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7903. color=QtGui.QColor("gray"))
  7904. else:
  7905. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7906. try:
  7907. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7908. directory=self.get_last_folder(), filter=_filter_)
  7909. except TypeError:
  7910. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7911. # The Qt methods above will return a QString which can cause problems later.
  7912. # So far json.dump() will fail to serialize it.
  7913. # TODO: Improve the serialization methods and remove this fix.
  7914. filename = str(filename)
  7915. if filename == "":
  7916. if silent is False:
  7917. self.inform.emit('[WARNING_NOTCL] %s' %
  7918. _("Run TCL script cancelled."))
  7919. else:
  7920. if self.cmd_line_headless != 1:
  7921. if self.ui.shell_dock.isHidden():
  7922. self.ui.shell_dock.show()
  7923. try:
  7924. with open(filename, "r") as tcl_script:
  7925. cmd_line_shellfile_content = tcl_script.read()
  7926. if self.cmd_line_headless != 1:
  7927. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7928. else:
  7929. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7930. if silent is False:
  7931. self.inform.emit('[success] %s' %
  7932. _("TCL script file opened in Code Editor and executed."))
  7933. except Exception as e:
  7934. log.debug("App.on_filerunscript() -> %s" % str(e))
  7935. sys.exit(2)
  7936. def on_file_saveproject(self, silent=False):
  7937. """
  7938. Callback for menu item File->Save Project. Saves the project to
  7939. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7940. if set to None. The project is saved by calling ``self.save_project()``.
  7941. :param silent: if True will not display status messages
  7942. :return: None
  7943. """
  7944. self.report_usage("on_file_saveproject")
  7945. if self.project_filename is None:
  7946. self.on_file_saveprojectas()
  7947. else:
  7948. self.worker_task.emit({'fcn': self.save_project,
  7949. 'params': [self.project_filename, silent]})
  7950. if self.defaults["global_open_style"] is False:
  7951. self.file_opened.emit("project", self.project_filename)
  7952. self.file_saved.emit("project", self.project_filename)
  7953. self.set_ui_title(name=self.project_filename)
  7954. self.should_we_save = False
  7955. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7956. """
  7957. Callback for menu item File->Save Project As... Opens a file
  7958. chooser and saves the project to the given file via
  7959. ``self.save_project()``.
  7960. :param make_copy if to be create a copy of the project; boolean
  7961. :param use_thread: if to be run in a separate thread; boolean
  7962. :param quit_action: if to be followed by quiting the application; boolean
  7963. :return: None
  7964. """
  7965. self.report_usage("on_file_saveprojectas")
  7966. self.date = str(datetime.today()).rpartition('.')[0]
  7967. self.date = ''.join(c for c in self.date if c not in ':-')
  7968. self.date = self.date.replace(' ', '_')
  7969. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7970. try:
  7971. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7972. caption=_("Save Project As ..."),
  7973. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7974. filter=filter_)
  7975. except TypeError:
  7976. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7977. filename = str(filename)
  7978. if filename == '':
  7979. self.inform.emit('[WARNING_NOTCL] %s' %
  7980. _("Save Project cancelled."))
  7981. return
  7982. try:
  7983. f = open(filename, 'r')
  7984. f.close()
  7985. except IOError:
  7986. pass
  7987. if use_thread is True:
  7988. self.worker_task.emit({'fcn': self.save_project,
  7989. 'params': [filename, quit_action]})
  7990. else:
  7991. self.save_project(filename, quit_action)
  7992. # self.save_project(filename)
  7993. if self.defaults["global_open_style"] is False:
  7994. self.file_opened.emit("project", filename)
  7995. self.file_saved.emit("project", filename)
  7996. if not make_copy:
  7997. self.project_filename = filename
  7998. self.set_ui_title(name=self.project_filename)
  7999. self.should_we_save = False
  8000. def export_svg(self, obj_name, filename, scale_factor=0.00):
  8001. """
  8002. Exports a Geometry Object to an SVG file.
  8003. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8004. :param filename: Path to the SVG file to save to.
  8005. :param scale_factor: factor by which to change/scale the thickness of the features
  8006. :return:
  8007. """
  8008. self.report_usage("export_svg()")
  8009. if filename is None:
  8010. filename = self.defaults["global_last_save_folder"]
  8011. self.log.debug("export_svg()")
  8012. try:
  8013. obj = self.collection.get_by_name(str(obj_name))
  8014. except:
  8015. # TODO: The return behavior has not been established... should raise exception?
  8016. return "Could not retrieve object: %s" % obj_name
  8017. with self.proc_container.new(_("Exporting SVG")) as proc:
  8018. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8019. # Determine bounding area for svg export
  8020. bounds = obj.bounds()
  8021. size = obj.size()
  8022. # Convert everything to strings for use in the xml doc
  8023. svgwidth = str(size[0])
  8024. svgheight = str(size[1])
  8025. minx = str(bounds[0])
  8026. miny = str(bounds[1] - size[1])
  8027. uom = obj.units.lower()
  8028. # Add a SVG Header and footer to the svg output from shapely
  8029. # The transform flips the Y Axis so that everything renders
  8030. # properly within svg apps such as inkscape
  8031. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8032. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8033. svg_header += 'width="' + svgwidth + uom + '" '
  8034. svg_header += 'height="' + svgheight + uom + '" '
  8035. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8036. svg_header += '<g transform="scale(1,-1)">'
  8037. svg_footer = '</g> </svg>'
  8038. svg_elem = svg_header + exported_svg + svg_footer
  8039. # Parse the xml through a xml parser just to add line feeds
  8040. # and to make it look more pretty for the output
  8041. svgcode = parse_xml_string(svg_elem)
  8042. try:
  8043. with open(filename, 'w') as fp:
  8044. fp.write(svgcode.toprettyxml())
  8045. except PermissionError:
  8046. self.inform.emit('[WARNING] %s' %
  8047. _("Permission denied, saving not possible.\n"
  8048. "Most likely another app is holding the file open and not accessible."))
  8049. return 'fail'
  8050. if self.defaults["global_open_style"] is False:
  8051. self.file_opened.emit("SVG", filename)
  8052. self.file_saved.emit("SVG", filename)
  8053. self.inform.emit('[success] %s: %s' %
  8054. (_("SVG file exported to"), filename))
  8055. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  8056. """
  8057. Exports a Geometry Object to an SVG file in negative.
  8058. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8059. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8060. :param filename: Path to the SVG file to save to.
  8061. :param boundary: thickness of a black border to surround all the features
  8062. :param scale_factor: factor by which to change/scale the thickness of the features
  8063. :param use_thread: if to be run in a separate thread; boolean
  8064. :return:
  8065. """
  8066. self.report_usage("export_negative()")
  8067. if filename is None:
  8068. filename = self.defaults["global_last_save_folder"]
  8069. self.log.debug("export_svg() negative")
  8070. try:
  8071. obj = self.collection.get_by_name(str(obj_name))
  8072. except:
  8073. # TODO: The return behavior has not been established... should raise exception?
  8074. return "Could not retrieve object: %s" % obj_name
  8075. try:
  8076. box = self.collection.get_by_name(str(box_name))
  8077. except:
  8078. # TODO: The return behavior has not been established... should raise exception?
  8079. return "Could not retrieve object: %s" % box_name
  8080. if box is None:
  8081. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8082. (_("No object Box. Using instead"), obj))
  8083. box = obj
  8084. def make_negative_film():
  8085. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8086. # Determine bounding area for svg export
  8087. bounds = box.bounds()
  8088. size = box.size()
  8089. uom = obj.units.lower()
  8090. # Convert everything to strings for use in the xml doc
  8091. svgwidth = str(size[0] + (2 * boundary))
  8092. svgheight = str(size[1] + (2 * boundary))
  8093. minx = str(bounds[0] - boundary)
  8094. miny = str(bounds[1] + boundary + size[1])
  8095. miny_rect = str(bounds[1] - boundary)
  8096. # Add a SVG Header and footer to the svg output from shapely
  8097. # The transform flips the Y Axis so that everything renders
  8098. # properly within svg apps such as inkscape
  8099. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8100. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8101. svg_header += 'width="' + svgwidth + uom + '" '
  8102. svg_header += 'height="' + svgheight + uom + '" '
  8103. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8104. svg_header += '>'
  8105. svg_header += '<g transform="scale(1,-1)">'
  8106. svg_footer = '</g> </svg>'
  8107. # Change the attributes of the exported SVG
  8108. # We don't need stroke-width - wrong, we do when we have lines with certain width
  8109. # We set opacity to maximum
  8110. # We set the color to WHITE
  8111. root = ET.fromstring(exported_svg)
  8112. for child in root:
  8113. child.set('fill', '#FFFFFF')
  8114. child.set('opacity', '1.0')
  8115. child.set('stroke', '#FFFFFF')
  8116. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  8117. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  8118. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  8119. first_svg_elem_tag = 'rect'
  8120. first_svg_elem_attribs = {
  8121. 'x': minx,
  8122. 'y': miny_rect,
  8123. 'width': svgwidth,
  8124. 'height': svgheight,
  8125. 'id': 'neg_rect',
  8126. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  8127. }
  8128. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  8129. exported_svg = ET.tostring(root)
  8130. svg_elem = svg_header + str(exported_svg) + svg_footer
  8131. # Parse the xml through a xml parser just to add line feeds
  8132. # and to make it look more pretty for the output
  8133. doc = parse_xml_string(svg_elem)
  8134. try:
  8135. with open(filename, 'w') as fp:
  8136. fp.write(doc.toprettyxml())
  8137. except PermissionError:
  8138. self.inform.emit('[WARNING] %s' %
  8139. _("Permission denied, saving not possible.\n"
  8140. "Most likely another app is holding the file open and not accessible."))
  8141. return 'fail'
  8142. if self.defaults["global_open_style"] is False:
  8143. self.file_opened.emit("SVG", filename)
  8144. self.file_saved.emit("SVG", filename)
  8145. self.inform.emit('[success] %s: %s' %
  8146. (_("SVG file exported to"), filename))
  8147. if use_thread is True:
  8148. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8149. def job_thread_film(app_obj):
  8150. try:
  8151. make_negative_film()
  8152. except Exception as e:
  8153. proc.done()
  8154. return
  8155. proc.done()
  8156. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8157. else:
  8158. make_negative_film()
  8159. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  8160. """
  8161. Exports a Geometry Object to an SVG file in positive black.
  8162. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8163. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8164. :param filename: Path to the SVG file to save to.
  8165. :param scale_factor: factor by which to change/scale the thickness of the features
  8166. :param use_thread: if to be run in a separate thread; boolean
  8167. :return:
  8168. """
  8169. self.report_usage("export_svg_positive()")
  8170. if filename is None:
  8171. filename = self.defaults["global_last_save_folder"]
  8172. self.log.debug("export_svg() black")
  8173. try:
  8174. obj = self.collection.get_by_name(str(obj_name))
  8175. except:
  8176. # TODO: The return behavior has not been established... should raise exception?
  8177. return "Could not retrieve object: %s" % obj_name
  8178. try:
  8179. box = self.collection.get_by_name(str(box_name))
  8180. except:
  8181. # TODO: The return behavior has not been established... should raise exception?
  8182. return "Could not retrieve object: %s" % box_name
  8183. if box is None:
  8184. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8185. (_("No object Box. Using instead"), obj))
  8186. box = obj
  8187. def make_positive_film():
  8188. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8189. self.progress.emit(40)
  8190. # Change the attributes of the exported SVG
  8191. # We don't need stroke-width
  8192. # We set opacity to maximum
  8193. # We set the colour to WHITE
  8194. root = ET.fromstring(exported_svg)
  8195. for child in root:
  8196. child.set('fill', str(self.defaults['tools_film_color']))
  8197. child.set('opacity', '1.0')
  8198. child.set('stroke', str(self.defaults['tools_film_color']))
  8199. exported_svg = ET.tostring(root)
  8200. # Determine bounding area for svg export
  8201. bounds = box.bounds()
  8202. size = box.size()
  8203. # This contain the measure units
  8204. uom = obj.units.lower()
  8205. # Define a boundary around SVG of about 1.0mm (~39mils)
  8206. if uom in "mm":
  8207. boundary = 1.0
  8208. else:
  8209. boundary = 0.0393701
  8210. self.progress.emit(80)
  8211. # Convert everything to strings for use in the xml doc
  8212. svgwidth = str(size[0] + (2 * boundary))
  8213. svgheight = str(size[1] + (2 * boundary))
  8214. minx = str(bounds[0] - boundary)
  8215. miny = str(bounds[1] + boundary + size[1])
  8216. self.log.debug(minx)
  8217. self.log.debug(miny)
  8218. # Add a SVG Header and footer to the svg output from shapely
  8219. # The transform flips the Y Axis so that everything renders
  8220. # properly within svg apps such as inkscape
  8221. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8222. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8223. svg_header += 'width="' + svgwidth + uom + '" '
  8224. svg_header += 'height="' + svgheight + uom + '" '
  8225. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8226. svg_header += '>'
  8227. svg_header += '<g transform="scale(1,-1)">'
  8228. svg_footer = '</g> </svg>'
  8229. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  8230. self.progress.emit(90)
  8231. # Parse the xml through a xml parser just to add line feeds
  8232. # and to make it look more pretty for the output
  8233. doc = parse_xml_string(svg_elem)
  8234. try:
  8235. with open(filename, 'w') as fp:
  8236. fp.write(doc.toprettyxml())
  8237. except PermissionError:
  8238. self.inform.emit('[WARNING] %s' %
  8239. _("Permission denied, saving not possible.\n"
  8240. "Most likely another app is holding the file open and not accessible."))
  8241. return 'fail'
  8242. self.progress.emit(100)
  8243. if self.defaults["global_open_style"] is False:
  8244. self.file_opened.emit("SVG", filename)
  8245. self.file_saved.emit("SVG", filename)
  8246. self.inform.emit('[success] %s: %s' %
  8247. (_("SVG file exported to"), filename))
  8248. if use_thread is True:
  8249. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8250. def job_thread_film(app_obj):
  8251. try:
  8252. make_positive_film()
  8253. except Exception as e:
  8254. proc.done()
  8255. return
  8256. proc.done()
  8257. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8258. else:
  8259. make_positive_film()
  8260. def save_source_file(self, obj_name, filename, use_thread=True):
  8261. """
  8262. Exports a FlatCAM Object to an Gerber/Excellon file.
  8263. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8264. :param filename: Path to the Gerber file to save to.
  8265. :param use_thread: if to be run in a separate thread
  8266. :return:
  8267. """
  8268. self.report_usage("save source file()")
  8269. if filename is None:
  8270. filename = self.defaults["global_last_save_folder"]
  8271. self.log.debug("save source file()")
  8272. obj = self.collection.get_by_name(obj_name)
  8273. file_string = StringIO(obj.source_file)
  8274. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8275. try:
  8276. with open(filename, 'w') as file:
  8277. file.writelines('G04*\n')
  8278. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8279. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8280. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8281. file.writelines('G04 Created on : %s*\n' % time_string)
  8282. for line in file_string:
  8283. file.writelines(line)
  8284. except PermissionError:
  8285. self.inform.emit('[WARNING] %s' %
  8286. _("Permission denied, saving not possible.\n"
  8287. "Most likely another app is holding the file open and not accessible."))
  8288. return 'fail'
  8289. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8290. """
  8291. Exports a Excellon Object to an Excellon file.
  8292. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8293. :param filename: Path to the Excellon file to save to.
  8294. :param use_thread: if to be run in a separate thread
  8295. :return:
  8296. """
  8297. self.report_usage("export_excellon()")
  8298. if filename is None:
  8299. filename = self.defaults["global_last_save_folder"]
  8300. self.log.debug("export_excellon()")
  8301. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8302. self.defaults["excellon_exp_decimals"]
  8303. )
  8304. if local_use is None:
  8305. try:
  8306. obj = self.collection.get_by_name(str(obj_name))
  8307. except:
  8308. # TODO: The return behavior has not been established... should raise exception?
  8309. return "Could not retrieve object: %s" % obj_name
  8310. else:
  8311. obj = local_use
  8312. # updated units
  8313. eunits = self.defaults["excellon_exp_units"]
  8314. ewhole = self.defaults["excellon_exp_integer"]
  8315. efract = self.defaults["excellon_exp_decimals"]
  8316. ezeros = self.defaults["excellon_exp_zeros"]
  8317. eformat = self.defaults["excellon_exp_format"]
  8318. slot_type = self.defaults["excellon_exp_slot_type"]
  8319. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8320. if fc_units == 'MM':
  8321. factor = 1 if eunits == 'METRIC' else 0.03937
  8322. else:
  8323. factor = 25.4 if eunits == 'METRIC' else 1
  8324. def make_excellon():
  8325. try:
  8326. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8327. header = 'M48\n'
  8328. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8329. (str(self.version), str(self.version_date))
  8330. header += ';Filename: %s' % str(obj_name) + '\n'
  8331. header += ';Created on : %s' % time_str + '\n'
  8332. if eformat == 'dec':
  8333. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8334. header += eunits + '\n'
  8335. for tool in obj.tools:
  8336. if eunits == 'METRIC':
  8337. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8338. tool=str(tool),
  8339. dec=2)
  8340. else:
  8341. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8342. tool=str(tool),
  8343. dec=4)
  8344. else:
  8345. if ezeros == 'LZ':
  8346. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8347. form='ndec', e_zeros='LZ', factor=factor,
  8348. slot_type=slot_type)
  8349. header += '%s,%s\n' % (eunits, 'LZ')
  8350. header += format_exc
  8351. for tool in obj.tools:
  8352. if eunits == 'METRIC':
  8353. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8354. tool=str(tool),
  8355. dec=2)
  8356. else:
  8357. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8358. tool=str(tool),
  8359. dec=4)
  8360. else:
  8361. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8362. form='ndec', e_zeros='TZ', factor=factor,
  8363. slot_type=slot_type)
  8364. header += '%s,%s\n' % (eunits, 'TZ')
  8365. header += format_exc
  8366. for tool in obj.tools:
  8367. if eunits == 'METRIC':
  8368. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8369. tool=str(tool),
  8370. dec=2)
  8371. else:
  8372. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8373. tool=str(tool),
  8374. dec=4)
  8375. header += '%\n'
  8376. footer = 'M30\n'
  8377. exported_excellon = header
  8378. exported_excellon += excellon_code
  8379. exported_excellon += footer
  8380. if local_use is None:
  8381. try:
  8382. with open(filename, 'w') as fp:
  8383. fp.write(exported_excellon)
  8384. except PermissionError:
  8385. self.inform.emit('[WARNING] %s' %
  8386. _("Permission denied, saving not possible.\n"
  8387. "Most likely another app is holding the file open and not accessible."))
  8388. return 'fail'
  8389. if self.defaults["global_open_style"] is False:
  8390. self.file_opened.emit("Excellon", filename)
  8391. self.file_saved.emit("Excellon", filename)
  8392. self.inform.emit('[success] %s: %s' %
  8393. (_("Excellon file exported to"), filename))
  8394. else:
  8395. return exported_excellon
  8396. except Exception as e:
  8397. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8398. return 'fail'
  8399. if use_thread is True:
  8400. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8401. def job_thread_exc(app_obj):
  8402. ret = make_excellon()
  8403. if ret == 'fail':
  8404. self.inform.emit('[ERROR_NOTCL] %s' %
  8405. _('Could not export Excellon file.'))
  8406. return
  8407. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8408. else:
  8409. ret = make_excellon()
  8410. if ret == 'fail':
  8411. self.inform.emit('[ERROR_NOTCL] %s' %
  8412. _('Could not export Excellon file.'))
  8413. return 'fail'
  8414. if local_use is not None:
  8415. return ret
  8416. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8417. """
  8418. Exports a Gerber Object to an Gerber file.
  8419. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8420. :param filename: Path to the Gerber file to save to.
  8421. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8422. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8423. :param use_thread: if to be run in a separate thread
  8424. :return:
  8425. """
  8426. self.report_usage("export_gerber()")
  8427. if filename is None:
  8428. filename = self.defaults["global_last_save_folder"]
  8429. self.log.debug("export_gerber()")
  8430. if local_use is None:
  8431. try:
  8432. obj = self.collection.get_by_name(str(obj_name))
  8433. except:
  8434. # TODO: The return behavior has not been established... should raise exception?
  8435. return "Could not retrieve object: %s" % obj_name
  8436. else:
  8437. obj = local_use
  8438. # updated units
  8439. gunits = self.defaults["gerber_exp_units"]
  8440. gwhole = self.defaults["gerber_exp_integer"]
  8441. gfract = self.defaults["gerber_exp_decimals"]
  8442. gzeros = self.defaults["gerber_exp_zeros"]
  8443. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8444. if fc_units == 'MM':
  8445. factor = 1 if gunits == 'MM' else 0.03937
  8446. else:
  8447. factor = 25.4 if gunits == 'MM' else 1
  8448. def make_gerber():
  8449. try:
  8450. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8451. header = 'G04*\n'
  8452. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8453. (str(self.version), str(self.version_date))
  8454. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8455. header += 'G04 Created on : %s*' % time_str + '\n'
  8456. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8457. header += "%MO{units}*%\n".format(units=gunits)
  8458. for apid in obj.apertures:
  8459. if obj.apertures[apid]['type'] == 'C':
  8460. header += "%ADD{apid}{type},{size}*%\n".format(
  8461. apid=str(apid),
  8462. type='C',
  8463. size=(factor * obj.apertures[apid]['size'])
  8464. )
  8465. elif obj.apertures[apid]['type'] == 'R':
  8466. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8467. apid=str(apid),
  8468. type='R',
  8469. width=(factor * obj.apertures[apid]['width']),
  8470. height=(factor * obj.apertures[apid]['height'])
  8471. )
  8472. elif obj.apertures[apid]['type'] == 'O':
  8473. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8474. apid=str(apid),
  8475. type='O',
  8476. width=(factor * obj.apertures[apid]['width']),
  8477. height=(factor * obj.apertures[apid]['height'])
  8478. )
  8479. header += '\n'
  8480. # obsolete units but some software may need it
  8481. if gunits == 'IN':
  8482. header += 'G70*\n'
  8483. else:
  8484. header += 'G71*\n'
  8485. # Absolute Mode
  8486. header += 'G90*\n'
  8487. header += 'G01*\n'
  8488. # positive polarity
  8489. header += '%LPD*%\n'
  8490. footer = 'M02*\n'
  8491. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8492. exported_gerber = header
  8493. exported_gerber += gerber_code
  8494. exported_gerber += footer
  8495. if local_use is None:
  8496. try:
  8497. with open(filename, 'w') as fp:
  8498. fp.write(exported_gerber)
  8499. except PermissionError:
  8500. self.inform.emit('[WARNING] %s' %
  8501. _("Permission denied, saving not possible.\n"
  8502. "Most likely another app is holding the file open and not accessible."))
  8503. return 'fail'
  8504. if self.defaults["global_open_style"] is False:
  8505. self.file_opened.emit("Gerber", filename)
  8506. self.file_saved.emit("Gerber", filename)
  8507. self.inform.emit('[success] %s: %s' %
  8508. (_("Gerber file exported to"), filename))
  8509. else:
  8510. return exported_gerber
  8511. except Exception as e:
  8512. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8513. return 'fail'
  8514. if use_thread is True:
  8515. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8516. def job_thread_grb(app_obj):
  8517. ret = make_gerber()
  8518. if ret == 'fail':
  8519. self.inform.emit('[ERROR_NOTCL] %s' %
  8520. _('Could not export Gerber file.'))
  8521. return
  8522. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8523. else:
  8524. ret = make_gerber()
  8525. if ret == 'fail':
  8526. self.inform.emit('[ERROR_NOTCL] %s' %
  8527. _('Could not export Gerber file.'))
  8528. return 'fail'
  8529. if local_use is not None:
  8530. return ret
  8531. def export_dxf(self, obj_name, filename, use_thread=True):
  8532. """
  8533. Exports a Geometry Object to an DXF file.
  8534. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8535. :param filename: Path to the DXF file to save to.
  8536. :param use_thread: if to be run in a separate thread
  8537. :return:
  8538. """
  8539. self.report_usage("export_dxf()")
  8540. if filename is None:
  8541. filename = self.defaults["global_last_save_folder"]
  8542. self.log.debug("export_dxf()")
  8543. format_exc = ''
  8544. units = ''
  8545. try:
  8546. obj = self.collection.get_by_name(str(obj_name))
  8547. except:
  8548. # TODO: The return behavior has not been established... should raise exception?
  8549. return "Could not retrieve object: %s" % obj_name
  8550. # updated units
  8551. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8552. if units == 'IN' or units == 'INCH':
  8553. units = 'INCH'
  8554. elif units == 'MM' or units == 'METIRC':
  8555. units ='METRIC'
  8556. def make_dxf():
  8557. try:
  8558. dxf_code = obj.export_dxf()
  8559. dxf_code.saveas(filename)
  8560. if self.defaults["global_open_style"] is False:
  8561. self.file_opened.emit("DXF", filename)
  8562. self.file_saved.emit("DXF", filename)
  8563. self.inform.emit('[success] %s: %s' %
  8564. (_("DXF file exported to"), filename))
  8565. except:
  8566. return 'fail'
  8567. if use_thread is True:
  8568. with self.proc_container.new(_("Exporting DXF")) as proc:
  8569. def job_thread_exc(app_obj):
  8570. ret = make_dxf()
  8571. if ret == 'fail':
  8572. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8573. _('Could not export DXF file.'))
  8574. return
  8575. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8576. else:
  8577. ret = make_dxf()
  8578. if ret == 'fail':
  8579. self.inform.emit('[WARNING_NOTCL] %s' %
  8580. _('Could not export DXF file.'))
  8581. return
  8582. def import_svg(self, filename, geo_type='geometry', outname=None):
  8583. """
  8584. Adds a new Geometry Object to the projects and populates
  8585. it with shapes extracted from the SVG file.
  8586. :param filename: Path to the SVG file.
  8587. :param geo_type: Type of FlatCAM object that will be created from SVG
  8588. :param outname:
  8589. :return:
  8590. """
  8591. self.report_usage("import_svg()")
  8592. obj_type = ""
  8593. if geo_type is None or geo_type == "geometry":
  8594. obj_type = "geometry"
  8595. elif geo_type == "gerber":
  8596. obj_type = geo_type
  8597. else:
  8598. self.inform.emit('[ERROR_NOTCL] %s' %
  8599. _("Not supported type is picked as parameter. "
  8600. "Only Geometry and Gerber are supported"))
  8601. return
  8602. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8603. def obj_init(geo_obj, app_obj):
  8604. geo_obj.import_svg(filename, obj_type, units=units)
  8605. geo_obj.multigeo = False
  8606. with self.proc_container.new(_("Importing SVG")) as proc:
  8607. # Object name
  8608. name = outname or filename.split('/')[-1].split('\\')[-1]
  8609. self.new_object(obj_type, name, obj_init, autoselected=False)
  8610. self.progress.emit(20)
  8611. # Register recent file
  8612. self.file_opened.emit("svg", filename)
  8613. # GUI feedback
  8614. self.inform.emit('[success] %s: %s' %
  8615. (_("Opened"), filename))
  8616. self.progress.emit(100)
  8617. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8618. """
  8619. Adds a new Geometry Object to the projects and populates
  8620. it with shapes extracted from the DXF file.
  8621. :param filename: Path to the DXF file.
  8622. :param geo_type: Type of FlatCAM object that will be created from DXF
  8623. :param outname:
  8624. :type putname: str
  8625. :return:
  8626. """
  8627. self.report_usage("import_dxf()")
  8628. obj_type = ""
  8629. if geo_type is None or geo_type == "geometry":
  8630. obj_type = "geometry"
  8631. elif geo_type == "gerber":
  8632. obj_type = geo_type
  8633. else:
  8634. self.inform.emit('[ERROR_NOTCL] %s' %
  8635. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8636. return
  8637. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8638. def obj_init(geo_obj, app_obj):
  8639. geo_obj.import_dxf(filename, obj_type, units=units)
  8640. geo_obj.multigeo = False
  8641. with self.proc_container.new(_("Importing DXF")) as proc:
  8642. # Object name
  8643. name = outname or filename.split('/')[-1].split('\\')[-1]
  8644. self.new_object(obj_type, name, obj_init, autoselected=False)
  8645. self.progress.emit(20)
  8646. # Register recent file
  8647. self.file_opened.emit("dxf", filename)
  8648. # GUI feedback
  8649. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8650. self.progress.emit(100)
  8651. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8652. """
  8653. Adds a new Geometry Object to the projects and populates
  8654. it with shapes extracted from the SVG file.
  8655. :param filename: Path to the SVG file.
  8656. :param o_type: type of FlatCAM objeect
  8657. :param dpi: dot per inch
  8658. :param mode: black or color
  8659. :param mask: dictate the level of detail
  8660. :param outname: name for the resulting file
  8661. :return:
  8662. """
  8663. self.report_usage("import_image()")
  8664. if o_type is None or o_type == "geometry":
  8665. obj_type = "geometry"
  8666. elif o_type == "gerber":
  8667. obj_type = o_type
  8668. else:
  8669. self.inform.emit('[ERROR_NOTCL] %s' %
  8670. _("Not supported type is picked as parameter. "
  8671. "Only Geometry and Gerber are supported"))
  8672. return
  8673. def obj_init(geo_obj, app_obj):
  8674. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8675. geo_obj.multigeo = False
  8676. with self.proc_container.new(_("Importing Image")) as proc:
  8677. # Object name
  8678. name = outname or filename.split('/')[-1].split('\\')[-1]
  8679. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8680. self.new_object(obj_type, name, obj_init)
  8681. self.progress.emit(20)
  8682. # Register recent file
  8683. self.file_opened.emit("image", filename)
  8684. # GUI feedback
  8685. self.inform.emit('[success] %s: %s' %
  8686. (_("Opened"), filename))
  8687. self.progress.emit(100)
  8688. def open_gerber(self, filename, outname=None):
  8689. """
  8690. Opens a Gerber file, parses it and creates a new object for
  8691. it in the program. Thread-safe.
  8692. :param outname: Name of the resulting object. None causes the
  8693. name to be that of the file.
  8694. :param filename: Gerber file filename
  8695. :type filename: str
  8696. :param follow: If true, the parser will not create polygons, just lines
  8697. following the gerber path.
  8698. :type follow: bool
  8699. :return: None
  8700. """
  8701. # How the object should be initialized
  8702. def obj_init(gerber_obj, app_obj):
  8703. assert isinstance(gerber_obj, FlatCAMGerber), \
  8704. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8705. # Opening the file happens here
  8706. self.progress.emit(30)
  8707. try:
  8708. gerber_obj.parse_file(filename)
  8709. except IOError:
  8710. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8711. (_("Failed to open file"), filename))
  8712. app_obj.progress.emit(0)
  8713. return "fail"
  8714. except ParseError as err:
  8715. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8716. (_("Failed to parse file"), filename, str(err)))
  8717. app_obj.progress.emit(0)
  8718. self.log.error(str(err))
  8719. return "fail"
  8720. except Exception as e:
  8721. log.debug("App.open_gerber() --> %s" % str(e))
  8722. msg = '[ERROR] %s' % \
  8723. _("An internal error has occurred. See shell.\n")
  8724. msg += traceback.format_exc()
  8725. app_obj.inform.emit(msg)
  8726. return "fail"
  8727. if gerber_obj.is_empty():
  8728. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8729. # self.collection.set_active(gerber_obj.options["name"])
  8730. # self.collection.delete_active()
  8731. self.inform.emit('[ERROR_NOTCL] %s' %
  8732. _("Object is not Gerber file or empty. Aborting object creation."))
  8733. return "fail"
  8734. # Further parsing
  8735. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8736. App.log.debug("open_gerber()")
  8737. with self.proc_container.new(_("Opening Gerber")) as proc:
  8738. self.progress.emit(10)
  8739. # Object name
  8740. name = outname or filename.split('/')[-1].split('\\')[-1]
  8741. # # ## Object creation # ##
  8742. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8743. if ret == 'fail':
  8744. self.inform.emit('[ERROR_NOTCL]%s' %
  8745. _(' Open Gerber failed. Probable not a Gerber file.'))
  8746. return
  8747. # Register recent file
  8748. self.file_opened.emit("gerber", filename)
  8749. self.progress.emit(100)
  8750. # GUI feedback
  8751. self.inform.emit('[success] %s: %s' %
  8752. (_("Opened"), filename))
  8753. def open_excellon(self, filename, outname=None, plot=True):
  8754. """
  8755. Opens an Excellon file, parses it and creates a new object for
  8756. it in the program. Thread-safe.
  8757. :param outname: Name of the resulting object. None causes the
  8758. name to be that of the file.
  8759. :param filename: Excellon file filename
  8760. :type filename: str
  8761. :return: None
  8762. """
  8763. App.log.debug("open_excellon()")
  8764. # How the object should be initialized
  8765. def obj_init(excellon_obj, app_obj):
  8766. # self.progress.emit(20)
  8767. try:
  8768. ret = excellon_obj.parse_file(filename=filename)
  8769. if ret == "fail":
  8770. log.debug("Excellon parsing failed.")
  8771. self.inform.emit('[ERROR_NOTCL] %s' %
  8772. _("This is not Excellon file."))
  8773. return "fail"
  8774. except IOError:
  8775. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8776. (_("Cannot open file"), filename))
  8777. log.debug("Could not open Excellon object.")
  8778. self.progress.emit(0) # TODO: self and app_bjj mixed
  8779. return "fail"
  8780. except:
  8781. msg = '[ERROR_NOTCL] %s' % \
  8782. _("An internal error has occurred. See shell.\n")
  8783. msg += traceback.format_exc()
  8784. app_obj.inform.emit(msg)
  8785. return "fail"
  8786. ret = excellon_obj.create_geometry()
  8787. if ret == 'fail':
  8788. log.debug("Could not create geometry for Excellon object.")
  8789. return "fail"
  8790. for tool in excellon_obj.tools:
  8791. if excellon_obj.tools[tool]['solid_geometry']:
  8792. return
  8793. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8794. (_("No geometry found in file"), filename))
  8795. return "fail"
  8796. with self.proc_container.new(_("Opening Excellon.")):
  8797. # Object name
  8798. name = outname or filename.split('/')[-1].split('\\')[-1]
  8799. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8800. if ret_val == 'fail':
  8801. self.inform.emit('[ERROR_NOTCL] %s' %
  8802. _('Open Excellon file failed. Probable not an Excellon file.'))
  8803. return
  8804. # Register recent file
  8805. self.file_opened.emit("excellon", filename)
  8806. # GUI feedback
  8807. self.inform.emit('[success] %s: %s' %
  8808. (_("Opened"), filename))
  8809. def open_gcode(self, filename, outname=None, plot=True):
  8810. """
  8811. Opens a G-gcode file, parses it and creates a new object for
  8812. it in the program. Thread-safe.
  8813. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8814. :param filename: G-code file filename
  8815. :type filename: str
  8816. :return: None
  8817. """
  8818. App.log.debug("open_gcode()")
  8819. # How the object should be initialized
  8820. def obj_init(job_obj, app_obj_):
  8821. """
  8822. :param job_obj: the resulting object
  8823. :type app_obj_: App
  8824. """
  8825. assert isinstance(app_obj_, App), \
  8826. "Initializer expected App, got %s" % type(app_obj_)
  8827. try:
  8828. f = open(filename)
  8829. gcode = f.read()
  8830. f.close()
  8831. except IOError:
  8832. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8833. (_("Failed to open"), filename))
  8834. return "fail"
  8835. job_obj.gcode = gcode
  8836. ret = job_obj.gcode_parse()
  8837. if ret == "fail":
  8838. self.inform.emit('[ERROR_NOTCL] %s' %
  8839. _("This is not GCODE"))
  8840. return "fail"
  8841. job_obj.create_geometry()
  8842. with self.proc_container.new(_("Opening G-Code.")):
  8843. # Object name
  8844. name = outname or filename.split('/')[-1].split('\\')[-1]
  8845. # New object creation and file processing
  8846. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8847. if ret == 'fail':
  8848. self.inform.emit('[ERROR_NOTCL] %s' %
  8849. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8850. "Attempting to create a FlatCAM CNCJob Object from "
  8851. "G-Code file failed during processing"))
  8852. return "fail"
  8853. # Register recent file
  8854. self.file_opened.emit("cncjob", filename)
  8855. # GUI feedback
  8856. self.inform.emit('[success] %s: %s' %
  8857. (_("Opened"), filename))
  8858. def open_script(self, filename, outname=None, silent=False):
  8859. """
  8860. Opens a Script file, parses it and creates a new object for
  8861. it in the program. Thread-safe.
  8862. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8863. :param filename: Script file filename
  8864. :type filename: str
  8865. :return: None
  8866. """
  8867. App.log.debug("open_script()")
  8868. with self.proc_container.new(_("Opening TCL Script...")):
  8869. try:
  8870. with open(filename, "r") as opened_script:
  8871. script_content = opened_script.readlines()
  8872. script_content = ''.join(script_content)
  8873. if silent is False:
  8874. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8875. except Exception as e:
  8876. log.debug("App.open_script() -> %s" % str(e))
  8877. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  8878. return
  8879. # Object name
  8880. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8881. # New object creation and file processing
  8882. self.on_filenewscript(name=script_name, text=script_content)
  8883. # Register recent file
  8884. self.file_opened.emit("script", filename)
  8885. # GUI feedback
  8886. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8887. def open_config_file(self, filename, run_from_arg=None):
  8888. """
  8889. Loads a config file from the specified file.
  8890. :param filename: Name of the file from which to load.
  8891. :type filename: str
  8892. :return: None
  8893. """
  8894. App.log.debug("Opening config file: " + filename)
  8895. if run_from_arg:
  8896. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8897. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8898. _("Opening FlatCAM Config file.")),
  8899. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8900. color=QtGui.QColor("gray"))
  8901. # add the tab if it was closed
  8902. self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8903. # first clear previous text in text editor (if any)
  8904. self.ui.text_editor_tab.code_editor.clear()
  8905. # Switch plot_area to CNCJob tab
  8906. self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8907. try:
  8908. if filename:
  8909. f = QtCore.QFile(filename)
  8910. if f.open(QtCore.QIODevice.ReadOnly):
  8911. stream = QtCore.QTextStream(f)
  8912. gcode_edited = stream.readAll()
  8913. self.ui.text_editor_tab.code_editor.setPlainText(gcode_edited)
  8914. f.close()
  8915. except IOError:
  8916. App.log.error("Failed to open config file: %s" % filename)
  8917. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8918. (_("Failed to open config file"), filename))
  8919. return
  8920. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8921. """
  8922. Loads a project from the specified file.
  8923. 1) Loads and parses file
  8924. 2) Registers the file as recently opened.
  8925. 3) Calls on_file_new()
  8926. 4) Updates options
  8927. 5) Calls new_object() with the object's from_dict() as init method.
  8928. 6) Calls plot_all() if plot=True
  8929. :param filename: Name of the file from which to load.
  8930. :type filename: str
  8931. :param run_from_arg: True if run for arguments
  8932. :param plot: If True plot all objects in the project
  8933. :param cli: run from command line
  8934. :return: None
  8935. """
  8936. App.log.debug("Opening project: " + filename)
  8937. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8938. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8939. if cli is None:
  8940. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8941. if run_from_arg:
  8942. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8943. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8944. _("Opening FlatCAM Project file.")),
  8945. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8946. color=QtGui.QColor("gray"))
  8947. # Open and parse an uncompressed Project file
  8948. try:
  8949. f = open(filename, 'r')
  8950. except IOError:
  8951. App.log.error("Failed to open project file: %s" % filename)
  8952. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8953. (_("Failed to open project file"), filename))
  8954. return
  8955. try:
  8956. d = json.load(f, object_hook=dict2obj)
  8957. except Exception as e:
  8958. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8959. (filename, str(e)))
  8960. f.close()
  8961. # Open and parse a compressed Project file
  8962. try:
  8963. with lzma.open(filename) as f:
  8964. file_content = f.read().decode('utf-8')
  8965. d = json.loads(file_content, object_hook=dict2obj)
  8966. except Exception as e:
  8967. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8968. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8969. (_("Failed to open project file"), filename))
  8970. return
  8971. # Clear the current project
  8972. # # NOT THREAD SAFE # ##
  8973. if run_from_arg is True:
  8974. pass
  8975. elif cli is True:
  8976. self.delete_selection_shape()
  8977. else:
  8978. self.on_file_new()
  8979. # Project options
  8980. self.options.update(d['options'])
  8981. self.project_filename = filename
  8982. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8983. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8984. if cli is None:
  8985. self.set_screen_units(self.options["units"])
  8986. # Re create objects
  8987. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8988. for obj in d['objs']:
  8989. def obj_init(obj_inst, app_inst):
  8990. obj_inst.from_dict(obj)
  8991. App.log.debug("Recreating from opened project an %s object: %s" %
  8992. (obj['kind'].capitalize(), obj['options']['name']))
  8993. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8994. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8995. if cli is None:
  8996. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8997. obj['kind'].upper(),
  8998. obj['options']['name']
  8999. )
  9000. )
  9001. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9002. self.inform.emit('[success] %s: %s' %
  9003. (_("Project loaded from"), filename))
  9004. self.should_we_save = False
  9005. self.file_opened.emit("project", filename)
  9006. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9007. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9008. if cli is None:
  9009. self.set_ui_title(name=self.project_filename)
  9010. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9011. def propagate_defaults(self, silent=False):
  9012. """
  9013. This method is used to set default values in classes. It's
  9014. an alternative to project options but allows the use
  9015. of values invisible to the user.
  9016. :return: None
  9017. """
  9018. if silent is False:
  9019. self.log.debug("propagate_defaults()")
  9020. # Which objects to update the given parameters.
  9021. routes = {
  9022. "global_zdownrate": CNCjob,
  9023. "excellon_zeros": Excellon,
  9024. "excellon_format_upper_in": Excellon,
  9025. "excellon_format_lower_in": Excellon,
  9026. "excellon_format_upper_mm": Excellon,
  9027. "excellon_format_lower_mm": Excellon,
  9028. "excellon_units": Excellon,
  9029. "gerber_use_buffer_for_union": Gerber,
  9030. "geometry_multidepth": Geometry
  9031. }
  9032. for param in routes:
  9033. if param in routes[param].defaults:
  9034. try:
  9035. routes[param].defaults[param] = self.defaults[param]
  9036. if silent is False:
  9037. self.log.debug(" " + param + " OK")
  9038. except KeyError:
  9039. if silent is False:
  9040. self.log.debug(" ERROR: " + param + " not in defaults.")
  9041. else:
  9042. # Try extracting the name:
  9043. # classname_param here is param in the object
  9044. if param.find(routes[param].__name__.lower() + "_") == 0:
  9045. p = param[len(routes[param].__name__) + 1:]
  9046. if p in routes[param].defaults:
  9047. routes[param].defaults[p] = self.defaults[param]
  9048. if silent is False:
  9049. self.log.debug(" " + param + " OK!")
  9050. def plot_all(self, zoom=True):
  9051. """
  9052. Re-generates all plots from all objects.
  9053. :return: None
  9054. """
  9055. self.log.debug("Plot_all()")
  9056. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9057. for obj in self.collection.get_list():
  9058. def worker_task(obj):
  9059. with self.proc_container.new("Plotting"):
  9060. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9061. if zoom:
  9062. self.object_plotted.emit(obj)
  9063. # Send to worker
  9064. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9065. def register_folder(self, filename):
  9066. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9067. def register_save_folder(self, filename):
  9068. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9069. def set_progress_bar(self, percentage, text=""):
  9070. self.ui.progress_bar.setValue(int(percentage))
  9071. def setup_shell(self):
  9072. """
  9073. Creates shell functions. Runs once at startup.
  9074. :return: None
  9075. """
  9076. self.log.debug("setup_shell()")
  9077. def shelp(p=None):
  9078. if not p:
  9079. return _("Available commands:\n") + \
  9080. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9081. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9082. if p not in commands:
  9083. return "Unknown command: %s" % p
  9084. return commands[p]["help"]
  9085. # --- Migrated to new architecture ---
  9086. # def options(name):
  9087. # ops = self.collection.get_by_name(str(name)).options
  9088. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9089. def h(*args):
  9090. """
  9091. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9092. and standalone parameters into list.
  9093. """
  9094. kwa = {}
  9095. a = []
  9096. n = len(args)
  9097. name = None
  9098. for i in range(n):
  9099. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9100. if match:
  9101. assert name is None
  9102. name = match.group(1)
  9103. continue
  9104. if name is None:
  9105. a.append(args[i])
  9106. else:
  9107. kwa[name] = args[i]
  9108. name = None
  9109. return a, kwa
  9110. @contextmanager
  9111. def wait_signal(signal, timeout=10000):
  9112. """
  9113. Block loop until signal emitted, timeout (ms) elapses
  9114. or unhandled exception happens in a thread.
  9115. :param timeout: time after which the loop is exited
  9116. :param signal: Signal to wait for.
  9117. """
  9118. loop = QtCore.QEventLoop()
  9119. # Normal termination
  9120. signal.connect(loop.quit)
  9121. # Termination by exception in thread
  9122. self.thread_exception.connect(loop.quit)
  9123. status = {'timed_out': False}
  9124. def report_quit():
  9125. status['timed_out'] = True
  9126. loop.quit()
  9127. yield
  9128. # Temporarily change how exceptions are managed.
  9129. oeh = sys.excepthook
  9130. ex = []
  9131. def except_hook(type_, value, traceback_):
  9132. ex.append(value)
  9133. oeh(type_, value, traceback_)
  9134. sys.excepthook = except_hook
  9135. # Terminate on timeout
  9136. if timeout is not None:
  9137. QtCore.QTimer.singleShot(timeout, report_quit)
  9138. # # ## Block ## ##
  9139. loop.exec_()
  9140. # Restore exception management
  9141. sys.excepthook = oeh
  9142. if ex:
  9143. self.raiseTclError(str(ex[0]))
  9144. if status['timed_out']:
  9145. raise Exception('Timed out!')
  9146. def make_docs():
  9147. output = ''
  9148. import collections
  9149. od = collections.OrderedDict(sorted(commands.items()))
  9150. for cmd_, val in od.items():
  9151. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9152. t = val['help']
  9153. usage_i = t.find('>')
  9154. if usage_i < 0:
  9155. expl = t
  9156. output += expl + '\n\n'
  9157. continue
  9158. expl = t[:usage_i - 1]
  9159. output += expl + '\n\n'
  9160. end_usage_i = t[usage_i:].find('\n')
  9161. if end_usage_i < 0:
  9162. end_usage_i = len(t[usage_i:])
  9163. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9164. else:
  9165. extras = t[usage_i+end_usage_i+1:]
  9166. parts = [s.strip() for s in extras.split('\n')]
  9167. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9168. for p in parts:
  9169. output += ' ' + p + '\n\n'
  9170. return output
  9171. '''
  9172. Howto implement TCL shell commands:
  9173. All parameters passed to command should be possible to set as None and test it afterwards.
  9174. This is because we need to see error caused in tcl,
  9175. if None value as default parameter is not allowed TCL will return empty error.
  9176. Use:
  9177. def mycommand(name=None,...):
  9178. Test it like this:
  9179. if name is None:
  9180. self.raise_tcl_error('Argument name is missing.')
  9181. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9182. otherwise we will miss it and processing will silently continue.
  9183. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9184. which is catched in exec_command and displayed in TCL shell console with red background.
  9185. Error in console is displayed with TCL trace.
  9186. This behavior works only within main thread,
  9187. errors with promissed tasks can be catched and detected only with log.
  9188. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9189. TCL shell.
  9190. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9191. '''
  9192. commands = {
  9193. 'help': {
  9194. 'fcn': shelp,
  9195. 'help': _("Shows list of commands.")
  9196. },
  9197. }
  9198. # Import/overwrite tcl commands as objects of TclCommand descendants
  9199. # This modifies the variable 'commands'.
  9200. tclCommands.register_all_commands(self, commands)
  9201. # Add commands to the tcl interpreter
  9202. for cmd in commands:
  9203. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9204. # Make the tcl puts function return instead of print to stdout
  9205. self.tcl.eval('''
  9206. rename puts original_puts
  9207. proc puts {args} {
  9208. if {[llength $args] == 1} {
  9209. return "[lindex $args 0]"
  9210. } else {
  9211. eval original_puts $args
  9212. }
  9213. }
  9214. ''')
  9215. def setup_recent_items(self):
  9216. # TODO: Move this to constructor
  9217. icons = {
  9218. "gerber": "share/flatcam_icon16.png",
  9219. "excellon": "share/drill16.png",
  9220. 'geometry': "share/geometry16.png",
  9221. "cncjob": "share/cnc16.png",
  9222. "script": "share/script_new24.png",
  9223. "document": "share/notes16_1.png",
  9224. "project": "share/project16.png",
  9225. "svg": "share/geometry16.png",
  9226. "dxf": "share/dxf16.png",
  9227. "pdf": "share/pdf32.png",
  9228. "image": "share/image16.png"
  9229. }
  9230. openers = {
  9231. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9232. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9233. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9234. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9235. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9236. "document": None,
  9237. 'project': self.open_project,
  9238. 'svg': self.import_svg,
  9239. 'dxf': self.import_dxf,
  9240. 'image': self.import_image,
  9241. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9242. }
  9243. # Open recent file for files
  9244. try:
  9245. f = open(self.data_path + '/recent.json')
  9246. except IOError:
  9247. App.log.error("Failed to load recent item list.")
  9248. self.inform.emit('[ERROR_NOTCL] %s' %
  9249. _("Failed to load recent item list."))
  9250. return
  9251. try:
  9252. self.recent = json.load(f)
  9253. except json.scanner.JSONDecodeError:
  9254. App.log.error("Failed to parse recent item list.")
  9255. self.inform.emit('[ERROR_NOTCL] %s' %
  9256. _("Failed to parse recent item list."))
  9257. f.close()
  9258. return
  9259. f.close()
  9260. # Open recent file for projects
  9261. try:
  9262. fp = open(self.data_path + '/recent_projects.json')
  9263. except IOError:
  9264. App.log.error("Failed to load recent project item list.")
  9265. self.inform.emit('[ERROR_NOTCL] %s' %
  9266. _("Failed to load recent projects item list."))
  9267. return
  9268. try:
  9269. self.recent_projects = json.load(fp)
  9270. except json.scanner.JSONDecodeError:
  9271. App.log.error("Failed to parse recent project item list.")
  9272. self.inform.emit('[ERROR_NOTCL] %s' %
  9273. _("Failed to parse recent project item list."))
  9274. fp.close()
  9275. return
  9276. fp.close()
  9277. # Closure needed to create callbacks in a loop.
  9278. # Otherwise late binding occurs.
  9279. def make_callback(func, fname):
  9280. def opener():
  9281. func(fname)
  9282. return opener
  9283. def reset_recent_files():
  9284. # Reset menu
  9285. self.ui.recent.clear()
  9286. self.recent = []
  9287. try:
  9288. f = open(self.data_path + '/recent.json', 'w')
  9289. except IOError:
  9290. App.log.error("Failed to open recent items file for writing.")
  9291. return
  9292. json.dump(self.recent, f)
  9293. def reset_recent_projects():
  9294. # Reset menu
  9295. self.ui.recent_projects.clear()
  9296. self.recent_projects = []
  9297. try:
  9298. fp = open(self.data_path + '/recent_projects.json', 'w')
  9299. except IOError:
  9300. App.log.error("Failed to open recent projects items file for writing.")
  9301. return
  9302. json.dump(self.recent, fp)
  9303. # Reset menu
  9304. self.ui.recent.clear()
  9305. self.ui.recent_projects.clear()
  9306. # Create menu items for projects
  9307. for recent in self.recent_projects:
  9308. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9309. if recent['kind'] == 'project':
  9310. try:
  9311. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9312. # Attach callback
  9313. o = make_callback(openers[recent["kind"]], recent['filename'])
  9314. action.triggered.connect(o)
  9315. self.ui.recent_projects.addAction(action)
  9316. except KeyError:
  9317. App.log.error("Unsupported file type: %s" % recent["kind"])
  9318. # Last action in Recent Files menu is one that Clear the content
  9319. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9320. clear_action_proj.triggered.connect(reset_recent_projects)
  9321. self.ui.recent_projects.addSeparator()
  9322. self.ui.recent_projects.addAction(clear_action_proj)
  9323. # Create menu items for files
  9324. for recent in self.recent:
  9325. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9326. if recent['kind'] != 'project':
  9327. try:
  9328. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9329. # Attach callback
  9330. o = make_callback(openers[recent["kind"]], recent['filename'])
  9331. action.triggered.connect(o)
  9332. self.ui.recent.addAction(action)
  9333. except KeyError:
  9334. App.log.error("Unsupported file type: %s" % recent["kind"])
  9335. # Last action in Recent Files menu is one that Clear the content
  9336. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9337. clear_action.triggered.connect(reset_recent_files)
  9338. self.ui.recent.addSeparator()
  9339. self.ui.recent.addAction(clear_action)
  9340. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9341. # self.ui.menufilerecent.set_submenu(recent_menu)
  9342. # recent_menu.show_all()
  9343. # self.ui.recent.show()
  9344. self.log.debug("Recent items list has been populated.")
  9345. def setup_component_editor(self):
  9346. # label = QtWidgets.QLabel("Choose an item from Project")
  9347. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9348. sel_title = QtWidgets.QTextEdit(
  9349. _('<b>Shortcut Key List</b>'))
  9350. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9351. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9352. settings = QSettings("Open Source", "FlatCAM")
  9353. if settings.contains("notebook_font_size"):
  9354. fsize = settings.value('notebook_font_size', type=int)
  9355. else:
  9356. fsize = 12
  9357. tsize = fsize + int(fsize / 2)
  9358. # selected_text = (_('''
  9359. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9360. #
  9361. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9362. # The normal flow when working in FlatCAM is the following:</span></p>
  9363. #
  9364. # <ol>
  9365. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9366. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9367. # even dragging and dropping the files on the GUI.<br />
  9368. # <br />
  9369. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9370. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9371. # &nbsp;</li>
  9372. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9373. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9374. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9375. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9376. # <br />
  9377. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9378. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9379. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9380. # it even if it was out of focus.<br />
  9381. # <br />
  9382. # You can change the parameters in this screen and the flow direction is like this:<br />
  9383. # <br />
  9384. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9385. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9386. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9387. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9388. # </ol>
  9389. #
  9390. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9391. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9392. # <strong>F3</strong>.</span></p>
  9393. #
  9394. # ''').format(fsize=fsize, tsize=tsize))
  9395. selected_text = '''
  9396. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9397. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9398. {s1}</span></p>
  9399. <ol>
  9400. <li><span style="font-size:{fsize}px">{s2}<br />
  9401. <br />
  9402. {s3}</span><br />
  9403. &nbsp;</li>
  9404. <li><span style="font-size:{fsize}px">{s4}<br />
  9405. &nbsp;</li>
  9406. <br />
  9407. <li><span style="font-size:{fsize}px">{s5}<br />
  9408. &nbsp;</li>
  9409. <br />
  9410. <li><span style="font-size:{fsize}px">{s6}<br />
  9411. <br />
  9412. {s7}</span></li>
  9413. </ol>
  9414. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9415. '''.format(
  9416. title=_("Selected Tab - Choose an Item from Project Tab"),
  9417. subtitle=_("Details"),
  9418. s1=_("The normal flow when working in FlatCAM is the following:"),
  9419. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9420. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9421. "files on the GUI."),
  9422. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9423. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9424. "actions offered within the app."),
  9425. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9426. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9427. "SELECTED TAB will be updated with the object properties according to its kind: "
  9428. "Gerber, Excellon, Geometry or CNCJob object."),
  9429. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9430. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9431. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9432. "the SELECTED TAB and populate it even if it was out of focus."),
  9433. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9434. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9435. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9436. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9437. "(again, done in SELECTED TAB) --> Save GCode."),
  9438. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9439. "or through its own key shortcut: <b>F3</b>."),
  9440. tsize=tsize,
  9441. fsize=fsize
  9442. )
  9443. sel_title.setText(selected_text)
  9444. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9445. self.ui.selected_scroll_area.setWidget(sel_title)
  9446. def setup_obj_classes(self):
  9447. """
  9448. Sets up application specifics on the FlatCAMObj class.
  9449. :return: None
  9450. """
  9451. FlatCAMObj.app = self
  9452. ObjectCollection.app = self
  9453. Gerber.app = self
  9454. Excellon.app = self
  9455. Geometry.app = self
  9456. CNCjob.app = self
  9457. FCProcess.app = self
  9458. FCProcessContainer.app = self
  9459. def version_check(self):
  9460. """
  9461. Checks for the latest version of the program. Alerts the
  9462. user if theirs is outdated. This method is meant to be run
  9463. in a separate thread.
  9464. :return: None
  9465. """
  9466. self.log.debug("version_check()")
  9467. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9468. full_url = App.version_url + \
  9469. "?s=" + str(self.defaults['global_serial']) + \
  9470. "&v=" + str(self.version) + \
  9471. "&os=" + str(self.os) + \
  9472. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9473. else:
  9474. # no_stats dict; just so it won't break things on website
  9475. no_ststs_dict = {}
  9476. no_ststs_dict["global_ststs"] = {}
  9477. full_url = App.version_url + \
  9478. "?s=" + str(self.defaults['global_serial']) + \
  9479. "&v=" + str(self.version) + \
  9480. "&os=" + str(self.os) + \
  9481. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9482. App.log.debug("Checking for updates @ %s" % full_url)
  9483. # ## Get the data
  9484. try:
  9485. f = urllib.request.urlopen(full_url)
  9486. except:
  9487. # App.log.warning("Failed checking for latest version. Could not connect.")
  9488. self.log.warning("Failed checking for latest version. Could not connect.")
  9489. self.inform.emit('[WARNING_NOTCL] %s' %
  9490. _("Failed checking for latest version. Could not connect."))
  9491. return
  9492. try:
  9493. data = json.load(f)
  9494. except Exception as e:
  9495. App.log.error("Could not parse information about latest version.")
  9496. self.inform.emit('[ERROR_NOTCL] %s' %
  9497. _("Could not parse information about latest version."))
  9498. App.log.debug("json.load(): %s" % str(e))
  9499. f.close()
  9500. return
  9501. f.close()
  9502. # ## Latest version?
  9503. if self.version >= data["version"]:
  9504. App.log.debug("FlatCAM is up to date!")
  9505. self.inform.emit('[success] %s' %
  9506. _("FlatCAM is up to date!"))
  9507. return
  9508. App.log.debug("Newer version available.")
  9509. self.message.emit(
  9510. _("Newer Version Available"),
  9511. _("There is a newer version of FlatCAM available for download:\n\n") +
  9512. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9513. _("info")
  9514. )
  9515. def on_plotcanvas_setup(self, container=None):
  9516. """
  9517. This is doing the setup for the plot area (VisPy canvas)
  9518. :param container: widget where to install the canvas
  9519. :return: None
  9520. """
  9521. if container:
  9522. plot_container = container
  9523. else:
  9524. plot_container = self.ui.right_layout
  9525. if self.is_legacy is False:
  9526. self.plotcanvas = PlotCanvas(plot_container, self)
  9527. else:
  9528. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9529. # So it can receive key presses
  9530. self.plotcanvas.native.setFocus()
  9531. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9532. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9533. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9534. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_double_click_over_plot)
  9535. # Keys over plot enabled
  9536. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9537. if self.defaults['global_cursor_type'] == 'small':
  9538. self.app_cursor = self.plotcanvas.new_cursor()
  9539. else:
  9540. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9541. if self.ui.grid_snap_btn.isChecked():
  9542. self.app_cursor.enabled = True
  9543. else:
  9544. self.app_cursor.enabled = False
  9545. if self.is_legacy is False:
  9546. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9547. else:
  9548. # will use the default Matplotlib axes
  9549. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9550. def on_zoom_fit(self, event):
  9551. """
  9552. Callback for zoom-out request. This can be either from the corresponding
  9553. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9554. with axes limits from the geometry bounds of all objects.
  9555. :param event: Ignored.
  9556. :return: None
  9557. """
  9558. if self.is_legacy is False:
  9559. self.plotcanvas.fit_view()
  9560. else:
  9561. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9562. width = xmax - xmin
  9563. height = ymax - ymin
  9564. xmin -= 0.05 * width
  9565. xmax += 0.05 * width
  9566. ymin -= 0.05 * height
  9567. ymax += 0.05 * height
  9568. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9569. def on_zoom_in(self):
  9570. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9571. def on_zoom_out(self):
  9572. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9573. def disable_all_plots(self):
  9574. self.report_usage("disable_all_plots()")
  9575. self.disable_plots(self.collection.get_list())
  9576. self.inform.emit('[success] %s' %
  9577. _("All plots disabled."))
  9578. def disable_other_plots(self):
  9579. self.report_usage("disable_other_plots()")
  9580. self.disable_plots(self.collection.get_non_selected())
  9581. self.inform.emit('[success] %s' %
  9582. _("All non selected plots disabled."))
  9583. def enable_all_plots(self):
  9584. self.report_usage("enable_all_plots()")
  9585. self.enable_plots(self.collection.get_list())
  9586. self.inform.emit('[success] %s' %
  9587. _("All plots enabled."))
  9588. def on_enable_sel_plots(self):
  9589. log.debug("App.on_enable_sel_plot()")
  9590. object_list = self.collection.get_selected()
  9591. self.enable_plots(objects=object_list)
  9592. self.inform.emit('[success] %s' %
  9593. _("Selected plots enabled..."))
  9594. def on_disable_sel_plots(self):
  9595. log.debug("App.on_disable_sel_plot()")
  9596. # self.inform.emit(_("Disabling plots ..."))
  9597. object_list = self.collection.get_selected()
  9598. self.disable_plots(objects=object_list)
  9599. self.inform.emit('[success] %s' %
  9600. _("Selected plots disabled..."))
  9601. def enable_plots(self, objects):
  9602. """
  9603. Disables plots
  9604. :param objects: list of Objects to be enabled
  9605. :return:
  9606. """
  9607. log.debug("Enabling plots ...")
  9608. # self.inform.emit(_("Working ..."))
  9609. for obj in objects:
  9610. if obj.options['plot'] is False:
  9611. obj.options.set_change_callback(lambda x: None)
  9612. obj.options['plot'] = True
  9613. obj.options.set_change_callback(obj.on_options_change)
  9614. def worker_task(objects):
  9615. with self.proc_container.new(_("Enabling plots ...")):
  9616. for obj in objects:
  9617. # obj.options['plot'] = True
  9618. if isinstance(obj, FlatCAMCNCjob):
  9619. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9620. else:
  9621. obj.plot(visible=True)
  9622. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9623. # self.plots_updated.emit()
  9624. def disable_plots(self, objects):
  9625. """
  9626. Disables plots
  9627. :param objects: list of Objects to be disabled
  9628. :return:
  9629. """
  9630. # if no objects selected then do nothing
  9631. if not self.collection.get_selected():
  9632. return
  9633. log.debug("Disabling plots ...")
  9634. # self.inform.emit(_("Working ..."))
  9635. for obj in objects:
  9636. if obj.options['plot'] is True:
  9637. obj.options.set_change_callback(lambda x: None)
  9638. obj.options['plot'] = False
  9639. obj.options.set_change_callback(obj.on_options_change)
  9640. try:
  9641. self.delete_selection_shape()
  9642. except Exception as e:
  9643. log.debug("App.disable_plots() --> %s" % str(e))
  9644. # self.plots_updated.emit()
  9645. def worker_task(objects):
  9646. with self.proc_container.new(_("Disabling plots ...")):
  9647. for obj in objects:
  9648. # obj.options['plot'] = True
  9649. if isinstance(obj, FlatCAMCNCjob):
  9650. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9651. else:
  9652. obj.plot(visible=False)
  9653. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9654. def toggle_plots(self, objects):
  9655. """
  9656. Toggle plots visibility
  9657. :param objects: list of Objects for which to be toggled the visibility
  9658. :return:
  9659. """
  9660. # if no objects selected then do nothing
  9661. if not self.collection.get_selected():
  9662. return
  9663. log.debug("Toggling plots ...")
  9664. self.inform.emit(_("Working ..."))
  9665. for obj in objects:
  9666. if obj.options['plot'] is False:
  9667. obj.options['plot'] = True
  9668. else:
  9669. obj.options['plot'] = False
  9670. self.plots_updated.emit()
  9671. def clear_plots(self):
  9672. objects = self.collection.get_list()
  9673. for obj in objects:
  9674. obj.clear(obj == objects[-1])
  9675. # Clear pool to free memory
  9676. self.clear_pool()
  9677. def generate_cnc_job(self, objects):
  9678. self.report_usage("generate_cnc_job()")
  9679. # for obj in objects:
  9680. # obj.generatecncjob()
  9681. for obj in objects:
  9682. obj.on_generatecnc_button_click()
  9683. def save_project(self, filename, quit_action=False, silent=False):
  9684. """
  9685. Saves the current project to the specified file.
  9686. :param filename: Name of the file in which to save.
  9687. :type filename: str
  9688. :param quit_action: if the project saving will be followed by an app quit; boolean
  9689. :param silent: if True will not display status messages
  9690. :return: None
  9691. """
  9692. self.log.debug("save_project()")
  9693. self.save_in_progress = True
  9694. with self.proc_container.new(_("Saving FlatCAM Project")):
  9695. # Capture the latest changes
  9696. # Current object
  9697. try:
  9698. self.collection.get_active().read_form()
  9699. except:
  9700. self.log.debug("There was no active object")
  9701. pass
  9702. # Project options
  9703. self.options_read_form()
  9704. # Serialize the whole project
  9705. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9706. "options": self.options,
  9707. "version": self.version}
  9708. if self.defaults["global_save_compressed"] is True:
  9709. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9710. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9711. # # Write
  9712. f.write(g)
  9713. self.inform.emit('[success] %s: %s' %
  9714. (_("Project saved to"), filename))
  9715. else:
  9716. # Open file
  9717. try:
  9718. f = open(filename, 'w')
  9719. except IOError:
  9720. App.log.error("Failed to open file for saving: %s", filename)
  9721. return
  9722. # Write
  9723. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9724. f.close()
  9725. # verification of the saved project
  9726. # Open and parse
  9727. try:
  9728. saved_f = open(filename, 'r')
  9729. except IOError:
  9730. if silent is False:
  9731. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9732. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9733. )
  9734. return
  9735. try:
  9736. saved_d = json.load(saved_f, object_hook=dict2obj)
  9737. except:
  9738. if silent is False:
  9739. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9740. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9741. )
  9742. f.close()
  9743. return
  9744. saved_f.close()
  9745. if silent is False:
  9746. if 'version' in saved_d:
  9747. self.inform.emit('[success] %s: %s' %
  9748. (_("Project saved to"), filename))
  9749. else:
  9750. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9751. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9752. )
  9753. settings = QSettings("Open Source", "FlatCAM")
  9754. lock_state = self.ui.lock_action.isChecked()
  9755. settings.setValue('toolbar_lock', lock_state)
  9756. # This will write the setting to the platform specific storage.
  9757. del settings
  9758. # if quit:
  9759. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9760. # t.start()
  9761. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9762. def start_delayed_quit(self, delay, filename, should_quit=None):
  9763. """
  9764. :param delay: period of checking if project file size is more than zero; in seconds
  9765. :param filename: the name of the project file to be checked periodically for size more than zero
  9766. :param should_quit: if the task finished will be followed by an app quit; boolean
  9767. :return:
  9768. """
  9769. to_quit = should_quit
  9770. self.save_timer = QtCore.QTimer()
  9771. self.save_timer.setInterval(delay)
  9772. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9773. self.save_timer.start()
  9774. def check_project_file_size(self, filename, should_quit=None):
  9775. """
  9776. :param filename: the name of the project file to be checked periodically for size more than zero
  9777. :param should_quit: will quit the app if True; boolean
  9778. :return:
  9779. """
  9780. try:
  9781. if os.stat(filename).st_size > 0:
  9782. self.save_in_progress = False
  9783. self.save_timer.stop()
  9784. if should_quit:
  9785. self.app_quit.emit()
  9786. except Exception as e:
  9787. traceback.print_exc()
  9788. def on_plotarea_tab_closed(self, tab_idx):
  9789. widget = self.ui.plot_tab_area.widget(tab_idx)
  9790. if widget is not None:
  9791. print(widget.objectName())
  9792. if widget.objectName() == 'text_editor_tab':
  9793. print("aha")
  9794. widget.deleteLater()
  9795. self.ui.plot_tab_area.removeTab(tab_idx)
  9796. def on_options_app2project(self):
  9797. """
  9798. Callback for Options->Transfer Options->App=>Project. Copies options
  9799. from application defaults to project defaults.
  9800. :return: None
  9801. """
  9802. self.report_usage("on_options_app2project")
  9803. self.defaults_read_form()
  9804. self.options.update(self.defaults)
  9805. self.options_write_form()
  9806. def on_options_project2app(self):
  9807. """
  9808. Callback for Options->Transfer Options->Project=>App. Copies options
  9809. from project defaults to application defaults.
  9810. :return: None
  9811. """
  9812. self.report_usage("on_options_project2app")
  9813. self.options_read_form()
  9814. self.defaults.update(self.options)
  9815. self.defaults_write_form()
  9816. def on_options_project2object(self):
  9817. """
  9818. Callback for Options->Transfer Options->Project=>Object. Copies options
  9819. from project defaults to the currently selected object.
  9820. :return: None
  9821. """
  9822. self.report_usage("on_options_project2object")
  9823. self.options_read_form()
  9824. obj = self.collection.get_active()
  9825. if obj is None:
  9826. self.inform.emit('[WARNING_NOTCL] %s' %
  9827. _("No object selected."))
  9828. return
  9829. for option in self.options:
  9830. if option.find(obj.kind + "_") == 0:
  9831. oname = option[len(obj.kind) + 1:]
  9832. obj.options[oname] = self.options[option]
  9833. obj.to_form() # Update UI
  9834. def on_options_object2project(self):
  9835. """
  9836. Callback for Options->Transfer Options->Object=>Project. Copies options
  9837. from the currently selected object to project defaults.
  9838. :return: None
  9839. """
  9840. self.report_usage("on_options_object2project")
  9841. obj = self.collection.get_active()
  9842. if obj is None:
  9843. self.inform.emit('[WARNING_NOTCL] %s' %
  9844. _("No object selected."))
  9845. return
  9846. obj.read_form()
  9847. for option in obj.options:
  9848. if option in ['name']: # TODO: Handle this better...
  9849. continue
  9850. self.options[obj.kind + "_" + option] = obj.options[option]
  9851. self.options_write_form()
  9852. def on_options_object2app(self):
  9853. """
  9854. Callback for Options->Transfer Options->Object=>App. Copies options
  9855. from the currently selected object to application defaults.
  9856. :return: None
  9857. """
  9858. self.report_usage("on_options_object2app")
  9859. obj = self.collection.get_active()
  9860. if obj is None:
  9861. self.inform.emit('[WARNING_NOTCL] %s' %
  9862. _("No object selected."))
  9863. return
  9864. obj.read_form()
  9865. for option in obj.options:
  9866. if option in ['name']: # TODO: Handle this better...
  9867. continue
  9868. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9869. self.defaults_write_form()
  9870. def on_options_app2object(self):
  9871. """
  9872. Callback for Options->Transfer Options->App=>Object. Copies options
  9873. from application defaults to the currently selected object.
  9874. :return: None
  9875. """
  9876. self.report_usage("on_options_app2object")
  9877. self.defaults_read_form()
  9878. obj = self.collection.get_active()
  9879. if obj is None:
  9880. self.inform.emit('[WARNING_NOTCL] %s' %
  9881. _("No object selected."))
  9882. return
  9883. for option in self.defaults:
  9884. if option.find(obj.kind + "_") == 0:
  9885. oname = option[len(obj.kind) + 1:]
  9886. obj.options[oname] = self.defaults[option]
  9887. obj.to_form() # Update UI
  9888. class ArgsThread(QtCore.QObject):
  9889. open_signal = pyqtSignal(list)
  9890. start = pyqtSignal()
  9891. if sys.platform == 'win32':
  9892. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9893. else:
  9894. address = ('/tmp/testipc', 'AF_UNIX')
  9895. def __init__(self):
  9896. super(ArgsThread, self).__init__()
  9897. self.start.connect(self.run)
  9898. def my_loop(self, address):
  9899. try:
  9900. listener = Listener(*address)
  9901. while True:
  9902. conn = listener.accept()
  9903. self.serve(conn)
  9904. except socket.error as e:
  9905. conn = Client(*address)
  9906. conn.send(sys.argv)
  9907. conn.send('close')
  9908. # close the current instance only if there are args
  9909. if len(sys.argv) > 1:
  9910. sys.exit()
  9911. def serve(self, conn):
  9912. while True:
  9913. msg = conn.recv()
  9914. if msg == 'close':
  9915. break
  9916. self.open_signal.emit(msg)
  9917. conn.close()
  9918. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9919. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9920. @pyqtSlot()
  9921. def run(self):
  9922. self.my_loop(self.address)
  9923. class GracefulException(Exception):
  9924. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9925. def __init__(self):
  9926. super().__init__()
  9927. def __str__(self):
  9928. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  9929. # end of file