FlatCAMApp.py 476 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749
  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 shutil
  16. from datetime import datetime
  17. import time
  18. import ctypes
  19. import traceback
  20. from PyQt5.QtCore import pyqtSlot, Qt
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Diverse
  37. from FlatCAMCommon import LoudDict, color_variant, ExclusionAreas
  38. from FlatCAMBookmark import BookmarkManager
  39. from FlatCAMDB import ToolsDB2
  40. from vispy.gloo.util import _screenshot
  41. from vispy.io import write_png
  42. # FlatCAM Objects
  43. from defaults import FlatCAMDefaults
  44. from flatcamGUI.preferences.OptionsGroupUI import OptionsGroupUI
  45. from flatcamGUI.preferences.PreferencesUIManager import PreferencesUIManager
  46. from flatcamObjects.ObjectCollection import *
  47. from flatcamObjects.FlatCAMObj import FlatCAMObj
  48. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  49. from flatcamObjects.FlatCAMDocument import DocumentObject
  50. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  51. from flatcamObjects.FlatCAMGeometry import GeometryObject
  52. from flatcamObjects.FlatCAMGerber import GerberObject
  53. from flatcamObjects.FlatCAMScript import ScriptObject
  54. # FlatCAM Parsing files
  55. from flatcamParsers.ParseExcellon import Excellon
  56. from flatcamParsers.ParseGerber import Gerber
  57. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  58. # FlatCAM GUI
  59. from flatcamGUI.PlotCanvas import *
  60. from flatcamGUI.PlotCanvasLegacy import *
  61. from flatcamGUI.FlatCAMGUI import *
  62. from flatcamGUI.GUIElements import FCFileSaveDialog
  63. # FlatCAM Pre-processors
  64. from FlatCAMPostProc import load_preprocessors
  65. # FlatCAM Editors
  66. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  67. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  68. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  69. from flatcamEditors.FlatCAMTextEditor import TextEditor
  70. from flatcamParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from FlatCAMProcess import *
  73. from FlatCAMWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from flatcamTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import FlatCAMTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = 8.993
  138. version_date = "2020/08/01"
  139. beta = True
  140. engine = '3D'
  141. # current date now
  142. date = str(datetime.today()).rpartition('.')[0]
  143. date = ''.join(c for c in date if c not in ':-')
  144. date = date.replace(' ', '_')
  145. # ###############################################################################################################
  146. # ############################################ URLS's ###########################################################
  147. # ###############################################################################################################
  148. # URL for update checks and statistics
  149. version_url = "http://flatcam.org/version"
  150. # App URL
  151. app_url = "http://flatcam.org"
  152. # Manual URL
  153. manual_url = "http://flatcam.org/manual/index.html"
  154. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  155. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  156. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  157. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  158. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  159. # this variable will hold the project status
  160. # if True it will mean that the project was modified and not saved
  161. should_we_save = False
  162. # flag is True if saving action has been triggered
  163. save_in_progress = False
  164. # ###############################################################################################################
  165. # ####################################### APP Signals ######################################################
  166. # ###############################################################################################################
  167. # Inform the user
  168. # Handled by:
  169. # * App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal(str)
  171. app_quit = QtCore.pyqtSignal()
  172. # General purpose background task
  173. worker_task = QtCore.pyqtSignal(dict)
  174. # File opened
  175. # Handled by:
  176. # * register_folder()
  177. # * register_recent()
  178. # Note: Setting the parameters to unicode does not seem
  179. # to have an effect. Then are received as Qstring
  180. # anyway.
  181. # File type and filename
  182. file_opened = QtCore.pyqtSignal(str, str)
  183. # File type and filename
  184. file_saved = QtCore.pyqtSignal(str, str)
  185. # Percentage of progress
  186. progress = QtCore.pyqtSignal(int)
  187. plots_updated = QtCore.pyqtSignal()
  188. # Emitted by new_object() and passes the new object as argument, plot flag.
  189. # on_object_created() adds the object to the collection, plots on appropriate flag
  190. # and emits new_object_available.
  191. object_created = QtCore.pyqtSignal(object, bool, bool)
  192. # Emitted when a object has been changed (like scaled, mirrored)
  193. object_changed = QtCore.pyqtSignal(object)
  194. # Emitted after object has been plotted.
  195. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  196. object_plotted = QtCore.pyqtSignal(object)
  197. # Emitted when a new object has been added or deleted from/to the collection
  198. object_status_changed = QtCore.pyqtSignal(object, str, str)
  199. message = QtCore.pyqtSignal(str, str, str)
  200. # Emmited when shell command is finished(one command only)
  201. shell_command_finished = QtCore.pyqtSignal(object)
  202. # Emitted when multiprocess pool has been recreated
  203. pool_recreated = QtCore.pyqtSignal(object)
  204. # Emitted when an unhandled exception happens
  205. # in the worker task.
  206. thread_exception = QtCore.pyqtSignal(object)
  207. # used to signal that there are arguments for the app
  208. args_at_startup = QtCore.pyqtSignal(list)
  209. # a reusable signal to replot a list of objects
  210. # should be disconnected after use so it can be reused
  211. replot_signal = pyqtSignal(list)
  212. # signal emitted when jumping
  213. jump_signal = pyqtSignal(tuple)
  214. # signal emitted when jumping
  215. locate_signal = pyqtSignal(tuple, str)
  216. # close app signal
  217. close_app_signal = pyqtSignal()
  218. # will perform the cleanup operation after a Graceful Exit
  219. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  220. # graphic residues behind
  221. cleanup = pyqtSignal()
  222. def __init__(self, user_defaults=True):
  223. """
  224. Starts the application.
  225. :return: app
  226. :rtype: App
  227. """
  228. super().__init__()
  229. App.log.info("FlatCAM Starting...")
  230. self.main_thread = QtWidgets.QApplication.instance().thread()
  231. # ############################################################################################################
  232. # ################# Setup the listening thread for another instance launching with args ######################
  233. # ############################################################################################################
  234. if sys.platform == 'win32' or sys.platform == 'linux':
  235. # make sure the thread is stored by using a self. otherwise it's garbage collected
  236. self.th = QtCore.QThread()
  237. self.th.start(priority=QtCore.QThread.LowestPriority)
  238. self.new_launch = ArgsThread()
  239. self.new_launch.open_signal[list].connect(self.on_startup_args)
  240. self.new_launch.moveToThread(self.th)
  241. self.new_launch.start.emit()
  242. # ############################################################################################################
  243. # # ######################################## OS-specific #####################################################
  244. # ############################################################################################################
  245. portable = False
  246. # Folder for user settings.
  247. if sys.platform == 'win32':
  248. if platform.architecture()[0] == '32bit':
  249. App.log.debug("Win32!")
  250. else:
  251. App.log.debug("Win64!")
  252. # #######################################################################################################
  253. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  254. # #######################################################################################################
  255. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  256. try:
  257. with open(config_file, 'r'):
  258. pass
  259. except FileNotFoundError:
  260. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  261. try:
  262. with open(config_file, 'r') as f:
  263. try:
  264. for line in f:
  265. param = str(line).replace('\n', '').rpartition('=')
  266. if param[0] == 'portable':
  267. try:
  268. portable = eval(param[2])
  269. except NameError:
  270. portable = False
  271. if param[0] == 'headless':
  272. if param[2].lower() == 'true':
  273. self.cmd_line_headless = 1
  274. else:
  275. self.cmd_line_headless = None
  276. except Exception as e:
  277. log.debug('App.__init__() -->%s' % str(e))
  278. return
  279. except FileNotFoundError as e:
  280. log.debug(str(e))
  281. pass
  282. if portable is False:
  283. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  284. else:
  285. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  286. self.os = 'windows'
  287. else: # Linux/Unix/MacOS
  288. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  289. self.os = 'unix'
  290. # ############################################################################################################
  291. # ################################# Setup folders and files ##################################################
  292. # ############################################################################################################
  293. if not os.path.exists(self.data_path):
  294. os.makedirs(self.data_path)
  295. App.log.debug('Created data folder: ' + self.data_path)
  296. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  297. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  298. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  299. if not os.path.exists(self.preprocessorpaths):
  300. os.makedirs(self.preprocessorpaths)
  301. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  302. # create geo_tools_db.FlatDB file if there is none
  303. try:
  304. f = open(self.data_path + '/geo_tools_db.FlatDB')
  305. f.close()
  306. except IOError:
  307. App.log.debug('Creating empty geo_tool_db.FlatDB')
  308. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  309. json.dump({}, f)
  310. f.close()
  311. # create current_defaults.FlatConfig file if there is none
  312. try:
  313. f = open(self.data_path + '/current_defaults.FlatConfig')
  314. f.close()
  315. except IOError:
  316. App.log.debug('Creating empty current_defaults.FlatConfig')
  317. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  318. json.dump({}, f)
  319. f.close()
  320. # Write factory_defaults.FlatConfig file to disk
  321. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  322. # create a recent files json file if there is none
  323. try:
  324. f = open(self.data_path + '/recent.json')
  325. f.close()
  326. except IOError:
  327. App.log.debug('Creating empty recent.json')
  328. f = open(self.data_path + '/recent.json', 'w')
  329. json.dump([], f)
  330. f.close()
  331. # create a recent projects json file if there is none
  332. try:
  333. fp = open(self.data_path + '/recent_projects.json')
  334. fp.close()
  335. except IOError:
  336. App.log.debug('Creating empty recent_projects.json')
  337. fp = open(self.data_path + '/recent_projects.json', 'w')
  338. json.dump([], fp)
  339. fp.close()
  340. # Application directory. CHDIR to it. Otherwise, trying to load
  341. # GUI icons will fail as their path is relative.
  342. # This will fail under cx_freeze ...
  343. self.app_home = os.path.dirname(os.path.realpath(__file__))
  344. App.log.debug("Application path is " + self.app_home)
  345. App.log.debug("Started in " + os.getcwd())
  346. # cx_freeze workaround
  347. if os.path.isfile(self.app_home):
  348. self.app_home = os.path.dirname(self.app_home)
  349. os.chdir(self.app_home)
  350. # ############################################################################################################
  351. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  352. # ############################################################################################################
  353. self.defaults = FlatCAMDefaults()
  354. self.defaults["root_folder_path"] = self.app_home
  355. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  356. if user_defaults:
  357. self.defaults.load(filename=current_defaults_path)
  358. if self.defaults['units'] == 'MM':
  359. self.decimals = int(self.defaults['decimals_metric'])
  360. else:
  361. self.decimals = int(self.defaults['decimals_inch'])
  362. if self.defaults["global_gray_icons"] is False:
  363. self.resource_location = 'assets/resources'
  364. else:
  365. self.resource_location = 'assets/resources/dark_resources'
  366. self.current_units = self.defaults['units']
  367. # ###########################################################################################################
  368. # #################################### SETUP OBJECT CLASSES #################################################
  369. # ###########################################################################################################
  370. self.setup_obj_classes()
  371. # ###########################################################################################################
  372. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  373. # ###########################################################################################################
  374. self.pool = Pool()
  375. # ###########################################################################################################
  376. # ###################################### Setting the Splash Screen ##########################################
  377. # ###########################################################################################################
  378. splash_settings = QSettings("Open Source", "FlatCAM")
  379. if splash_settings.contains("splash_screen"):
  380. show_splash = splash_settings.value("splash_screen")
  381. else:
  382. splash_settings.setValue('splash_screen', 1)
  383. # This will write the setting to the platform specific storage.
  384. del splash_settings
  385. show_splash = 1
  386. if show_splash and self.cmd_line_headless != 1:
  387. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  388. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  389. # self.splash.setMask(splash_pix.mask())
  390. # move splashscreen to the current monitor
  391. desktop = QtWidgets.QApplication.desktop()
  392. screen = desktop.screenNumber(QtGui.QCursor.pos())
  393. current_screen_center = desktop.availableGeometry(screen).center()
  394. self.splash.move(current_screen_center - self.splash.rect().center())
  395. self.splash.show()
  396. self.splash.showMessage(_("FlatCAM is initializing ..."),
  397. alignment=Qt.AlignBottom | Qt.AlignLeft,
  398. color=QtGui.QColor("gray"))
  399. else:
  400. show_splash = 0
  401. # ###########################################################################################################
  402. # ######################################### Initialize GUI ##################################################
  403. # ###########################################################################################################
  404. # FlatCAM colors used in plotting
  405. self.FC_light_green = '#BBF268BF'
  406. self.FC_dark_green = '#006E20BF'
  407. self.FC_light_blue = '#a5a5ffbf'
  408. self.FC_dark_blue = '#0000ffbf'
  409. self.ui = FlatCAMGUI(self)
  410. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  411. if theme_settings.contains("theme"):
  412. theme = theme_settings.value('theme', type=str)
  413. else:
  414. theme = 'white'
  415. if self.defaults["global_cursor_color_enabled"]:
  416. self.cursor_color_3D = self.defaults["global_cursor_color"]
  417. else:
  418. if theme == 'white':
  419. self.cursor_color_3D = 'black'
  420. else:
  421. self.cursor_color_3D = 'gray'
  422. # update the defaults dict with the setting in QSetting
  423. self.defaults['global_theme'] = theme
  424. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  425. self.ui.final_save.connect(self.final_save)
  426. # restore the toolbar view
  427. self.restore_toolbar_view()
  428. # restore the GUI geometry
  429. self.restore_main_win_geom()
  430. # set FlatCAM units in the Status bar
  431. self.set_screen_units(self.defaults['units'])
  432. # ###########################################################################################################
  433. # ########################################### AUTOSAVE SETUP ################################################
  434. # ###########################################################################################################
  435. self.block_autosave = False
  436. self.autosave_timer = QtCore.QTimer(self)
  437. self.save_project_auto_update()
  438. self.autosave_timer.timeout.connect(self.save_project_auto)
  439. # ###########################################################################################################
  440. # #################################### LOAD PREPROCESSORS ###################################################
  441. # ###########################################################################################################
  442. # ----------------------------------------- WARNING --------------------------------------------------------
  443. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  444. # That's because the number of preprocessors can vary and here the comboboxes are populated
  445. # -----------------------------------------------------------------------------------------------------------
  446. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  447. # the preprocessor file
  448. self.preprocessors = load_preprocessors(self)
  449. # make sure that always the 'default' preprocessor is the first item in the dictionary
  450. if 'default' in self.preprocessors.keys():
  451. new_ppp_dict = {}
  452. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  453. default_pp = self.preprocessors.pop('default')
  454. new_ppp_dict['default'] = default_pp
  455. # then add the rest of the keys
  456. for name, val_class in self.preprocessors.items():
  457. new_ppp_dict[name] = val_class
  458. # and now put back the ordered dict with 'default' key first
  459. self.preprocessors = new_ppp_dict
  460. for name in list(self.preprocessors.keys()):
  461. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  462. if name.partition('_')[0] == 'Paste':
  463. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  464. continue
  465. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  466. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  467. if name == 'hpgl':
  468. continue
  469. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  470. # ###########################################################################################################
  471. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  472. # ###########################################################################################################
  473. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  474. inform=self.inform)
  475. self.preferencesUiManager.defaults_write_form()
  476. # When the self.defaults dictionary changes will update the Preferences GUI forms
  477. self.defaults.set_change_callback(self.on_defaults_dict_change)
  478. # ###########################################################################################################
  479. # ##################################### FIRST RUN SECTION ###################################################
  480. # ################################ It's done only once after install #####################################
  481. # ###########################################################################################################
  482. if self.defaults["first_run"] is True:
  483. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  484. initial_lay = 'minimal'
  485. layout_field = self.preferencesUiManager.get_form_field("layout")
  486. layout_field.setCurrentIndex(layout_field.findText(initial_lay))
  487. self.ui.set_layout(initial_lay)
  488. # after the first run, this object should be False
  489. self.defaults["first_run"] = False
  490. self.preferencesUiManager.save_defaults(silent=True)
  491. # ###########################################################################################################
  492. # ############################################ Data #########################################################
  493. # ###########################################################################################################
  494. self.recent = []
  495. self.recent_projects = []
  496. self.clipboard = QtWidgets.QApplication.clipboard()
  497. self.project_filename = None
  498. self.toggle_units_ignore = False
  499. # ###########################################################################################################
  500. # ########################################## LOAD LANGUAGES ################################################
  501. # ###########################################################################################################
  502. self.languages = fcTranslate.load_languages()
  503. language_field = self.preferencesUiManager.get_form_field("global_language")
  504. for name in sorted(self.languages.values()):
  505. language_field.addItem(name)
  506. # ###########################################################################################################
  507. # ####################################### APPLY APP LANGUAGE ################################################
  508. # ###########################################################################################################
  509. ret_val = fcTranslate.apply_language('strings')
  510. if ret_val == "no language":
  511. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  512. log.debug("Could not find the Language files. The App strings are missing.")
  513. else:
  514. # make the current language the current selection on the language combobox
  515. self.preferencesUiManager.get_form_field("global_language").setCurrentText(ret_val)
  516. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  517. # ###########################################################################################################
  518. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  519. # ###########################################################################################################
  520. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  521. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  522. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  523. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  524. self.defaults.propagate_defaults()
  525. # ###########################################################################################################
  526. # ######################################## UPDATE THE OPTIONS ###############################################
  527. # ###########################################################################################################
  528. self.options = LoudDict()
  529. # -----------------------------------------------------------------------------------------------------------
  530. # Update the self.options from the self.defaults
  531. # The self.defaults holds the application defaults while the self.options holds the object defaults
  532. # -----------------------------------------------------------------------------------------------------------
  533. # Copy app defaults to project options
  534. for def_key, def_val in self.defaults.items():
  535. self.options[def_key] = deepcopy(def_val)
  536. self.preferencesUiManager.show_preferences_gui()
  537. # ### End of Data ####
  538. # ###########################################################################################################
  539. # #################################### SETUP OBJECT COLLECTION ##############################################
  540. # ###########################################################################################################
  541. self.collection = ObjectCollection(self)
  542. self.ui.project_tab_layout.addWidget(self.collection.view)
  543. # ### Adjust tabs width ## ##
  544. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  545. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  546. self.collection.view.setMinimumWidth(290)
  547. self.log.debug("Finished creating Object Collection.")
  548. # ###########################################################################################################
  549. # ######################################## SETUP Plot Area ##################################################
  550. # ###########################################################################################################
  551. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  552. if self.defaults["global_graphic_engine"] == '3D':
  553. self.is_legacy = False
  554. else:
  555. self.is_legacy = True
  556. # Event signals disconnect id holders
  557. self.mp = None
  558. self.mm = None
  559. self.mr = None
  560. self.mdc = None
  561. self.mp_zc = None
  562. self.kp = None
  563. # Matplotlib axis
  564. self.axes = None
  565. if show_splash:
  566. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  567. "Canvas initialization started."),
  568. alignment=Qt.AlignBottom | Qt.AlignLeft,
  569. color=QtGui.QColor("gray"))
  570. start_plot_time = time.time() # debug
  571. self.plotcanvas = None
  572. self.app_cursor = None
  573. self.hover_shapes = None
  574. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  575. # setup the PlotCanvas
  576. self.on_plotcanvas_setup()
  577. end_plot_time = time.time()
  578. self.used_time = end_plot_time - start_plot_time
  579. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  580. if show_splash:
  581. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  582. "Canvas initialization started.\n"
  583. "Canvas initialization finished in"), '%.2f' % self.used_time),
  584. alignment=Qt.AlignBottom | Qt.AlignLeft,
  585. color=QtGui.QColor("gray"))
  586. self.ui.splitter.setStretchFactor(1, 2)
  587. # ###########################################################################################################
  588. # ############################################### SYS TRAY ##################################################
  589. # ###########################################################################################################
  590. if self.defaults["global_systray_icon"]:
  591. self.parent_w = QtWidgets.QWidget()
  592. if self.cmd_line_headless == 1:
  593. self.trayIcon = FlatCAMSystemTray(app=self,
  594. icon=QtGui.QIcon(self.resource_location +
  595. '/flatcam_icon32_green.png'),
  596. headless=True,
  597. parent=self.parent_w)
  598. else:
  599. self.trayIcon = FlatCAMSystemTray(app=self,
  600. icon=QtGui.QIcon(self.resource_location +
  601. '/flatcam_icon32_green.png'),
  602. parent=self.parent_w)
  603. # ###########################################################################################################
  604. # ############################################### Worker SETUP ##############################################
  605. # ###########################################################################################################
  606. if self.defaults["global_worker_number"]:
  607. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  608. else:
  609. self.workers = WorkerStack(workers_number=2)
  610. self.worker_task.connect(self.workers.add_task)
  611. self.log.debug("Finished creating Workers crew.")
  612. # ###########################################################################################################
  613. # ############################################# Activity Monitor ###########################################
  614. # ###########################################################################################################
  615. self.activity_view = FlatCAMActivityView(app=self)
  616. self.ui.infobar.addWidget(self.activity_view)
  617. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  618. # ###########################################################################################################
  619. # ############################################# Signal handling #############################################
  620. # ###########################################################################################################
  621. # ########################################## Custom signals ################################################
  622. # signal for displaying messages in status bar
  623. self.inform.connect(self.info)
  624. # signal to be called when the app is quiting
  625. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  626. self.message.connect(self.message_dialog)
  627. # self.progress.connect(self.set_progress_bar)
  628. # signals that are emitted when object state changes
  629. self.object_created.connect(self.on_object_created)
  630. self.object_changed.connect(self.on_object_changed)
  631. self.object_plotted.connect(self.on_object_plotted)
  632. self.plots_updated.connect(self.on_plots_updated)
  633. # signals emitted when file state change
  634. self.file_opened.connect(self.register_recent)
  635. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  636. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  637. # ########################################## Standard signals ###############################################
  638. # ### Menu
  639. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  640. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  641. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  642. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  643. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  644. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  645. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  646. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  647. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  648. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  649. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  650. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  651. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  652. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  653. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  654. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  655. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  656. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  657. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  658. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  659. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  660. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  661. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  662. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  663. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  664. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  665. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  666. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  667. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  668. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  669. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  670. self.ui.menufile_exit.triggered.connect(self.final_save)
  671. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  672. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  673. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  674. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  675. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  676. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  677. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  678. self.ui.menueditdelete.triggered.connect(self.on_delete)
  679. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  680. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  681. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  682. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  683. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  684. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  685. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  686. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  687. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  688. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  689. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  690. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  691. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  692. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  693. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  694. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  695. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  696. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  697. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  698. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  699. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  700. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  701. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  702. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  703. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  704. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  705. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  706. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  707. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  708. self.ui.menuview_replot.triggered.connect(self.plot_all)
  709. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  710. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  711. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  712. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  713. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  714. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  715. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  716. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  717. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  718. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  719. self.ui.menuhelp_about.triggered.connect(self.on_about)
  720. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  721. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  722. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  723. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  724. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  725. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  726. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  727. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  728. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  729. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  730. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  731. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  732. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  733. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  734. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  735. # ToolBar signals
  736. self.connect_toolbar_signals()
  737. # Notebook and Plot Tab Area signals
  738. # make the right click on the notebook tab and plot tab area tab raise a menu
  739. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  740. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  741. self.on_tab_setup_context_menu()
  742. # activate initial state
  743. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  744. # Context Menu
  745. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  746. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  747. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  748. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  749. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  750. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  751. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  752. self.ui.clearplot.triggered.connect(self.clear_plots)
  753. self.ui.replot.triggered.connect(self.plot_all)
  754. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  755. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  756. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  757. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  758. self.ui.popmenu_move.triggered.connect(self.obj_move)
  759. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  760. # Project Context Menu -> Color Setting
  761. for act in self.ui.menuprojectcolor.actions():
  762. act.triggered.connect(self.on_set_color_action_triggered)
  763. # ###########################################################################################################
  764. # #################################### GUI PREFERENCES SIGNALS ##############################################
  765. # ###########################################################################################################
  766. self.preferencesUiManager.get_form_field("units").activated_custom.connect(
  767. lambda: self.on_toggle_units(no_pref=False))
  768. # ##################################### Workspace Setting Signals ###########################################
  769. self.preferencesUiManager.get_form_field("global_workspaceT").currentIndexChanged.connect(
  770. self.on_workspace_modified)
  771. self.preferencesUiManager.get_form_field("global_workspace_orientation").activated_custom.connect(
  772. self.on_workspace_modified
  773. )
  774. self.preferencesUiManager.get_form_field("global_workspace").stateChanged.connect(self.on_workspace)
  775. # ###########################################################################################################
  776. # ######################################## GUI SETTINGS SIGNALS #############################################
  777. # ###########################################################################################################
  778. self.preferencesUiManager.get_form_field("global_graphic_engine").activated_custom.connect(self.on_app_restart)
  779. self.preferencesUiManager.get_form_field("global_cursor_type").activated_custom.connect(self.on_cursor_type)
  780. # ######################################## Tools related signals ############################################
  781. # Film Tool
  782. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  783. self.on_film_color_entry)
  784. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  785. self.on_film_color_button)
  786. # QRCode Tool
  787. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  788. self.on_qrcode_fill_color_entry)
  789. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  790. self.on_qrcode_fill_color_button)
  791. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  792. self.on_qrcode_back_color_entry)
  793. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  794. self.on_qrcode_back_color_button)
  795. # portability changed signal
  796. self.preferencesUiManager.get_form_field("global_portable").stateChanged.connect(self.on_portable_checked)
  797. # Object list
  798. self.collection.view.activated.connect(self.on_row_activated)
  799. self.collection.item_selected.connect(self.on_row_selected)
  800. self.object_status_changed.connect(self.on_collection_updated)
  801. # when there are arguments at application startup this get launched
  802. self.args_at_startup[list].connect(self.on_startup_args)
  803. # ###########################################################################################################
  804. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  805. # ###########################################################################################################
  806. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  807. lambda: self.restore_extensions(ext_type='excellon'))
  808. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  809. lambda: self.restore_extensions(ext_type='gcode'))
  810. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  811. lambda: self.restore_extensions(ext_type='gerber'))
  812. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  813. lambda: self.delete_all_extensions(ext_type='excellon'))
  814. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  815. lambda: self.delete_all_extensions(ext_type='gcode'))
  816. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  817. lambda: self.delete_all_extensions(ext_type='gerber'))
  818. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  819. lambda: self.add_extension(ext_type='excellon'))
  820. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  821. lambda: self.add_extension(ext_type='gcode'))
  822. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  823. lambda: self.add_extension(ext_type='gerber'))
  824. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  825. lambda: self.del_extension(ext_type='excellon'))
  826. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  827. lambda: self.del_extension(ext_type='gcode'))
  828. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  829. lambda: self.del_extension(ext_type='gerber'))
  830. # connect the 'Apply' buttons from the Preferences/File Associations
  831. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  832. lambda: self.on_register_files(obj_type='excellon'))
  833. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  834. lambda: self.on_register_files(obj_type='gcode'))
  835. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  836. lambda: self.on_register_files(obj_type='gerber'))
  837. # ###########################################################################################################
  838. # ########################################### KEYWORDS SIGNALS ##############################################
  839. # ###########################################################################################################
  840. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  841. lambda: self.restore_extensions(ext_type='keyword'))
  842. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  843. lambda: self.delete_all_extensions(ext_type='keyword'))
  844. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  845. lambda: self.add_extension(ext_type='keyword'))
  846. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  847. lambda: self.del_extension(ext_type='keyword'))
  848. # connect the abort_all_tasks related slots to the related signals
  849. self.proc_container.idle_flag.connect(self.app_is_idle)
  850. # signal emitted when a tab is closed in the Plot Area
  851. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  852. # signal to close the application
  853. self.close_app_signal.connect(self.kill_app)
  854. # ################################# FINISHED CONNECTING SIGNALS #############################################
  855. # ###########################################################################################################
  856. # ###########################################################################################################
  857. # ###########################################################################################################
  858. self.log.debug("Finished connecting Signals.")
  859. # ###########################################################################################################
  860. # ########################################## Other setups ###################################################
  861. # ###########################################################################################################
  862. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  863. # depending on from where those tools are called different actions can be done
  864. self.call_source = 'app'
  865. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  866. self.tool_tab_locked = False
  867. # decide if to show or hide the Notebook side of the screen at startup
  868. if self.defaults["global_project_at_startup"] is True:
  869. self.ui.splitter.setSizes([1, 1])
  870. else:
  871. self.ui.splitter.setSizes([0, 1])
  872. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  873. self.setup_component_editor()
  874. # ###########################################################################################################
  875. # ####################################### Auto-complete KEYWORDS ############################################
  876. # ###########################################################################################################
  877. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  878. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  879. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  880. 'export_exc',
  881. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  882. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  883. 'interiors', 'isolate', 'join_excellon',
  884. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  885. 'mirror', 'ncc',
  886. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  887. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  888. 'options', 'origin',
  889. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  890. 'save', 'save_project',
  891. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  892. 'skew', 'subtract_poly', 'subtract_rectangle',
  893. 'version', 'write_gcode'
  894. ]
  895. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  896. 'Paste_1',
  897. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  898. 'Toolchange_manual', 'True', 'Users',
  899. 'all', 'auto', 'axis',
  900. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  901. 'contour', 'default',
  902. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  903. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  904. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  905. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  906. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  907. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  908. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  909. 'spacing_columns',
  910. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  911. 'toolchange_xy', 'toolchangez', 'travelz',
  912. 'tooldia', 'use_threads', 'value',
  913. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  914. ]
  915. self.tcl_keywords = [
  916. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  917. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  918. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  919. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  920. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  921. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  922. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  923. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  924. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  925. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  926. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  927. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  928. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  929. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  930. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  931. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  932. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  933. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  934. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  935. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  936. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  937. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  938. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  939. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  940. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  941. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  942. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  943. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  944. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  945. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  946. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  947. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  948. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  949. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  950. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  951. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  952. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  953. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  954. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  955. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  956. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  957. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  958. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  959. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  960. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  961. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  962. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  963. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  964. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  965. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  966. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  967. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  968. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  969. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  970. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  971. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  972. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  973. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  974. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  975. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  976. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  977. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  978. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  979. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  980. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  981. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  982. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  983. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  984. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  985. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  986. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  987. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  988. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  989. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  990. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  991. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  992. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  993. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  994. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  995. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  996. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  997. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  998. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  999. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1000. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1001. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1002. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1003. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1004. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1005. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1006. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1007. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1008. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1009. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1010. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1011. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1012. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1013. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1014. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1015. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1016. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1017. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1018. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1019. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1020. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1021. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1022. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1023. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1024. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1025. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1026. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1027. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1028. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1029. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1030. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1031. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1032. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1033. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1034. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1035. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1036. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1037. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1038. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1039. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1040. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1041. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1042. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1043. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1044. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1045. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1046. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1047. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1048. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1049. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1050. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1051. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1052. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1053. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1054. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1055. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1056. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1057. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1058. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1059. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1060. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1061. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1062. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1063. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1064. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1065. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1066. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1067. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1068. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1069. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1070. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1071. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1072. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1073. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1074. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1075. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1076. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1077. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1078. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1079. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1080. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1081. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1082. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1083. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1084. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1085. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1086. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1087. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1088. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1089. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1090. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1091. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1092. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1093. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1094. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1095. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1096. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1097. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1098. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1099. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1100. ]
  1101. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1102. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1103. # ###########################################################################################################
  1104. # ############################################## Shell SETUP ################################################
  1105. # ###########################################################################################################
  1106. self.shell = FCShell(app=self, version=self.version)
  1107. self.ui.shell_dock.setWidget(self.shell)
  1108. self.log.debug("TCL Shell has been initialized.")
  1109. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1110. if self.defaults["global_shell_at_startup"]:
  1111. self.ui.shell_dock.show()
  1112. else:
  1113. self.ui.shell_dock.hide()
  1114. # ###########################################################################################################
  1115. # ########################################## Tools and Plugins ##############################################
  1116. # ###########################################################################################################
  1117. self.dblsidedtool = None
  1118. self.distance_tool = None
  1119. self.distance_min_tool = None
  1120. self.panelize_tool = None
  1121. self.film_tool = None
  1122. self.paste_tool = None
  1123. self.calculator_tool = None
  1124. self.rules_tool = None
  1125. self.sub_tool = None
  1126. self.move_tool = None
  1127. self.cutout_tool = None
  1128. self.ncclear_tool = None
  1129. self.optimal_tool = None
  1130. self.paint_tool = None
  1131. self.transform_tool = None
  1132. self.properties_tool = None
  1133. self.pdf_tool = None
  1134. self.image_tool = None
  1135. self.pcb_wizard_tool = None
  1136. self.cal_exc_tool = None
  1137. self.qrcode_tool = None
  1138. self.copper_thieving_tool = None
  1139. self.fiducial_tool = None
  1140. self.edrills_tool = None
  1141. self.align_objects_tool = None
  1142. self.punch_tool = None
  1143. self.invert_tool = None
  1144. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1145. try:
  1146. self.install_tools()
  1147. except AttributeError as e:
  1148. log.debug("App.__init__() install tools() --> %s" % str(e))
  1149. # ###########################################################################################################
  1150. # ############################################ SETUP RECENT ITEMS ###########################################
  1151. # ###########################################################################################################
  1152. self.setup_recent_items()
  1153. # ###########################################################################################################
  1154. # ######################################### BookMarks Manager ###############################################
  1155. # ###########################################################################################################
  1156. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1157. self.install_bookmarks()
  1158. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1159. # ###########################################################################################################
  1160. # ########################################### Tools Database ################################################
  1161. # ###########################################################################################################
  1162. self.tools_db_tab = None
  1163. # ### System Font Parsing ###
  1164. # self.f_parse = ParseFont(self)
  1165. # self.parse_system_fonts()
  1166. # ###########################################################################################################
  1167. # ######################################### Check for updates ###############################################
  1168. # ###########################################################################################################
  1169. # Separate thread (Not worker)
  1170. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1171. if (self.beta is False or self.beta is None) and \
  1172. self.preferencesUiManager.get_form_field("global_version_check").get_value() is True:
  1173. App.log.info("Checking for updates in background (this is version %s)." % str(self.version))
  1174. # self.thr2 = QtCore.QThread()
  1175. self.worker_task.emit({'fcn': self.version_check,
  1176. 'params': []})
  1177. # self.thr2.start(QtCore.QThread.LowPriority)
  1178. # ###########################################################################################################
  1179. # ##################################### Register files with FlatCAM; #######################################
  1180. # ################################### It works only for Windows for now ####################################
  1181. # ###########################################################################################################
  1182. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1183. self.on_register_files()
  1184. # ###########################################################################################################
  1185. # ######################################## Variables for global usage #######################################
  1186. # ###########################################################################################################
  1187. # hold the App units
  1188. self.units = 'MM'
  1189. # coordinates for relative position display
  1190. self.rel_point1 = (0, 0)
  1191. self.rel_point2 = (0, 0)
  1192. # variable to store coordinates
  1193. self.pos = (0, 0)
  1194. self.pos_canvas = (0, 0)
  1195. self.pos_jump = (0, 0)
  1196. # variable to store mouse coordinates
  1197. self.mouse = [0, 0]
  1198. # variable to store the delta positions on cavnas
  1199. self.dx = 0
  1200. self.dy = 0
  1201. # decide if we have a double click or single click
  1202. self.doubleclick = False
  1203. # store here the is_dragging value
  1204. self.event_is_dragging = False
  1205. # variable to store if a command is active (then the var is not None) and which one it is
  1206. self.command_active = None
  1207. # variable to store the status of moving selection action
  1208. # None value means that it's not an selection action
  1209. # True value = a selection from left to right
  1210. # False value = a selection from right to left
  1211. self.selection_type = None
  1212. # List to store the objects that are currently loaded in FlatCAM
  1213. # This list is updated on each object creation or object delete
  1214. self.all_objects_list = []
  1215. self.objects_under_the_click_list = []
  1216. # List to store the objects that are selected
  1217. self.sel_objects_list = []
  1218. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1219. self.key_modifiers = None
  1220. # Variable to hold the status of the axis
  1221. self.toggle_axis = True
  1222. # Variable to hold the status of the grid lines
  1223. self.toggle_grid_lines = True
  1224. # Variable to store the status of the fullscreen event
  1225. self.toggle_fscreen = False
  1226. # Variable to store the status of the code editor
  1227. self.toggle_codeeditor = False
  1228. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1229. self.click_noproject = False
  1230. self.cursor = None
  1231. # Variable to store the GCODE that was edited
  1232. self.gcode_edited = ""
  1233. self.text_editor_tab = None
  1234. # reference for the self.ui.code_editor
  1235. self.reference_code_editor = None
  1236. self.script_code = ''
  1237. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1238. self.tools_db_changed_flag = False
  1239. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1240. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1241. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1242. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1243. 'tsm']
  1244. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1245. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1246. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1247. 'sbp', 'tap', 'xpi']
  1248. self.svg_list = ['svg']
  1249. self.dxf_list = ['dxf']
  1250. self.pdf_list = ['pdf']
  1251. self.prj_list = ['flatprj']
  1252. self.conf_list = ['flatconfig']
  1253. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1254. # flag for polygons not cleared
  1255. self.poly_not_cleared = False
  1256. # VisPy visuals
  1257. self.isHovering = False
  1258. self.notHovering = True
  1259. # Window geometry
  1260. self.x_pos = None
  1261. self.y_pos = None
  1262. self.width = None
  1263. self.height = None
  1264. # when True, the app has to return from any thread
  1265. self.abort_flag = False
  1266. # set the value used in the Windows Title
  1267. self.engine = self.preferencesUiManager.get_form_field("global_graphic_engine").get_value()
  1268. # this holds a widget that is installed in the Plot Area when View Source option is used
  1269. self.source_editor_tab = None
  1270. self.pagesize = {}
  1271. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1272. # VisPy visuals
  1273. if self.is_legacy is False:
  1274. try:
  1275. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1276. except AttributeError:
  1277. self.tool_shapes = None
  1278. else:
  1279. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1280. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1281. # used in the delayed shutdown self.start_delayed_quit() method
  1282. self.save_timer = None
  1283. # ###########################################################################################################
  1284. # ################################## ADDING FlatCAM EDITORS section #########################################
  1285. # ###########################################################################################################
  1286. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1287. # at the first launch of the App , the editors will not be functional.
  1288. try:
  1289. self.geo_editor = FlatCAMGeoEditor(self)
  1290. except AttributeError:
  1291. pass
  1292. try:
  1293. self.exc_editor = FlatCAMExcEditor(self)
  1294. except AttributeError:
  1295. pass
  1296. try:
  1297. self.grb_editor = FlatCAMGrbEditor(self)
  1298. except AttributeError:
  1299. pass
  1300. self.log.debug("Finished adding FlatCAM Editor's.")
  1301. self.set_ui_title(name=_("New Project - Not saved"))
  1302. # ###########################################################################################################
  1303. # ########################################### EXCLUSION AREAS ###############################################
  1304. # ###########################################################################################################
  1305. self.exc_areas = ExclusionAreas(app=self)
  1306. # ###########################################################################################################
  1307. # ##################################### Finished the CONSTRUCTOR ############################################
  1308. # ###########################################################################################################
  1309. App.log.debug("END of constructor. Releasing control.")
  1310. # ###########################################################################################################
  1311. # ########################################## SHOW GUI #######################################################
  1312. # ###########################################################################################################
  1313. # if the app is not started as headless, show it
  1314. if self.cmd_line_headless != 1:
  1315. if show_splash:
  1316. # finish the splash
  1317. self.splash.finish(self.ui)
  1318. mgui_settings = QSettings("Open Source", "FlatCAM")
  1319. if mgui_settings.contains("maximized_gui"):
  1320. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1321. if maximized_ui is True:
  1322. self.ui.showMaximized()
  1323. else:
  1324. self.ui.show()
  1325. else:
  1326. self.ui.show()
  1327. if self.defaults["global_systray_icon"]:
  1328. self.trayIcon.show()
  1329. else:
  1330. log.warning("******************* RUNNING HEADLESS *******************")
  1331. # ###########################################################################################################
  1332. # ######################################## START-UP ARGUMENTS ###############################################
  1333. # ###########################################################################################################
  1334. # test if the program was started with a script as parameter
  1335. if self.cmd_line_shellvar:
  1336. try:
  1337. cnt = 0
  1338. command_tcl = 0
  1339. for i in self.cmd_line_shellvar.split(','):
  1340. if i is not None:
  1341. # noinspection PyBroadException
  1342. try:
  1343. command_tcl = eval(i)
  1344. except Exception:
  1345. command_tcl = i
  1346. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1347. cnt += 1
  1348. # if there are Windows paths then replace the path separator with a Unix like one
  1349. if sys.platform == 'win32':
  1350. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1351. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1352. except Exception as ext:
  1353. print("ERROR: ", ext)
  1354. sys.exit(2)
  1355. if self.cmd_line_shellfile:
  1356. if self.cmd_line_headless != 1:
  1357. if self.ui.shell_dock.isHidden():
  1358. self.ui.shell_dock.show()
  1359. try:
  1360. with open(self.cmd_line_shellfile, "r") as myfile:
  1361. # if show_splash:
  1362. # self.splash.showMessage('%s: %ssec\n%s' % (
  1363. # _("Canvas initialization started.\n"
  1364. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1365. # _("Executing Tcl Script ...")),
  1366. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1367. # color=QtGui.QColor("gray"))
  1368. cmd_line_shellfile_text = myfile.read()
  1369. if self.cmd_line_headless != 1:
  1370. self.shell.exec_command(cmd_line_shellfile_text)
  1371. else:
  1372. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1373. except Exception as ext:
  1374. print("ERROR: ", ext)
  1375. sys.exit(2)
  1376. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1377. # the path/file_name must be enclosed in quotes if it contain spaces
  1378. if App.args:
  1379. self.args_at_startup.emit(App.args)
  1380. if self.defaults.old_defaults_found is True:
  1381. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1382. "Please reboot the application to update."))
  1383. self.defaults.old_defaults_found = False
  1384. # ######################################### INIT FINISHED #######################################################
  1385. # #################################################################################################################
  1386. # #################################################################################################################
  1387. # #################################################################################################################
  1388. # #################################################################################################################
  1389. # #################################################################################################################
  1390. @staticmethod
  1391. def copy_and_overwrite(from_path, to_path):
  1392. """
  1393. From here:
  1394. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1395. :param from_path: source path
  1396. :param to_path: destination path
  1397. :return: None
  1398. """
  1399. if os.path.exists(to_path):
  1400. shutil.rmtree(to_path)
  1401. try:
  1402. shutil.copytree(from_path, to_path)
  1403. except FileNotFoundError:
  1404. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1405. shutil.copytree(from_new_path, to_path)
  1406. def on_startup_args(self, args, silent=False):
  1407. """
  1408. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1409. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1410. :param args: a list containing the application args at startup
  1411. :return: None
  1412. """
  1413. if args is not None:
  1414. args_to_process = args
  1415. else:
  1416. args_to_process = App.args
  1417. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1418. for argument in args_to_process:
  1419. if '.FlatPrj'.lower() in argument.lower():
  1420. try:
  1421. project_name = str(argument)
  1422. if project_name == "":
  1423. if silent is False:
  1424. self.inform.emit(_("Cancelled."))
  1425. else:
  1426. # self.open_project(project_name)
  1427. run_from_arg = True
  1428. # self.worker_task.emit({'fcn': self.open_project,
  1429. # 'params': [project_name, run_from_arg]})
  1430. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1431. except Exception as e:
  1432. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1433. elif '.FlatConfig'.lower() in argument.lower():
  1434. try:
  1435. file_name = str(argument)
  1436. if file_name == "":
  1437. if silent is False:
  1438. self.inform.emit(_("Open Config file failed."))
  1439. else:
  1440. run_from_arg = True
  1441. # self.worker_task.emit({'fcn': self.open_config_file,
  1442. # 'params': [file_name, run_from_arg]})
  1443. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1444. except Exception as e:
  1445. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1446. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1447. try:
  1448. file_name = str(argument)
  1449. if file_name == "":
  1450. if silent is False:
  1451. self.inform.emit(_("Open Script file failed."))
  1452. else:
  1453. if silent is False:
  1454. self.on_fileopenscript(name=file_name)
  1455. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1456. self.on_filerunscript(name=file_name)
  1457. except Exception as e:
  1458. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1459. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1460. log.debug("App.on_startup_args() --> Quit event.")
  1461. sys.exit()
  1462. elif 'save'.lower() in argument.lower():
  1463. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1464. self.preferencesUiManager.save_defaults()
  1465. else:
  1466. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1467. proc_arg = argument.lower()
  1468. for ext in exc_list:
  1469. proc_ext = ext.replace(' ', '')
  1470. proc_ext = '.%s' % proc_ext
  1471. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1472. file_name = str(argument)
  1473. if file_name == "":
  1474. if silent is False:
  1475. self.inform.emit(_("Open Excellon file failed."))
  1476. else:
  1477. self.on_fileopenexcellon(name=file_name, signal=None)
  1478. return
  1479. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1480. for ext in gco_list:
  1481. proc_ext = ext.replace(' ', '')
  1482. proc_ext = '.%s' % proc_ext
  1483. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1484. file_name = str(argument)
  1485. if file_name == "":
  1486. if silent is False:
  1487. self.inform.emit(_("Open GCode file failed."))
  1488. else:
  1489. self.on_fileopengcode(name=file_name, signal=None)
  1490. return
  1491. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1492. for ext in grb_list:
  1493. proc_ext = ext.replace(' ', '')
  1494. proc_ext = '.%s' % proc_ext
  1495. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1496. file_name = str(argument)
  1497. if file_name == "":
  1498. if silent is False:
  1499. self.inform.emit(_("Open Gerber file failed."))
  1500. else:
  1501. self.on_fileopengerber(name=file_name, signal=None)
  1502. return
  1503. # if it reached here without already returning then the app was registered with a file that it does not
  1504. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1505. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1506. # for arg in args_to_process:
  1507. # if 'FlatCAM.exe' in arg:
  1508. # continue
  1509. # else:
  1510. # sys.exit(2)
  1511. def set_ui_title(self, name):
  1512. """
  1513. Sets the title of the main window.
  1514. :param name: String that store the project path and project name
  1515. :return: None
  1516. """
  1517. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1518. (self.version,
  1519. ('BETA' if self.beta else ''),
  1520. platform.architecture()[0],
  1521. self.engine,
  1522. name)
  1523. )
  1524. def on_app_restart(self):
  1525. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1526. # be left in the SySTray
  1527. try:
  1528. self.trayIcon.hide()
  1529. except Exception:
  1530. pass
  1531. fcTranslate.restart_program(app=self)
  1532. def clear_pool(self):
  1533. """
  1534. Clear the multiprocessing pool and calls garbage collector.
  1535. :return: None
  1536. """
  1537. self.pool.close()
  1538. self.pool = Pool()
  1539. self.pool_recreated.emit(self.pool)
  1540. gc.collect()
  1541. def install_tools(self):
  1542. """
  1543. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1544. Instantiation of the Tools classes.
  1545. The order that the tools are installed is important as they can depend on each other install position.
  1546. :return: None
  1547. """
  1548. self.distance_tool = Distance(self)
  1549. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1550. before=self.ui.menueditorigin,
  1551. separator=False)
  1552. self.distance_min_tool = DistanceMin(self)
  1553. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1554. pos=self.ui.menuedit,
  1555. before=self.ui.menueditorigin,
  1556. separator=True)
  1557. self.dblsidedtool = DblSidedTool(self)
  1558. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1559. self.cal_exc_tool = ToolCalibration(self)
  1560. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1561. before=self.dblsidedtool.menuAction,
  1562. separator=False)
  1563. self.align_objects_tool = AlignObjects(self)
  1564. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1565. self.edrills_tool = ToolExtractDrills(self)
  1566. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1567. self.panelize_tool = Panelize(self)
  1568. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1569. self.film_tool = Film(self)
  1570. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1571. self.paste_tool = SolderPaste(self)
  1572. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1573. self.calculator_tool = ToolCalculator(self)
  1574. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1575. self.sub_tool = ToolSub(self)
  1576. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1577. pos=self.ui.menutool, separator=True)
  1578. self.rules_tool = RulesCheck(self)
  1579. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1580. pos=self.ui.menutool, separator=False)
  1581. self.optimal_tool = ToolOptimal(self)
  1582. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1583. pos=self.ui.menutool, separator=True)
  1584. self.move_tool = ToolMove(self)
  1585. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1586. before=self.ui.menueditorigin, separator=True)
  1587. self.cutout_tool = CutOut(self)
  1588. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1589. before=self.sub_tool.menuAction)
  1590. self.ncclear_tool = NonCopperClear(self)
  1591. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1592. before=self.sub_tool.menuAction, separator=True)
  1593. self.paint_tool = ToolPaint(self)
  1594. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1595. before=self.sub_tool.menuAction, separator=True)
  1596. self.copper_thieving_tool = ToolCopperThieving(self)
  1597. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1598. pos=self.ui.menutool)
  1599. self.fiducial_tool = ToolFiducials(self)
  1600. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1601. pos=self.ui.menutool)
  1602. self.qrcode_tool = QRCode(self)
  1603. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1604. pos=self.ui.menutool)
  1605. self.punch_tool = ToolPunchGerber(self)
  1606. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1607. self.invert_tool = ToolInvertGerber(self)
  1608. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1609. self.transform_tool = ToolTransform(self)
  1610. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1611. pos=self.ui.menuoptions, separator=True)
  1612. self.properties_tool = Properties(self)
  1613. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1614. pos=self.ui.menuoptions)
  1615. self.pdf_tool = ToolPDF(self)
  1616. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1617. pos=self.ui.menufileimport,
  1618. separator=True)
  1619. self.image_tool = ToolImage(self)
  1620. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1621. pos=self.ui.menufileimport,
  1622. separator=True)
  1623. self.pcb_wizard_tool = PcbWizard(self)
  1624. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1625. pos=self.ui.menufileimport)
  1626. self.log.debug("Tools are installed.")
  1627. def remove_tools(self):
  1628. """
  1629. Will remove all the actions in the Tool menu.
  1630. :return: None
  1631. """
  1632. for act in self.ui.menutool.actions():
  1633. self.ui.menutool.removeAction(act)
  1634. def init_tools(self):
  1635. """
  1636. Initialize the Tool tab in the notebook side of the central widget.
  1637. Remove the actions in the Tools menu.
  1638. Instantiate again the FlatCAM tools (plugins).
  1639. All this is required when changing the layout: standard, compact etc.
  1640. :return: None
  1641. """
  1642. log.debug("init_tools()")
  1643. # delete the data currently in the Tools Tab and the Tab itself
  1644. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1645. if widget is not None:
  1646. widget.deleteLater()
  1647. self.ui.notebook.removeTab(2)
  1648. # rebuild the Tools Tab
  1649. self.ui.tool_tab = QtWidgets.QWidget()
  1650. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1651. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1652. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1653. self.ui.tool_scroll_area = VerticalScrollArea()
  1654. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1655. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1656. # first remove all of them
  1657. self.remove_tools()
  1658. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1659. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1660. '&Command Line\tS')
  1661. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1662. # third install all of them
  1663. try:
  1664. self.install_tools()
  1665. except AttributeError:
  1666. pass
  1667. self.log.debug("Tools are initialized.")
  1668. # def parse_system_fonts(self):
  1669. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1670. # 'params': []})
  1671. def connect_toolbar_signals(self):
  1672. """
  1673. Reconnect the signals to the actions in the toolbar.
  1674. This has to be done each time after the FlatCAM tools are removed/installed.
  1675. :return: None
  1676. """
  1677. # Toolbar
  1678. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1679. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1680. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1681. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1682. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1683. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1684. self.ui.replot_btn.triggered.connect(self.plot_all)
  1685. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1686. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1687. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1688. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1689. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1690. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1691. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1692. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1693. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1694. self.ui.delete_btn.triggered.connect(self.on_delete)
  1695. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1696. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1697. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1698. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1699. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1700. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1701. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1702. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1703. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1704. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1705. # Tools Toolbar Signals
  1706. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1707. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1708. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1709. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1710. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1711. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1712. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1713. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1714. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1715. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1716. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1717. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1718. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1719. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1720. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1721. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1722. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1723. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1724. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1725. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1726. def object2editor(self):
  1727. """
  1728. Send the current Geometry or Excellon object (if any) into the it's editor.
  1729. :return: None
  1730. """
  1731. self.defaults.report_usage("object2editor()")
  1732. # disable the objects menu as it may interfere with the Editors
  1733. self.ui.menuobjects.setDisabled(True)
  1734. edited_object = self.collection.get_active()
  1735. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1736. isinstance(edited_object, ExcellonObject):
  1737. pass
  1738. else:
  1739. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1740. return
  1741. if isinstance(edited_object, GeometryObject):
  1742. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1743. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1744. # we set the notebook to hidden
  1745. # self.ui.splitter.setSizes([0, 1])
  1746. if edited_object.multigeo is True:
  1747. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1748. if len(sel_rows) > 1:
  1749. self.inform.emit('[WARNING_NOTCL] %s' %
  1750. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1751. "is not possible.\n"
  1752. "Edit only one geometry at a time."))
  1753. # determine the tool dia of the selected tool
  1754. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1755. # now find the key in the edited_object.tools that has this tooldia
  1756. multi_tool = 1
  1757. for tool in edited_object.tools:
  1758. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1759. multi_tool = tool
  1760. break
  1761. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1762. else:
  1763. self.geo_editor.edit_fcgeometry(edited_object)
  1764. # set call source to the Editor we go into
  1765. self.call_source = 'geo_editor'
  1766. elif isinstance(edited_object, ExcellonObject):
  1767. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1768. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1769. if self.ui.splitter.sizes()[0] == 0:
  1770. self.ui.splitter.setSizes([1, 1])
  1771. self.exc_editor.edit_fcexcellon(edited_object)
  1772. # set call source to the Editor we go into
  1773. self.call_source = 'exc_editor'
  1774. elif isinstance(edited_object, GerberObject):
  1775. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1776. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1777. if self.ui.splitter.sizes()[0] == 0:
  1778. self.ui.splitter.setSizes([1, 1])
  1779. self.grb_editor.edit_fcgerber(edited_object)
  1780. # set call source to the Editor we go into
  1781. self.call_source = 'grb_editor'
  1782. # reset the following variables so the UI is built again after edit
  1783. edited_object.ui_build = False
  1784. edited_object.build_aperture_storage = False
  1785. # make sure that we can't select another object while in Editor Mode:
  1786. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1787. self.ui.project_frame.setDisabled(True)
  1788. # delete any selection shape that might be active as they are not relevant in Editor
  1789. self.delete_selection_shape()
  1790. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1791. self.ui.plot_tab_area.protectTab(0)
  1792. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1793. self.should_we_save = True
  1794. def editor2object(self, cleanup=None):
  1795. """
  1796. Transfers the Geometry or Excellon from it's editor to the current object.
  1797. :return: None
  1798. """
  1799. self.defaults.report_usage("editor2object()")
  1800. # re-enable the objects menu that was disabled on entry in Editor mode
  1801. self.ui.menuobjects.setDisabled(False)
  1802. # do not update a geometry or excellon object unless it comes out of an editor
  1803. if self.call_source != 'app':
  1804. edited_obj = self.collection.get_active()
  1805. if cleanup is None:
  1806. msgbox = QtWidgets.QMessageBox()
  1807. msgbox.setText(_("Do you want to save the edited object?"))
  1808. msgbox.setWindowTitle(_("Close Editor"))
  1809. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1810. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1811. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1812. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1813. msgbox.setDefaultButton(bt_yes)
  1814. msgbox.exec_()
  1815. response = msgbox.clickedButton()
  1816. if response == bt_yes:
  1817. # clean the Tools Tab
  1818. self.ui.tool_scroll_area.takeWidget()
  1819. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1820. self.ui.notebook.setTabText(2, "Tool")
  1821. if isinstance(edited_obj, GeometryObject):
  1822. obj_type = "Geometry"
  1823. if cleanup is None:
  1824. self.geo_editor.update_fcgeometry(edited_obj)
  1825. # self.geo_editor.update_options(edited_obj)
  1826. self.geo_editor.deactivate()
  1827. # restore GUI to the Selected TAB
  1828. # Remove anything else in the GUI
  1829. self.ui.tool_scroll_area.takeWidget()
  1830. # update the geo object options so it is including the bounding box values
  1831. try:
  1832. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1833. edited_obj.options['xmin'] = xmin
  1834. edited_obj.options['ymin'] = ymin
  1835. edited_obj.options['xmax'] = xmax
  1836. edited_obj.options['ymax'] = ymax
  1837. except AttributeError as e:
  1838. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1839. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1840. edited_obj.build_ui()
  1841. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1842. elif isinstance(edited_obj, GerberObject):
  1843. obj_type = "Gerber"
  1844. if cleanup is None:
  1845. self.grb_editor.update_fcgerber()
  1846. self.grb_editor.update_options(edited_obj)
  1847. self.grb_editor.deactivate_grb_editor()
  1848. # delete the old object (the source object) if it was an empty one
  1849. try:
  1850. if len(edited_obj.solid_geometry) == 0:
  1851. old_name = edited_obj.options['name']
  1852. self.collection.set_active(old_name)
  1853. self.collection.delete_active()
  1854. except TypeError:
  1855. # if the solid_geometry is a single Polygon the len() will not work
  1856. # in any case, falling here means that we have something in the solid_geometry, even if only
  1857. # a single Polygon, therefore we pass this
  1858. pass
  1859. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1860. # restore GUI to the Selected TAB
  1861. # Remove anything else in the GUI
  1862. self.ui.selected_scroll_area.takeWidget()
  1863. elif isinstance(edited_obj, ExcellonObject):
  1864. obj_type = "Excellon"
  1865. if cleanup is None:
  1866. self.exc_editor.update_fcexcellon(edited_obj)
  1867. # self.exc_editor.update_options(edited_obj)
  1868. self.exc_editor.deactivate()
  1869. # restore GUI to the Selected TAB
  1870. # Remove anything else in the GUI
  1871. self.ui.tool_scroll_area.takeWidget()
  1872. # delete the old object (the source object) if it was an empty one
  1873. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1874. old_name = edited_obj.options['name']
  1875. self.collection.delete_by_name(name=old_name)
  1876. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1877. else:
  1878. self.inform.emit('[WARNING_NOTCL] %s' %
  1879. _("Select a Gerber, Geometry or Excellon Object to update."))
  1880. return
  1881. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1882. elif response == bt_no:
  1883. # clean the Tools Tab
  1884. self.ui.tool_scroll_area.takeWidget()
  1885. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1886. self.ui.notebook.setTabText(2, "Tool")
  1887. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1888. if isinstance(edited_obj, GeometryObject):
  1889. self.geo_editor.deactivate()
  1890. edited_obj.build_ui()
  1891. elif isinstance(edited_obj, GerberObject):
  1892. self.grb_editor.deactivate_grb_editor()
  1893. edited_obj.build_ui()
  1894. elif isinstance(edited_obj, ExcellonObject):
  1895. self.exc_editor.deactivate()
  1896. edited_obj.build_ui()
  1897. else:
  1898. self.inform.emit('[WARNING_NOTCL] %s' %
  1899. _("Select a Gerber, Geometry or Excellon Object to update."))
  1900. return
  1901. elif response == bt_cancel:
  1902. return
  1903. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1904. # edited_obj.build_ui()
  1905. # Switch notebook to Selected page
  1906. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1907. else:
  1908. if isinstance(edited_obj, GeometryObject):
  1909. self.geo_editor.deactivate()
  1910. elif isinstance(edited_obj, GerberObject):
  1911. self.grb_editor.deactivate_grb_editor()
  1912. elif isinstance(edited_obj, ExcellonObject):
  1913. self.exc_editor.deactivate()
  1914. else:
  1915. self.inform.emit('[WARNING_NOTCL] %s' %
  1916. _("Select a Gerber, Geometry or Excellon Object to update."))
  1917. return
  1918. # if notebook is hidden we show it
  1919. if self.ui.splitter.sizes()[0] == 0:
  1920. self.ui.splitter.setSizes([1, 1])
  1921. # restore the call_source to app
  1922. self.call_source = 'app'
  1923. edited_obj.plot()
  1924. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1925. self.ui.plot_tab_area.protectTab(0)
  1926. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1927. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1928. self.ui.project_frame.setDisabled(False)
  1929. def get_last_folder(self):
  1930. """
  1931. Get the folder path from where the last file was opened.
  1932. :return: String, last opened folder path
  1933. """
  1934. return self.defaults["global_last_folder"]
  1935. def get_last_save_folder(self):
  1936. """
  1937. Get the folder path from where the last file was saved.
  1938. :return: String, last saved folder path
  1939. """
  1940. loc = self.defaults["global_last_save_folder"]
  1941. if loc is None:
  1942. loc = self.defaults["global_last_folder"]
  1943. if loc is None:
  1944. loc = os.path.dirname(__file__)
  1945. return loc
  1946. def info(self, msg):
  1947. """
  1948. Informs the user. Normally on the status bar, optionally
  1949. also on the shell.
  1950. :param msg: Text to write.
  1951. :return: None
  1952. """
  1953. # Type of message in brackets at the beginning of the message.
  1954. match = re.search(r"\[(.*)\](.*)", msg)
  1955. if match:
  1956. level = match.group(1)
  1957. msg_ = match.group(2)
  1958. self.ui.fcinfo.set_status(str(msg_), level=level)
  1959. if level.lower() == "error":
  1960. self.shell_message(msg, error=True, show=True)
  1961. elif level.lower() == "warning":
  1962. self.shell_message(msg, warning=True, show=True)
  1963. elif level.lower() == "error_notcl":
  1964. self.shell_message(msg, error=True, show=False)
  1965. elif level.lower() == "warning_notcl":
  1966. self.shell_message(msg, warning=True, show=False)
  1967. elif level.lower() == "success":
  1968. self.shell_message(msg, success=True, show=False)
  1969. elif level.lower() == "selected":
  1970. self.shell_message(msg, selected=True, show=False)
  1971. else:
  1972. self.shell_message(msg, show=False)
  1973. else:
  1974. self.ui.fcinfo.set_status(str(msg), level="info")
  1975. # make sure that if the message is to clear the infobar with a space
  1976. # is not printed over and over on the shell
  1977. if msg != '':
  1978. self.shell_message(msg)
  1979. def restore_toolbar_view(self):
  1980. """
  1981. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1982. was saved in the defaults dictionary.
  1983. :return: None
  1984. """
  1985. tb = self.defaults["global_toolbar_view"]
  1986. if tb & 1:
  1987. self.ui.toolbarfile.setVisible(True)
  1988. else:
  1989. self.ui.toolbarfile.setVisible(False)
  1990. if tb & 2:
  1991. self.ui.toolbargeo.setVisible(True)
  1992. else:
  1993. self.ui.toolbargeo.setVisible(False)
  1994. if tb & 4:
  1995. self.ui.toolbarview.setVisible(True)
  1996. else:
  1997. self.ui.toolbarview.setVisible(False)
  1998. if tb & 8:
  1999. self.ui.toolbartools.setVisible(True)
  2000. else:
  2001. self.ui.toolbartools.setVisible(False)
  2002. if tb & 16:
  2003. self.ui.exc_edit_toolbar.setVisible(True)
  2004. else:
  2005. self.ui.exc_edit_toolbar.setVisible(False)
  2006. if tb & 32:
  2007. self.ui.geo_edit_toolbar.setVisible(True)
  2008. else:
  2009. self.ui.geo_edit_toolbar.setVisible(False)
  2010. if tb & 64:
  2011. self.ui.grb_edit_toolbar.setVisible(True)
  2012. else:
  2013. self.ui.grb_edit_toolbar.setVisible(False)
  2014. if tb & 128:
  2015. self.ui.snap_toolbar.setVisible(True)
  2016. else:
  2017. self.ui.snap_toolbar.setVisible(False)
  2018. if tb & 256:
  2019. self.ui.toolbarshell.setVisible(True)
  2020. else:
  2021. self.ui.toolbarshell.setVisible(False)
  2022. def on_import_preferences(self):
  2023. """
  2024. Loads the application default settings from a saved file into
  2025. ``self.defaults`` dictionary.
  2026. :return: None
  2027. """
  2028. self.defaults.report_usage("on_import_preferences")
  2029. App.log.debug("App.on_import_preferences()")
  2030. # Show file chooser
  2031. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2032. try:
  2033. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2034. directory=self.data_path,
  2035. filter=filter_)
  2036. except TypeError:
  2037. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2038. filter=filter_)
  2039. filename = str(filename)
  2040. if filename == "":
  2041. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2042. return
  2043. # Load in the defaults from the chosen file
  2044. self.defaults.load(filename=filename)
  2045. self.preferencesUiManager.on_preferences_edited()
  2046. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2047. def on_export_preferences(self):
  2048. """
  2049. Save the defaults dictionary to a file.
  2050. :return: None
  2051. """
  2052. self.defaults.report_usage("on_export_preferences")
  2053. App.log.debug("on_export_preferences()")
  2054. # defaults_file_content = None
  2055. # Show file chooser
  2056. date = str(datetime.today()).rpartition('.')[0]
  2057. date = ''.join(c for c in date if c not in ':-')
  2058. date = date.replace(' ', '_')
  2059. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2060. try:
  2061. filename, _f = FCFileSaveDialog.get_saved_filename(
  2062. caption=_("Export FlatCAM Preferences"),
  2063. directory=self.data_path + '/preferences_' + date,
  2064. filter=filter__
  2065. )
  2066. except TypeError:
  2067. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2068. filename = str(filename)
  2069. if filename == "":
  2070. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2071. return
  2072. # Update options
  2073. self.preferencesUiManager.defaults_read_form()
  2074. self.defaults.propagate_defaults()
  2075. # Save update options
  2076. try:
  2077. self.defaults.write(filename=filename)
  2078. except Exception:
  2079. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2080. return
  2081. if self.defaults["global_open_style"] is False:
  2082. self.file_opened.emit("preferences", filename)
  2083. self.file_saved.emit("preferences", filename)
  2084. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2085. def save_to_file(self, content_to_save, txt_content):
  2086. """
  2087. Save something to a file.
  2088. :return: None
  2089. """
  2090. self.defaults.report_usage("save_to_file")
  2091. App.log.debug("save_to_file()")
  2092. self.date = str(datetime.today()).rpartition('.')[0]
  2093. self.date = ''.join(c for c in self.date if c not in ':-')
  2094. self.date = self.date.replace(' ', '_')
  2095. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2096. path_to_save = self.defaults["global_last_save_folder"] if \
  2097. self.defaults["global_last_save_folder"] is not None else self.data_path
  2098. try:
  2099. filename, _f = FCFileSaveDialog.get_saved_filename(
  2100. caption=_("Save to file"),
  2101. directory=path_to_save + '/file_' + self.date,
  2102. filter=filter__
  2103. )
  2104. except TypeError:
  2105. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2106. filename = str(filename)
  2107. if filename == "":
  2108. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2109. return
  2110. else:
  2111. try:
  2112. with open(filename, 'w') as f:
  2113. ___ = f.read()
  2114. except PermissionError:
  2115. self.inform.emit('[WARNING] %s' %
  2116. _("Permission denied, saving not possible.\n"
  2117. "Most likely another app is holding the file open and not accessible."))
  2118. return
  2119. except IOError:
  2120. App.log.debug('Creating a new file ...')
  2121. f = open(filename, 'w')
  2122. f.close()
  2123. except Exception:
  2124. e = sys.exc_info()[0]
  2125. App.log.error("Could not load the file.")
  2126. App.log.error(str(e))
  2127. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2128. return
  2129. # Save content
  2130. if filename.rpartition('.')[2].lower() == 'html':
  2131. file_content = content_to_save
  2132. else:
  2133. file_content = txt_content
  2134. try:
  2135. with open(filename, "w") as f:
  2136. f.write(file_content)
  2137. except Exception:
  2138. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2139. return
  2140. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2141. def save_geometry(self, x, y, width, height, notebook_width):
  2142. """
  2143. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2144. launch of the application.
  2145. :param x: X position of the main window
  2146. :param y: Y position of the main window
  2147. :param width: width of the main window
  2148. :param height: height of the main window
  2149. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2150. :return: None
  2151. """
  2152. self.defaults["global_def_win_x"] = x
  2153. self.defaults["global_def_win_y"] = y
  2154. self.defaults["global_def_win_w"] = width
  2155. self.defaults["global_def_win_h"] = height
  2156. self.defaults["global_def_notebook_width"] = notebook_width
  2157. self.preferencesUiManager.save_defaults()
  2158. def restore_main_win_geom(self):
  2159. try:
  2160. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2161. self.defaults["global_def_win_y"],
  2162. self.defaults["global_def_win_w"],
  2163. self.defaults["global_def_win_h"])
  2164. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2165. except KeyError as e:
  2166. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2167. def message_dialog(self, title, message, kind="info"):
  2168. """
  2169. Builds and show a custom QMessageBox to be used in FlatCAM.
  2170. :param title: title of the QMessageBox
  2171. :param message: message to be displayed
  2172. :param kind: type of QMessageBox; will display a specific icon.
  2173. :return:
  2174. """
  2175. icon = {"info": QtWidgets.QMessageBox.Information,
  2176. "warning": QtWidgets.QMessageBox.Warning,
  2177. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2178. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2179. dlg.setText(message)
  2180. dlg.exec_()
  2181. def register_recent(self, kind, filename):
  2182. """
  2183. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2184. dictionary.
  2185. :param kind: type of file that was opened
  2186. :param filename: the path and file name for the file that was opened
  2187. :return:
  2188. """
  2189. self.log.debug("register_recent()")
  2190. self.log.debug(" %s" % kind)
  2191. self.log.debug(" %s" % filename)
  2192. record = {'kind': str(kind), 'filename': str(filename)}
  2193. if record in self.recent:
  2194. return
  2195. if record in self.recent_projects:
  2196. return
  2197. if record['kind'] == 'project':
  2198. self.recent_projects.insert(0, record)
  2199. else:
  2200. self.recent.insert(0, record)
  2201. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2202. self.recent.pop()
  2203. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2204. self.recent_projects.pop()
  2205. try:
  2206. f = open(self.data_path + '/recent.json', 'w')
  2207. except IOError:
  2208. App.log.error("Failed to open recent items file for writing.")
  2209. self.inform.emit('[ERROR_NOTCL] %s' %
  2210. _('Failed to open recent files file for writing.'))
  2211. return
  2212. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2213. f.close()
  2214. try:
  2215. fp = open(self.data_path + '/recent_projects.json', 'w')
  2216. except IOError:
  2217. App.log.error("Failed to open recent items file for writing.")
  2218. self.inform.emit('[ERROR_NOTCL] %s' %
  2219. _('Failed to open recent projects file for writing.'))
  2220. return
  2221. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2222. fp.close()
  2223. # Re-build the recent items menu
  2224. self.setup_recent_items()
  2225. def new_object(self, kind, name, initialize, plot=True, autoselected=True):
  2226. """
  2227. Creates a new specialized FlatCAMObj and attaches it to the application,
  2228. this is, updates the GUI accordingly, any other records and plots it.
  2229. This method is thread-safe.
  2230. Notes:
  2231. * If the name is in use, the self.collection will modify it
  2232. when appending it to the collection. There is no need to handle
  2233. name conflicts here.
  2234. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2235. :type kind: str
  2236. :param name: Name for the object.
  2237. :type name: str
  2238. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2239. The function is called with 2 parameters: the new object and the App instance.
  2240. :type initialize: function
  2241. :param plot: If to plot the resulting object
  2242. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2243. self.collection
  2244. :return: None
  2245. :rtype: None
  2246. """
  2247. App.log.debug("new_object()")
  2248. obj_plot = plot
  2249. obj_autoselected = autoselected
  2250. t0 = time.time() # Debug
  2251. # ## Create object
  2252. classdict = {
  2253. "gerber": GerberObject,
  2254. "excellon": ExcellonObject,
  2255. "cncjob": CNCJobObject,
  2256. "geometry": GeometryObject,
  2257. "script": ScriptObject,
  2258. "document": DocumentObject
  2259. }
  2260. App.log.debug("Calling object constructor...")
  2261. # Object creation/instantiation
  2262. obj = classdict[kind](name)
  2263. obj.units = self.options["units"]
  2264. # IMPORTANT
  2265. # The key names in defaults and options dictionary's are not random:
  2266. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2267. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2268. # copied to self.options. After that, below, depending on the type of
  2269. # object that is created, it will strip the name of the object and the underline (if the original key was
  2270. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2271. # "toolchange"
  2272. for option in self.options:
  2273. if option.find(kind + "_") == 0:
  2274. oname = option[len(kind) + 1:]
  2275. obj.options[oname] = self.options[option]
  2276. obj.isHovering = False
  2277. obj.notHovering = True
  2278. # Initialize as per user request
  2279. # User must take care to implement initialize
  2280. # in a thread-safe way as is is likely that we
  2281. # have been invoked in a separate thread.
  2282. t1 = time.time()
  2283. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2284. try:
  2285. return_value = initialize(obj, self)
  2286. except Exception as e:
  2287. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2288. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2289. msg += traceback.format_exc()
  2290. self.inform.emit(msg)
  2291. return "fail"
  2292. t2 = time.time()
  2293. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2294. if return_value == 'fail':
  2295. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2296. return "fail"
  2297. # Check units and convert if necessary
  2298. # This condition CAN be true because initialize() can change obj.units
  2299. if self.options["units"].upper() != obj.units.upper():
  2300. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2301. obj.convert_units(self.options["units"])
  2302. t3 = time.time()
  2303. self.log.debug("%f seconds converting units." % (t3 - t2))
  2304. # Create the bounding box for the object and then add the results to the obj.options
  2305. # But not for Scripts or for Documents
  2306. if kind != 'document' and kind != 'script':
  2307. try:
  2308. xmin, ymin, xmax, ymax = obj.bounds()
  2309. obj.options['xmin'] = xmin
  2310. obj.options['ymin'] = ymin
  2311. obj.options['xmax'] = xmax
  2312. obj.options['ymax'] = ymax
  2313. except Exception as e:
  2314. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2315. return "fail"
  2316. try:
  2317. if kind == 'excellon':
  2318. obj.fill_color = self.defaults["excellon_plot_fill"]
  2319. obj.outline_color = self.defaults["excellon_plot_line"]
  2320. if kind == 'gerber':
  2321. obj.fill_color = self.defaults["gerber_plot_fill"]
  2322. obj.outline_color = self.defaults["gerber_plot_line"]
  2323. except Exception as e:
  2324. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2325. # update the KeyWords list with the name of the file
  2326. self.myKeywords.append(obj.options['name'])
  2327. log.debug("Moving new object back to main thread.")
  2328. # Move the object to the main thread and let the app know that it is available.
  2329. obj.moveToThread(self.main_thread)
  2330. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2331. return obj
  2332. def new_excellon_object(self):
  2333. """
  2334. Creates a new, blank Excellon object.
  2335. :return: None
  2336. """
  2337. self.defaults.report_usage("new_excellon_object()")
  2338. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2339. def new_geometry_object(self):
  2340. """
  2341. Creates a new, blank and single-tool Geometry object.
  2342. :return: None
  2343. """
  2344. self.defaults.report_usage("new_geometry_object()")
  2345. def initialize(obj, app):
  2346. obj.multitool = False
  2347. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2348. def new_gerber_object(self):
  2349. """
  2350. Creates a new, blank Gerber object.
  2351. :return: None
  2352. """
  2353. self.defaults.report_usage("new_gerber_object()")
  2354. def initialize(grb_obj, app):
  2355. grb_obj.multitool = False
  2356. grb_obj.source_file = []
  2357. grb_obj.multigeo = False
  2358. grb_obj.follow = False
  2359. grb_obj.apertures = {}
  2360. grb_obj.solid_geometry = []
  2361. try:
  2362. grb_obj.options['xmin'] = 0
  2363. grb_obj.options['ymin'] = 0
  2364. grb_obj.options['xmax'] = 0
  2365. grb_obj.options['ymax'] = 0
  2366. except KeyError:
  2367. pass
  2368. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2369. def new_script_object(self):
  2370. """
  2371. Creates a new, blank TCL Script object.
  2372. :return: None
  2373. """
  2374. self.defaults.report_usage("new_script_object()")
  2375. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2376. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2377. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2378. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2379. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2380. # "ListSys, MillDrills,\n" \
  2381. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2382. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2383. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2384. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2385. # "# SubtractRectangle, Version, WriteGCode\n"
  2386. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2387. '# %s:\n' % _('TCL Tutorial is here') + \
  2388. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2389. '# %s:\n' % _("FlatCAM commands list")
  2390. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2391. "(displayed in Tcl Shell).")
  2392. def initialize(obj, app):
  2393. obj.source_file = deepcopy(new_source_file)
  2394. outname = 'new_script'
  2395. self.new_object('script', outname, initialize, plot=False)
  2396. def new_document_object(self):
  2397. """
  2398. Creates a new, blank Document object.
  2399. :return: None
  2400. """
  2401. self.defaults.report_usage("new_document_object()")
  2402. def initialize(obj, app):
  2403. obj.source_file = ""
  2404. self.new_object('document', 'new_document', initialize, plot=False)
  2405. def on_object_created(self, obj, plot, auto_select):
  2406. """
  2407. Event callback for object creation.
  2408. It will add the new object to the collection. After that it will plot the object in a threaded way
  2409. :param obj: The newly created FlatCAM object.
  2410. :param plot: if the newly create object t obe plotted
  2411. :param auto_select: if the newly created object to be autoselected after creation
  2412. :return: None
  2413. """
  2414. t0 = time.time() # DEBUG
  2415. self.log.debug("on_object_created()")
  2416. # The Collection might change the name if there is a collision
  2417. self.collection.append(obj)
  2418. # after adding the object to the collection always update the list of objects that are in the collection
  2419. self.all_objects_list = self.collection.get_list()
  2420. # self.inform.emit('[selected] %s created & selected: %s' %
  2421. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2422. if obj.kind == 'gerber':
  2423. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2424. kind=obj.kind.capitalize(),
  2425. color='green',
  2426. name=str(obj.options['name']), tx=_("created/selected"))
  2427. )
  2428. elif obj.kind == 'excellon':
  2429. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2430. kind=obj.kind.capitalize(),
  2431. color='brown',
  2432. name=str(obj.options['name']), tx=_("created/selected"))
  2433. )
  2434. elif obj.kind == 'cncjob':
  2435. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2436. kind=obj.kind.capitalize(),
  2437. color='blue',
  2438. name=str(obj.options['name']), tx=_("created/selected"))
  2439. )
  2440. elif obj.kind == 'geometry':
  2441. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2442. kind=obj.kind.capitalize(),
  2443. color='red',
  2444. name=str(obj.options['name']), tx=_("created/selected"))
  2445. )
  2446. elif obj.kind == 'script':
  2447. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2448. kind=obj.kind.capitalize(),
  2449. color='orange',
  2450. name=str(obj.options['name']), tx=_("created/selected"))
  2451. )
  2452. elif obj.kind == 'document':
  2453. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2454. kind=obj.kind.capitalize(),
  2455. color='darkCyan',
  2456. name=str(obj.options['name']), tx=_("created/selected"))
  2457. )
  2458. # update the SHELL auto-completer model with the name of the new object
  2459. self.shell._edit.set_model_data(self.myKeywords)
  2460. if auto_select:
  2461. # select the just opened object but deselect the previous ones
  2462. self.collection.set_all_inactive()
  2463. self.collection.set_active(obj.options["name"])
  2464. else:
  2465. self.collection.set_all_inactive()
  2466. # here it is done the object plotting
  2467. def worker_task(t_obj):
  2468. with self.proc_container.new(_("Plotting")):
  2469. if isinstance(t_obj, CNCJobObject):
  2470. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2471. else:
  2472. t_obj.plot()
  2473. t1 = time.time() # DEBUG
  2474. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2475. self.object_plotted.emit(t_obj)
  2476. # Send to worker
  2477. # self.worker.add_task(worker_task, [self])
  2478. if plot is True:
  2479. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2480. def on_object_changed(self, obj):
  2481. """
  2482. Called whenever the geometry of the object was changed in some way.
  2483. This require the update of it's bounding values so it can be the selected on canvas.
  2484. Update the bounding box data from obj.options
  2485. :param obj: the object that was changed
  2486. :return: None
  2487. """
  2488. xmin, ymin, xmax, ymax = obj.bounds()
  2489. obj.options['xmin'] = xmin
  2490. obj.options['ymin'] = ymin
  2491. obj.options['xmax'] = xmax
  2492. obj.options['ymax'] = ymax
  2493. log.debug("Object changed, updating the bounding box data on self.options")
  2494. # delete the old selection shape
  2495. self.delete_selection_shape()
  2496. self.should_we_save = True
  2497. def on_object_plotted(self):
  2498. """
  2499. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2500. :return: None
  2501. """
  2502. self.on_zoom_fit(None)
  2503. def on_about(self):
  2504. """
  2505. Displays the "about" dialog found in the Menu --> Help.
  2506. :return: None
  2507. """
  2508. self.defaults.report_usage("on_about")
  2509. version = self.version
  2510. version_date = self.version_date
  2511. beta = self.beta
  2512. class AboutDialog(QtWidgets.QDialog):
  2513. def __init__(self, app, parent=None):
  2514. QtWidgets.QDialog.__init__(self, parent)
  2515. self.app = app
  2516. # Icon and title
  2517. self.setWindowIcon(parent.app_icon)
  2518. self.setWindowTitle(_("About FlatCAM"))
  2519. self.resize(600, 200)
  2520. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2521. # self.setStyleSheet(
  2522. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2523. # "background-attachment: fixed"
  2524. # )
  2525. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2526. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2527. # palette = QtGui.QPalette()
  2528. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2529. # self.setPalette(palette)
  2530. logo = QtWidgets.QLabel()
  2531. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2532. title = QtWidgets.QLabel(
  2533. "<font size=8><B>FlatCAM</B></font><BR>"
  2534. "{title}<BR>"
  2535. "<BR>"
  2536. "<BR>"
  2537. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2538. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2539. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2540. "<B>{issue}</B></a><BR>".format(
  2541. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2542. devel=_("Development"),
  2543. down=_("DOWNLOAD"),
  2544. issue=_("Issue tracker"))
  2545. )
  2546. title.setOpenExternalLinks(True)
  2547. closebtn = QtWidgets.QPushButton(_("Close"))
  2548. tab_widget = QtWidgets.QTabWidget()
  2549. description_label = QtWidgets.QLabel(
  2550. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2551. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2552. version=version,
  2553. beta=('BETA' if beta else ''),
  2554. date=version_date,
  2555. arch=platform.architecture()[0])
  2556. )
  2557. description_label.setOpenExternalLinks(True)
  2558. lic_lbl_header = QtWidgets.QLabel(
  2559. '%s:<br>%s<br>' % (
  2560. _('Licensed under the MIT license'),
  2561. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2562. "http://www.opensource.org/licenses/mit-license.php</a>"
  2563. )
  2564. )
  2565. lic_lbl_header.setOpenExternalLinks(True)
  2566. lic_lbl_body = QtWidgets.QLabel(
  2567. _(
  2568. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2569. 'of this software and associated documentation files (the "Software"), to deal\n'
  2570. 'in the Software without restriction, including without limitation the rights\n'
  2571. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2572. 'copies of the Software, and to permit persons to whom the Software is\n'
  2573. 'furnished to do so, subject to the following conditions:\n\n'
  2574. 'The above copyright notice and this permission notice shall be included in\n'
  2575. 'all copies or substantial portions of the Software.\n\n'
  2576. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2577. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2578. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2579. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2580. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2581. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2582. 'THE SOFTWARE.'
  2583. )
  2584. )
  2585. attributions_label = QtWidgets.QLabel(
  2586. _(
  2587. 'Some of the icons used are from the following sources:<br>'
  2588. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2589. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2590. 'title="Flaticon">www.flaticon.com</a></div>'
  2591. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2592. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2593. )
  2594. )
  2595. attributions_label.setOpenExternalLinks(True)
  2596. # layouts
  2597. layout1 = QtWidgets.QVBoxLayout()
  2598. layout1_1 = QtWidgets.QHBoxLayout()
  2599. layout1_2 = QtWidgets.QHBoxLayout()
  2600. layout2 = QtWidgets.QHBoxLayout()
  2601. layout3 = QtWidgets.QHBoxLayout()
  2602. self.setLayout(layout1)
  2603. layout1.addLayout(layout1_1)
  2604. layout1.addLayout(layout1_2)
  2605. layout1.addLayout(layout2)
  2606. layout1.addLayout(layout3)
  2607. layout1_1.addStretch()
  2608. layout1_1.addWidget(description_label)
  2609. layout1_2.addWidget(tab_widget)
  2610. self.splash_tab = QtWidgets.QWidget()
  2611. self.splash_tab.setObjectName("splash_about")
  2612. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2613. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2614. tab_widget.addTab(self.splash_tab, _("Splash"))
  2615. self.programmmers_tab = QtWidgets.QWidget()
  2616. self.programmmers_tab.setObjectName("programmers_about")
  2617. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2618. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2619. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2620. self.translators_tab = QtWidgets.QWidget()
  2621. self.translators_tab.setObjectName("translators_about")
  2622. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2623. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2624. tab_widget.addTab(self.translators_tab, _("Translators"))
  2625. self.license_tab = QtWidgets.QWidget()
  2626. self.license_tab.setObjectName("license_about")
  2627. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2628. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2629. tab_widget.addTab(self.license_tab, _("License"))
  2630. self.attributions_tab = QtWidgets.QWidget()
  2631. self.attributions_tab.setObjectName("attributions_about")
  2632. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2633. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2634. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2635. self.splash_tab_layout.addWidget(logo, stretch=0)
  2636. self.splash_tab_layout.addWidget(title, stretch=1)
  2637. pal = QtGui.QPalette()
  2638. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2639. self.prog_grid_lay = QtWidgets.QGridLayout()
  2640. self.prog_grid_lay.setHorizontalSpacing(20)
  2641. self.prog_grid_lay.setColumnStretch(0, 0)
  2642. self.prog_grid_lay.setColumnStretch(2, 1)
  2643. prog_widget = QtWidgets.QWidget()
  2644. prog_widget.setLayout(self.prog_grid_lay)
  2645. prog_scroll = QtWidgets.QScrollArea()
  2646. prog_scroll.setWidget(prog_widget)
  2647. prog_scroll.setWidgetResizable(True)
  2648. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2649. prog_scroll.setPalette(pal)
  2650. self.programmmers_tab_layout.addWidget(prog_scroll)
  2651. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2652. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2653. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2654. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2655. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2656. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2657. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2658. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2659. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2660. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2661. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2662. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2663. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2664. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2665. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2666. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2698. self.translator_grid_lay = QtWidgets.QGridLayout()
  2699. self.translator_grid_lay.setColumnStretch(0, 0)
  2700. self.translator_grid_lay.setColumnStretch(1, 0)
  2701. self.translator_grid_lay.setColumnStretch(2, 1)
  2702. self.translator_grid_lay.setColumnStretch(3, 0)
  2703. # trans_widget = QtWidgets.QWidget()
  2704. # trans_widget.setLayout(self.translator_grid_lay)
  2705. # self.translators_tab_layout.addWidget(trans_widget)
  2706. # self.translators_tab_layout.addStretch()
  2707. trans_widget = QtWidgets.QWidget()
  2708. trans_widget.setLayout(self.translator_grid_lay)
  2709. trans_scroll = QtWidgets.QScrollArea()
  2710. trans_scroll.setWidget(trans_widget)
  2711. trans_scroll.setWidgetResizable(True)
  2712. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2713. trans_scroll.setPalette(pal)
  2714. self.translators_tab_layout.addWidget(trans_scroll)
  2715. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2716. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2717. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2718. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2719. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2720. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2721. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2722. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2723. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2724. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2725. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2726. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2727. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2728. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2729. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2748. self.translator_grid_lay.setColumnStretch(0, 0)
  2749. self.translators_tab_layout.addStretch()
  2750. self.license_tab_layout.addWidget(lic_lbl_header)
  2751. self.license_tab_layout.addWidget(lic_lbl_body)
  2752. self.license_tab_layout.addStretch()
  2753. self.attributions_tab_layout.addWidget(attributions_label)
  2754. self.attributions_tab_layout.addStretch()
  2755. layout3.addStretch()
  2756. layout3.addWidget(closebtn)
  2757. closebtn.clicked.connect(self.accept)
  2758. AboutDialog(app=self, parent=self.ui).exec_()
  2759. def install_bookmarks(self, book_dict=None):
  2760. """
  2761. Install the bookmarks actions in the Help menu -> Bookmarks
  2762. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2763. :return: None
  2764. """
  2765. if book_dict is None:
  2766. self.defaults["global_bookmarks"].update(
  2767. {
  2768. '1': ['FlatCAM', "http://flatcam.org"],
  2769. '2': ['Backup Site', ""]
  2770. }
  2771. )
  2772. else:
  2773. self.defaults["global_bookmarks"].clear()
  2774. self.defaults["global_bookmarks"].update(book_dict)
  2775. # first try to disconnect if somehow they get connected from elsewhere
  2776. for act in self.ui.menuhelp_bookmarks.actions():
  2777. try:
  2778. act.triggered.disconnect()
  2779. except TypeError:
  2780. pass
  2781. # clear all actions except the last one who is the Bookmark manager
  2782. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2783. pass
  2784. else:
  2785. self.ui.menuhelp_bookmarks.removeAction(act)
  2786. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2787. if self.defaults["global_bookmarks"]:
  2788. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2789. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2790. # the JSON is first making the keys as strings (therefore I have to use strings too
  2791. # or do the conversion :(
  2792. # )
  2793. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2794. # the '10' entry jsut after '1' therefore ordering as strings
  2795. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2796. key=lambda x: int(x[0]))
  2797. for entry, bookmark in sorted_bookmarks:
  2798. title = bookmark[0]
  2799. weblink = bookmark[1]
  2800. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2801. act.setText(title)
  2802. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2803. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2804. if title == 'Backup Site' and weblink == "":
  2805. act.triggered.connect(self.on_backup_site)
  2806. else:
  2807. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2808. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2809. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2810. def on_bookmarks_manager(self):
  2811. """
  2812. Adds the bookmark manager in a Tab in Plot Area
  2813. :return:
  2814. """
  2815. for idx in range(self.ui.plot_tab_area.count()):
  2816. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2817. # there can be only one instance of Bookmark Manager at one time
  2818. return
  2819. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2820. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2821. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2822. # add the tab if it was closed
  2823. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2824. # delete the absolute and relative position and messages in the infobar
  2825. self.ui.position_label.setText("")
  2826. self.ui.rel_position_label.setText("")
  2827. # Switch plot_area to preferences page
  2828. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2829. def on_backup_site(self):
  2830. msgbox = QtWidgets.QMessageBox()
  2831. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2832. "1. FlatCAM.org website is down\n"
  2833. "2. Someone forked FlatCAM project and wants to point\n"
  2834. "to his own website\n\n"
  2835. "If you can't get any informations about FlatCAM beta\n"
  2836. "use the YouTube channel link from the Help menu."))
  2837. msgbox.setWindowTitle(_("Alternative website"))
  2838. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2839. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2840. msgbox.setDefaultButton(bt_yes)
  2841. msgbox.exec_()
  2842. # response = msgbox.clickedButton()
  2843. def on_file_savedefaults(self):
  2844. """
  2845. Callback for menu item File->Save Defaults. Saves application default options
  2846. ``self.defaults`` to current_defaults.FlatConfig.
  2847. :return: None
  2848. """
  2849. self.preferencesUiManager.save_defaults()
  2850. def final_save(self):
  2851. """
  2852. Callback for doing a preferences save to file whenever the application is about to quit.
  2853. If the project has changes, it will ask the user to save the project.
  2854. :return: None
  2855. """
  2856. if self.save_in_progress:
  2857. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2858. return
  2859. if self.should_we_save and self.collection.get_list():
  2860. msgbox = QtWidgets.QMessageBox()
  2861. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2862. "\n"
  2863. "Do you want to Save the project?"))
  2864. msgbox.setWindowTitle(_("Save changes"))
  2865. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2866. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2867. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2868. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2869. msgbox.setDefaultButton(bt_yes)
  2870. msgbox.exec_()
  2871. response = msgbox.clickedButton()
  2872. if response == bt_yes:
  2873. try:
  2874. self.trayIcon.hide()
  2875. except Exception:
  2876. pass
  2877. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2878. elif response == bt_no:
  2879. try:
  2880. self.trayIcon.hide()
  2881. except Exception:
  2882. pass
  2883. self.quit_application()
  2884. elif response == bt_cancel:
  2885. return
  2886. else:
  2887. try:
  2888. self.trayIcon.hide()
  2889. except Exception:
  2890. pass
  2891. self.quit_application()
  2892. def quit_application(self):
  2893. """
  2894. Called (as a pyslot or not) when the application is quit.
  2895. :return: None
  2896. """
  2897. self.preferencesUiManager.save_defaults(silent=True)
  2898. log.debug("App.quit_application() --> App Defaults saved.")
  2899. if self.cmd_line_headless != 1:
  2900. # save app state to file
  2901. stgs = QSettings("Open Source", "FlatCAM")
  2902. stgs.setValue('saved_gui_state', self.ui.saveState())
  2903. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2904. stgs.setValue(
  2905. 'language',
  2906. self.preferencesUiManager.get_form_field("global_language").get_value()
  2907. )
  2908. stgs.setValue(
  2909. 'notebook_font_size',
  2910. self.preferencesUiManager.get_form_field("notebook_font_size").get_value()
  2911. )
  2912. stgs.setValue(
  2913. 'axis_font_size',
  2914. self.preferencesUiManager.get_form_field("axis_font_size").get_value()
  2915. )
  2916. stgs.setValue(
  2917. 'textbox_font_size',
  2918. self.preferencesUiManager.get_form_field("textbox_font_size").get_value()
  2919. )
  2920. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2921. stgs.setValue(
  2922. 'machinist',
  2923. 1 if self.preferencesUiManager.get_form_field("global_machinist_setting").get_value() else 0
  2924. )
  2925. # This will write the setting to the platform specific storage.
  2926. del stgs
  2927. log.debug("App.quit_application() --> App UI state saved.")
  2928. # try to quit the Socket opened by ArgsThread class
  2929. try:
  2930. self.new_launch.stop.emit()
  2931. except Exception as err:
  2932. log.debug("App.quit_application() --> %s" % str(err))
  2933. # try to quit the QThread that run ArgsThread class
  2934. try:
  2935. self.th.quit()
  2936. except Exception as e:
  2937. log.debug("App.quit_application() --> %s" % str(e))
  2938. # terminate workers
  2939. self.workers.__del__()
  2940. # quit app by signalling for self.kill_app() method
  2941. # self.close_app_signal.emit()
  2942. QtWidgets.qApp.quit()
  2943. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2944. # we use the following command
  2945. minor_v = sys.version_info.minor
  2946. if minor_v < 8:
  2947. sys.exit(0)
  2948. else:
  2949. os._exit(0) # fix to work with Python 3.8
  2950. @staticmethod
  2951. def kill_app():
  2952. QtWidgets.qApp.quit()
  2953. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2954. # we use the following command
  2955. sys.exit(0)
  2956. def on_portable_checked(self, state):
  2957. """
  2958. Callback called when the checkbox in Preferences GUI is checked.
  2959. It will set the application as portable by creating the preferences and recent files in the
  2960. 'config' folder found in the FlatCAM installation folder.
  2961. :param state: boolean, the state of the checkbox when clicked/checked
  2962. :return:
  2963. """
  2964. line_no = 0
  2965. data = None
  2966. if sys.platform != 'win32':
  2967. # this won't work in Linux or MacOS
  2968. return
  2969. # test if the app was frozen and choose the path for the configuration file
  2970. if getattr(sys, "frozen", False) is True:
  2971. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2972. else:
  2973. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2974. config_file = current_data_path + '\\configuration.txt'
  2975. try:
  2976. with open(config_file, 'r') as f:
  2977. try:
  2978. data = f.readlines()
  2979. except Exception as e:
  2980. log.debug('App.__init__() -->%s' % str(e))
  2981. return
  2982. except FileNotFoundError:
  2983. pass
  2984. for line in data:
  2985. line = line.strip('\n')
  2986. param = str(line).rpartition('=')
  2987. if param[0] == 'portable':
  2988. break
  2989. line_no += 1
  2990. if state:
  2991. data[line_no] = 'portable=True\n'
  2992. # create the new defauults files
  2993. # create current_defaults.FlatConfig file if there is none
  2994. try:
  2995. f = open(current_data_path + '/current_defaults.FlatConfig')
  2996. f.close()
  2997. except IOError:
  2998. App.log.debug('Creating empty current_defaults.FlatConfig')
  2999. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3000. json.dump({}, f)
  3001. f.close()
  3002. # create factory_defaults.FlatConfig file if there is none
  3003. try:
  3004. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3005. f.close()
  3006. except IOError:
  3007. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3008. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3009. json.dump({}, f)
  3010. f.close()
  3011. try:
  3012. f = open(current_data_path + '/recent.json')
  3013. f.close()
  3014. except IOError:
  3015. App.log.debug('Creating empty recent.json')
  3016. f = open(current_data_path + '/recent.json', 'w')
  3017. json.dump([], f)
  3018. f.close()
  3019. try:
  3020. fp = open(current_data_path + '/recent_projects.json')
  3021. fp.close()
  3022. except IOError:
  3023. App.log.debug('Creating empty recent_projects.json')
  3024. fp = open(current_data_path + '/recent_projects.json', 'w')
  3025. json.dump([], fp)
  3026. fp.close()
  3027. # save the current defaults to the new defaults file
  3028. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3029. else:
  3030. data[line_no] = 'portable=False\n'
  3031. with open(config_file, 'w') as f:
  3032. f.writelines(data)
  3033. def on_register_files(self, obj_type=None):
  3034. """
  3035. Called whenever there is a need to register file extensions with FlatCAM.
  3036. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3037. :param obj_type: the type of object to be register for.
  3038. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3039. :return: None
  3040. """
  3041. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3042. new_reg_path = 'Software\\Classes\\'
  3043. # find if the current user is admin
  3044. try:
  3045. is_admin = os.getuid() == 0
  3046. except AttributeError:
  3047. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3048. if is_admin is True:
  3049. root_path = winreg.HKEY_LOCAL_MACHINE
  3050. else:
  3051. root_path = winreg.HKEY_CURRENT_USER
  3052. # create the keys
  3053. def set_reg(name, root_pth, new_reg_path, value):
  3054. try:
  3055. winreg.CreateKey(root_pth, new_reg_path)
  3056. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3057. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3058. return True
  3059. except WindowsError:
  3060. return False
  3061. # delete key in registry
  3062. def delete_reg(root_pth, reg_path, key_to_del):
  3063. key_to_del_path = reg_path + key_to_del
  3064. try:
  3065. winreg.DeleteKey(root_pth, key_to_del_path)
  3066. return True
  3067. except WindowsError:
  3068. return False
  3069. if obj_type is None or obj_type == 'excellon':
  3070. exc_list = \
  3071. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3072. exc_list = [x for x in exc_list if x != '']
  3073. # register all keys in the Preferences window
  3074. for ext in exc_list:
  3075. new_k = new_reg_path + '.%s' % ext
  3076. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3077. # and unregister those that are no longer in the Preferences windows but are in the file
  3078. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3079. if ext not in exc_list:
  3080. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3081. # now write the updated extensions to the self.defaults
  3082. # new_ext = ''
  3083. # for ext in exc_list:
  3084. # new_ext = new_ext + ext + ', '
  3085. # self.defaults["fa_excellon"] = new_ext
  3086. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3087. if obj_type is None or obj_type == 'gcode':
  3088. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3089. gco_list = [x for x in gco_list if x != '']
  3090. # register all keys in the Preferences window
  3091. for ext in gco_list:
  3092. new_k = new_reg_path + '.%s' % ext
  3093. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3094. # and unregister those that are no longer in the Preferences windows but are in the file
  3095. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3096. if ext not in gco_list:
  3097. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3098. # now write the updated extensions to the self.defaults
  3099. # new_ext = ''
  3100. # for ext in gco_list:
  3101. # new_ext = new_ext + ext + ', '
  3102. # self.defaults["fa_gcode"] = new_ext
  3103. self.inform.emit('[success] %s' %
  3104. _("Selected GCode file extensions registered with FlatCAM."))
  3105. if obj_type is None or obj_type == 'gerber':
  3106. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3107. grb_list = [x for x in grb_list if x != '']
  3108. # register all keys in the Preferences window
  3109. for ext in grb_list:
  3110. new_k = new_reg_path + '.%s' % ext
  3111. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3112. # and unregister those that are no longer in the Preferences windows but are in the file
  3113. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3114. if ext not in grb_list:
  3115. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3116. # now write the updated extensions to the self.defaults
  3117. # new_ext = ''
  3118. # for ext in grb_list:
  3119. # new_ext = new_ext + ext + ', '
  3120. # self.defaults["fa_gerber"] = new_ext
  3121. self.inform.emit('[success] %s' %
  3122. _("Selected Gerber file extensions registered with FlatCAM."))
  3123. def add_extension(self, ext_type):
  3124. """
  3125. Add a file extension to the list for a specific object
  3126. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3127. :return:
  3128. """
  3129. if ext_type == 'excellon':
  3130. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3131. if new_ext == '':
  3132. return
  3133. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3134. if new_ext in old_val:
  3135. return
  3136. old_val.append(new_ext)
  3137. old_val.sort()
  3138. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3139. if ext_type == 'gcode':
  3140. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3141. if new_ext == '':
  3142. return
  3143. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3144. if new_ext in old_val:
  3145. return
  3146. old_val.append(new_ext)
  3147. old_val.sort()
  3148. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3149. if ext_type == 'gerber':
  3150. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3151. if new_ext == '':
  3152. return
  3153. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3154. if new_ext in old_val:
  3155. return
  3156. old_val.append(new_ext)
  3157. old_val.sort()
  3158. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3159. if ext_type == 'keyword':
  3160. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3161. if new_kw == '':
  3162. return
  3163. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3164. if new_kw in old_val:
  3165. return
  3166. old_val.append(new_kw)
  3167. old_val.sort()
  3168. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3169. # update the self.myKeywords so the model is updated
  3170. self.autocomplete_kw_list = \
  3171. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3172. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3173. self.shell._edit.set_model_data(self.myKeywords)
  3174. def del_extension(self, ext_type):
  3175. """
  3176. Remove a file extension from the list for a specific object
  3177. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3178. :return:
  3179. """
  3180. if ext_type == 'excellon':
  3181. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3182. if new_ext == '':
  3183. return
  3184. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3185. if new_ext not in old_val:
  3186. return
  3187. old_val.remove(new_ext)
  3188. old_val.sort()
  3189. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3190. if ext_type == 'gcode':
  3191. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3192. if new_ext == '':
  3193. return
  3194. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3195. if new_ext not in old_val:
  3196. return
  3197. old_val.remove(new_ext)
  3198. old_val.sort()
  3199. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3200. if ext_type == 'gerber':
  3201. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3202. if new_ext == '':
  3203. return
  3204. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3205. if new_ext not in old_val:
  3206. return
  3207. old_val.remove(new_ext)
  3208. old_val.sort()
  3209. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3210. if ext_type == 'keyword':
  3211. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3212. if new_kw == '':
  3213. return
  3214. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3215. if new_kw not in old_val:
  3216. return
  3217. old_val.remove(new_kw)
  3218. old_val.sort()
  3219. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3220. # update the self.myKeywords so the model is updated
  3221. self.autocomplete_kw_list = \
  3222. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3223. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3224. self.shell._edit.set_model_data(self.myKeywords)
  3225. def restore_extensions(self, ext_type):
  3226. """
  3227. Restore all file extensions associations with FlatCAM, for a specific object
  3228. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3229. :return:
  3230. """
  3231. if ext_type == 'excellon':
  3232. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3233. # for the ability to open Excellon files with .txt extension
  3234. new_exc_list = deepcopy(self.exc_list)
  3235. try:
  3236. new_exc_list.remove('txt')
  3237. except ValueError:
  3238. pass
  3239. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3240. if ext_type == 'gcode':
  3241. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3242. if ext_type == 'gerber':
  3243. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3244. if ext_type == 'keyword':
  3245. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3246. # update the self.myKeywords so the model is updated
  3247. self.autocomplete_kw_list = self.default_keywords
  3248. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3249. self.shell._edit.set_model_data(self.myKeywords)
  3250. def delete_all_extensions(self, ext_type):
  3251. """
  3252. Delete all file extensions associations with FlatCAM, for a specific object
  3253. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3254. :return:
  3255. """
  3256. if ext_type == 'excellon':
  3257. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3258. if ext_type == 'gcode':
  3259. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3260. if ext_type == 'gerber':
  3261. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3262. if ext_type == 'keyword':
  3263. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3264. # update the self.myKeywords so the model is updated
  3265. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3266. self.shell._edit.set_model_data(self.myKeywords)
  3267. def on_edit_join(self, name=None):
  3268. """
  3269. Callback for Edit->Join. Joins the selected geometry objects into
  3270. a new one.
  3271. :return: None
  3272. """
  3273. self.defaults.report_usage("on_edit_join()")
  3274. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3275. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3276. geo_type_set = set()
  3277. objs = self.collection.get_selected()
  3278. if len(objs) < 2:
  3279. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3280. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3281. return 'fail'
  3282. for obj in objs:
  3283. geo_type_set.add(obj.multigeo)
  3284. # if len(geo_type_list) == 1 means that all list elements are the same
  3285. if len(geo_type_set) != 1:
  3286. self.inform.emit('[ERROR] %s' %
  3287. _("Failed join. The Geometry objects are of different types.\n"
  3288. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3289. "convert from one to another and retry joining \n"
  3290. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3291. "the result may not be what was expected. \n"
  3292. "Check the generated GCODE."))
  3293. return
  3294. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3295. if True in geo_type_set:
  3296. def initialize(geo_obj, app):
  3297. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3298. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3299. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3300. for v in geo_obj.tools.values():
  3301. v['data']['name'] = obj_name_multi
  3302. self.new_object("geometry", obj_name_multi, initialize)
  3303. else:
  3304. def initialize(geo_obj, app):
  3305. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3306. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3307. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3308. for v in geo_obj.tools.values():
  3309. v['data']['name'] = obj_name_single
  3310. self.new_object("geometry", obj_name_single, initialize)
  3311. self.should_we_save = True
  3312. def on_edit_join_exc(self):
  3313. """
  3314. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3315. a new Excellon.
  3316. :return: None
  3317. """
  3318. self.defaults.report_usage("on_edit_join_exc()")
  3319. objs = self.collection.get_selected()
  3320. for obj in objs:
  3321. if not isinstance(obj, ExcellonObject):
  3322. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3323. return
  3324. if len(objs) < 2:
  3325. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3326. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3327. return 'fail'
  3328. def initialize(exc_obj, app):
  3329. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3330. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3331. self.new_object("excellon", 'Combo_Excellon', initialize)
  3332. self.should_we_save = True
  3333. def on_edit_join_grb(self):
  3334. """
  3335. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3336. a new Gerber object.
  3337. :return: None
  3338. """
  3339. self.defaults.report_usage("on_edit_join_grb()")
  3340. objs = self.collection.get_selected()
  3341. for obj in objs:
  3342. if not isinstance(obj, GerberObject):
  3343. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3344. return
  3345. if len(objs) < 2:
  3346. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3347. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3348. return 'fail'
  3349. def initialize(grb_obj, app):
  3350. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3351. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3352. self.new_object("gerber", 'Combo_Gerber', initialize)
  3353. self.should_we_save = True
  3354. def on_convert_singlegeo_to_multigeo(self):
  3355. """
  3356. Called for converting a Geometry object from single-geo to multi-geo.
  3357. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3358. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3359. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3360. the solid-geometry of that tool.
  3361. :return: None
  3362. """
  3363. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3364. obj = self.collection.get_active()
  3365. if obj is None:
  3366. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3367. return
  3368. if not isinstance(obj, GeometryObject):
  3369. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3370. return
  3371. obj.multigeo = True
  3372. for tooluid, dict_value in obj.tools.items():
  3373. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3374. if not isinstance(obj.solid_geometry, list):
  3375. obj.solid_geometry = [obj.solid_geometry]
  3376. # obj.solid_geometry[:] = []
  3377. obj.plot()
  3378. self.should_we_save = True
  3379. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3380. def on_convert_multigeo_to_singlegeo(self):
  3381. """
  3382. Called for converting a Geometry object from multi-geo to single-geo.
  3383. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3384. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3385. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3386. the solid-geometry of that tool.
  3387. :return: None
  3388. """
  3389. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3390. obj = self.collection.get_active()
  3391. if obj is None:
  3392. self.inform.emit('[ERROR_NOTCL] %s' %
  3393. _("Failed. Select a Geometry Object and try again."))
  3394. return
  3395. if not isinstance(obj, GeometryObject):
  3396. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3397. (_("Expected a GeometryObject, got"), type(obj)))
  3398. return
  3399. obj.multigeo = False
  3400. total_solid_geometry = []
  3401. for tooluid, dict_value in obj.tools.items():
  3402. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3403. # clear the original geometry
  3404. dict_value['solid_geometry'][:] = []
  3405. obj.solid_geometry = deepcopy(total_solid_geometry)
  3406. obj.plot()
  3407. self.should_we_save = True
  3408. self.inform.emit('[success] %s' %
  3409. _("A Geometry object was converted to SingleGeo type."))
  3410. def on_defaults_dict_change(self, field):
  3411. """
  3412. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3413. Edit -> Preferences tab window.
  3414. :param field: the key of the self.defaults dictionary that was changed.
  3415. :return: None
  3416. """
  3417. self.preferencesUiManager.defaults_write_form_field(field=field)
  3418. if field == "units":
  3419. self.set_screen_units(self.defaults['units'])
  3420. def set_screen_units(self, units):
  3421. """
  3422. Set the FlatCAM units on the status bar.
  3423. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3424. :return: None
  3425. """
  3426. self.ui.units_label.setText("[" + units.lower() + "]")
  3427. def on_toggle_units_click(self):
  3428. try:
  3429. self.preferencesUiManager.get_form_field("units").activated_custom.disconnect()
  3430. except (TypeError, AttributeError):
  3431. pass
  3432. if self.defaults["units"] == 'MM':
  3433. self.preferencesUiManager.get_form_field("units").set_value("IN")
  3434. else:
  3435. self.preferencesUiManager.get_form_field("units").set_value("MM")
  3436. self.on_toggle_units(no_pref=True)
  3437. self.preferencesUiManager.get_form_field("units").activated_custom.connect(
  3438. lambda: self.on_toggle_units(no_pref=False))
  3439. def on_toggle_units(self, no_pref=False):
  3440. """
  3441. Callback for the Units radio-button change in the Preferences tab.
  3442. Changes the application's default units adn for the project too.
  3443. If changing the project's units, the change propagates to all of
  3444. the objects in the project.
  3445. :return: None
  3446. """
  3447. self.defaults.report_usage("on_toggle_units")
  3448. if self.toggle_units_ignore:
  3449. return
  3450. new_units = self.preferencesUiManager.get_form_field("units").get_value().upper()
  3451. # If option is the same, then ignore
  3452. if new_units == self.defaults["units"].upper():
  3453. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3454. return
  3455. # Keys in self.defaults for which to scale their values
  3456. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3457. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3458. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3459. "gerber_editor_ma_high",
  3460. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3461. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3462. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3463. "excellon_feedrate_probe", "excellon_milling_dia",
  3464. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3465. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3466. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3467. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3468. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3469. "geometry_extracut_length", "geometry_z_pdepth",
  3470. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3471. 'cncjob_tooldia',
  3472. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3473. "tools_paintnewdia",
  3474. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3475. "tools_nccnewdia", "tools_ncc_offset_value",
  3476. "tools_2sided_drilldia",
  3477. "tools_film_boundary", "tools_film_scale_stroke",
  3478. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3479. "tools_cutout_depthperpass",
  3480. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3481. "tools_panelize_spacing_rows",
  3482. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3483. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3484. "tools_transform_buffer_dis",
  3485. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3486. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3487. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3488. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3489. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3490. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3491. "tools_cr_h2h_val", "tools_cr_dh_val",
  3492. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3493. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3494. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3495. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3496. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3497. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3498. "tools_copper_thieving_mask_clearance",
  3499. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3500. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3501. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3502. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3503. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3504. "tools_invert_margin",
  3505. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3506. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3507. def scale_defaults(sfactor):
  3508. for dim in dimensions:
  3509. if dim in [
  3510. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3511. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3512. 'tools_transform_mirror_point'
  3513. ]:
  3514. if self.defaults[dim] is None or self.defaults[dim] == '':
  3515. continue
  3516. try:
  3517. coordinates = self.defaults[dim].split(",")
  3518. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3519. coords_xy[0] *= sfactor
  3520. coords_xy[1] *= sfactor
  3521. self.defaults[dim] = "%.*f, %.*f" % (
  3522. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3523. except Exception as e:
  3524. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3525. elif dim in [
  3526. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3527. ]:
  3528. if self.defaults[dim] is None or self.defaults[dim] == '':
  3529. continue
  3530. try:
  3531. self.defaults[dim] = float(self.defaults[dim])
  3532. tools_diameters = [self.defaults[dim]]
  3533. except ValueError:
  3534. try:
  3535. tools_string = self.defaults[dim].split(",")
  3536. tools_diameters = [eval(a) for a in tools_string if a != '']
  3537. except Exception as e:
  3538. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3539. continue
  3540. self.defaults[dim] = ''
  3541. td_len = len(tools_diameters)
  3542. if td_len > 1:
  3543. for t in range(td_len):
  3544. tools_diameters[t] *= sfactor
  3545. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3546. else:
  3547. tools_diameters[0] *= sfactor
  3548. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3549. elif dim in ['global_gridx', 'global_gridy']:
  3550. # format the number of decimals to the one specified in self.decimals
  3551. try:
  3552. val = float(self.defaults[dim]) * sfactor
  3553. except Exception as e:
  3554. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3555. continue
  3556. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3557. else:
  3558. # the number of decimals for the rest is kept unchanged
  3559. if self.defaults[dim]:
  3560. try:
  3561. val = float(self.defaults[dim]) * sfactor
  3562. except Exception as e:
  3563. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3564. continue
  3565. self.defaults[dim] = val
  3566. # The scaling factor depending on choice of units.
  3567. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3568. # Changing project units. Warn user.
  3569. msgbox = QtWidgets.QMessageBox()
  3570. msgbox.setWindowTitle(_("Toggle Units"))
  3571. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3572. msgbox.setText(_("Changing the units of the project\n"
  3573. "will scale all objects.\n\n"
  3574. "Do you want to continue?"))
  3575. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3576. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3577. msgbox.setDefaultButton(bt_ok)
  3578. msgbox.exec_()
  3579. response = msgbox.clickedButton()
  3580. if response == bt_ok:
  3581. if no_pref is False:
  3582. self.preferencesUiManager.defaults_read_form()
  3583. scale_defaults(factor)
  3584. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3585. self.defaults["units"] = new_units
  3586. # update the defaults from form, some may assume that the conversion is enough and it's not
  3587. self.on_options_app2project()
  3588. # update the objects
  3589. for obj in self.collection.get_list():
  3590. obj.convert_units(new_units)
  3591. # make that the properties stored in the object are also updated
  3592. self.object_changed.emit(obj)
  3593. # rebuild the object UI
  3594. obj.build_ui()
  3595. # change this only if the workspace is active
  3596. if self.defaults['global_workspace'] is True:
  3597. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3598. # adjust the grid values on the main toolbar
  3599. val_x = float(self.defaults['global_gridx']) * factor
  3600. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3601. current = self.collection.get_active()
  3602. if current is not None:
  3603. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3604. if not isinstance(current, GeometryObject):
  3605. current.to_form()
  3606. # replot all objects
  3607. self.plot_all()
  3608. # set the status labels to reflect the current FlatCAM units
  3609. self.set_screen_units(new_units)
  3610. # signal to the app that we changed the object properties and it should save the project
  3611. self.should_we_save = True
  3612. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3613. else:
  3614. # Undo toggling
  3615. self.toggle_units_ignore = True
  3616. if self.defaults['units'].upper() == 'MM':
  3617. self.preferencesUiManager.get_form_field("units").set_value('IN')
  3618. else:
  3619. self.preferencesUiManager.get_form_field("units").set_value('MM')
  3620. self.toggle_units_ignore = False
  3621. # store the grid values so they are not changed in the next step
  3622. val_x = float(self.defaults['global_gridx'])
  3623. val_y = float(self.defaults['global_gridy'])
  3624. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3625. self.preferencesUiManager.defaults_read_form()
  3626. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3627. # in self.defaults from the GUI elements but
  3628. # I don't want it for the grid values, so I update them here
  3629. self.defaults['global_gridx'] = val_x
  3630. self.defaults['global_gridy'] = val_y
  3631. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3632. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3633. def on_fullscreen(self, disable=False):
  3634. self.defaults.report_usage("on_fullscreen()")
  3635. flags = self.ui.windowFlags()
  3636. if self.toggle_fscreen is False and disable is False:
  3637. # self.ui.showFullScreen()
  3638. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3639. a = self.ui.geometry()
  3640. self.x_pos = a.x()
  3641. self.y_pos = a.y()
  3642. self.width = a.width()
  3643. self.height = a.height()
  3644. # set new geometry to full desktop rect
  3645. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3646. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3647. # everything else will not work without this hack. This happen in Windows.
  3648. # https://bugreports.qt.io/browse/QTBUG-41309
  3649. desktop = QtWidgets.QApplication.desktop()
  3650. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3651. rec = desktop.screenGeometry(screen)
  3652. x = rec.x() - 1
  3653. y = rec.y() - 1
  3654. h = rec.height() + 2
  3655. w = rec.width() + 2
  3656. self.ui.setGeometry(x, y, w, h)
  3657. self.ui.show()
  3658. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3659. tb.setVisible(False)
  3660. self.ui.splitter_left.setVisible(False)
  3661. self.toggle_fscreen = True
  3662. elif self.toggle_fscreen is True or disable is True:
  3663. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3664. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3665. self.ui.showNormal()
  3666. self.restore_toolbar_view()
  3667. self.ui.splitter_left.setVisible(True)
  3668. self.toggle_fscreen = False
  3669. def on_toggle_plotarea(self):
  3670. self.defaults.report_usage("on_toggle_plotarea()")
  3671. try:
  3672. name = self.ui.plot_tab_area.widget(0).objectName()
  3673. except AttributeError:
  3674. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3675. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3676. self.ui.plot_tab_area.protectTab(0)
  3677. return
  3678. if name != 'plotarea_tab':
  3679. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3680. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3681. self.ui.plot_tab_area.protectTab(0)
  3682. else:
  3683. self.ui.plot_tab_area.closeTab(0)
  3684. def on_toggle_notebook(self):
  3685. if self.ui.splitter.sizes()[0] == 0:
  3686. self.ui.splitter.setSizes([1, 1])
  3687. self.ui.menu_toggle_nb.setChecked(True)
  3688. else:
  3689. self.ui.splitter.setSizes([0, 1])
  3690. self.ui.menu_toggle_nb.setChecked(False)
  3691. def on_toggle_axis(self):
  3692. self.defaults.report_usage("on_toggle_axis()")
  3693. if self.toggle_axis is False:
  3694. if self.is_legacy is False:
  3695. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3696. parent=self.plotcanvas.view.scene)
  3697. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3698. parent=self.plotcanvas.view.scene)
  3699. else:
  3700. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3701. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3702. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3703. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3704. self.plotcanvas.canvas.draw()
  3705. self.toggle_axis = True
  3706. else:
  3707. if self.is_legacy is False:
  3708. self.plotcanvas.v_line.parent = None
  3709. self.plotcanvas.h_line.parent = None
  3710. else:
  3711. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3712. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3713. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3714. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3715. self.plotcanvas.canvas.draw()
  3716. self.toggle_axis = False
  3717. def on_toggle_grid(self):
  3718. self.defaults.report_usage("on_toggle_grid()")
  3719. self.ui.grid_snap_btn.trigger()
  3720. self.ui.on_grid_snap_triggered(state=True)
  3721. def on_toggle_grid_lines(self):
  3722. self.defaults.report_usage("on_toggle_grd_lines()")
  3723. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3724. if tt_settings.contains("theme"):
  3725. theme = tt_settings.value('theme', type=str)
  3726. else:
  3727. theme = 'white'
  3728. if self.toggle_grid_lines is False:
  3729. if self.is_legacy is False:
  3730. if theme == 'white':
  3731. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3732. else:
  3733. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3734. else:
  3735. self.plotcanvas.axes.grid(True)
  3736. try:
  3737. self.plotcanvas.canvas.draw()
  3738. except IndexError:
  3739. pass
  3740. pass
  3741. self.toggle_grid_lines = True
  3742. else:
  3743. if self.is_legacy is False:
  3744. if theme == 'white':
  3745. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3746. else:
  3747. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3748. else:
  3749. self.plotcanvas.axes.grid(False)
  3750. try:
  3751. self.plotcanvas.canvas.draw()
  3752. except IndexError:
  3753. pass
  3754. self.toggle_grid_lines = False
  3755. if self.is_legacy is False:
  3756. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3757. # - perhaps is a bug in VisPy implementation
  3758. if self.grid_status() is True:
  3759. self.app_cursor.enabled = False
  3760. self.app_cursor.enabled = True
  3761. else:
  3762. self.app_cursor.enabled = True
  3763. self.app_cursor.enabled = False
  3764. def on_film_color_entry(self):
  3765. self.defaults['tools_film_color'] = \
  3766. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3767. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3768. "background-color:%s;"
  3769. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3770. )
  3771. def on_film_color_button(self):
  3772. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3773. c_dialog = QtWidgets.QColorDialog()
  3774. film_color = c_dialog.getColor(initial=current_color)
  3775. if film_color.isValid() is False:
  3776. return
  3777. # if new color is different then mark that the Preferences are changed
  3778. if film_color != current_color:
  3779. self.preferencesUiManager.on_preferences_edited()
  3780. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3781. "background-color:%s;"
  3782. "border-color: dimgray" % str(film_color.name())
  3783. )
  3784. new_val_sel = str(film_color.name())
  3785. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3786. self.defaults['tools_film_color'] = new_val_sel
  3787. def on_qrcode_fill_color_entry(self):
  3788. self.defaults['tools_qrcode_fill_color'] = \
  3789. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3790. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3791. "background-color:%s;"
  3792. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3793. )
  3794. def on_qrcode_fill_color_button(self):
  3795. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3796. c_dialog = QtWidgets.QColorDialog()
  3797. fill_color = c_dialog.getColor(initial=current_color)
  3798. if fill_color.isValid() is False:
  3799. return
  3800. # if new color is different then mark that the Preferences are changed
  3801. if fill_color != current_color:
  3802. self.preferencesUiManager.on_preferences_edited()
  3803. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3804. "background-color:%s;"
  3805. "border-color: dimgray" % str(fill_color.name())
  3806. )
  3807. new_val_sel = str(fill_color.name())
  3808. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3809. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3810. def on_qrcode_back_color_entry(self):
  3811. self.defaults['tools_qrcode_back_color'] = \
  3812. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3813. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3814. "background-color:%s;"
  3815. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3816. )
  3817. def on_qrcode_back_color_button(self):
  3818. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3819. c_dialog = QtWidgets.QColorDialog()
  3820. back_color = c_dialog.getColor(initial=current_color)
  3821. if back_color.isValid() is False:
  3822. return
  3823. # if new color is different then mark that the Preferences are changed
  3824. if back_color != current_color:
  3825. self.preferencesUiManager.on_preferences_edited()
  3826. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3827. "background-color:%s;"
  3828. "border-color: dimgray" % str(back_color.name())
  3829. )
  3830. new_val_sel = str(back_color.name())
  3831. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3832. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3833. def on_tab_rmb_click(self, checked):
  3834. self.ui.notebook.set_detachable(val=checked)
  3835. self.defaults["global_tabs_detachable"] = checked
  3836. self.ui.plot_tab_area.set_detachable(val=checked)
  3837. self.defaults["global_tabs_detachable"] = checked
  3838. def on_tab_setup_context_menu(self):
  3839. initial_checked = self.defaults["global_tabs_detachable"]
  3840. action_name = str(_("Detachable Tabs"))
  3841. action = QtWidgets.QAction(self)
  3842. action.setCheckable(True)
  3843. action.setText(action_name)
  3844. action.setChecked(initial_checked)
  3845. self.ui.notebook.tabBar.addAction(action)
  3846. self.ui.plot_tab_area.tabBar.addAction(action)
  3847. try:
  3848. action.triggered.disconnect()
  3849. except TypeError:
  3850. pass
  3851. action.triggered.connect(self.on_tab_rmb_click)
  3852. def on_deselect_all(self):
  3853. self.collection.set_all_inactive()
  3854. self.delete_selection_shape()
  3855. def on_workspace_modified(self):
  3856. # self.save_defaults(silent=True)
  3857. if self.is_legacy is True:
  3858. self.plotcanvas.delete_workspace()
  3859. self.preferencesUiManager.defaults_read_form()
  3860. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3861. def on_workspace(self):
  3862. if self.preferencesUiManager.get_form_field("global_workspace").get_value():
  3863. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3864. else:
  3865. self.plotcanvas.delete_workspace()
  3866. self.preferencesUiManager.defaults_read_form()
  3867. # self.save_defaults(silent=True)
  3868. def on_workspace_toggle(self):
  3869. state = False if self.preferencesUiManager.get_form_field("global_workspace").get_value() else True
  3870. try:
  3871. self.preferencesUiManager.get_form_field("global_workspace").stateChanged.disconnect(self.on_workspace)
  3872. except TypeError:
  3873. pass
  3874. self.preferencesUiManager.get_form_field("global_workspace").set_value(state)
  3875. self.preferencesUiManager.get_form_field("global_workspace").stateChanged.connect(self.on_workspace)
  3876. self.on_workspace()
  3877. def on_cursor_type(self, val):
  3878. """
  3879. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3880. :return: None
  3881. """
  3882. self.app_cursor.enabled = False
  3883. if val == 'small':
  3884. self.preferencesUiManager.get_form_field("global_cursor_size").setDisabled(False)
  3885. #self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3886. self.app_cursor = self.plotcanvas.new_cursor()
  3887. else:
  3888. self.preferencesUiManager.get_form_field("global_cursor_size").setDisabled(False)
  3889. #self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3890. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3891. if self.ui.grid_snap_btn.isChecked():
  3892. self.app_cursor.enabled = True
  3893. else:
  3894. self.app_cursor.enabled = False
  3895. def on_tool_add_keypress(self):
  3896. # ## Current application units in Upper Case
  3897. self.units = self.defaults['units'].upper()
  3898. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3899. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3900. if notebook_widget_name == 'selected_tab':
  3901. if self.collection.get_active().kind == 'geometry':
  3902. # Tool add works for Geometry only if Advanced is True in Preferences
  3903. if self.defaults["global_app_level"] == 'a':
  3904. tool_add_popup = FCInputDialog(title="New Tool ...",
  3905. text='Enter a Tool Diameter:',
  3906. min=0.0000, max=99.9999, decimals=4)
  3907. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3908. val, ok = tool_add_popup.get_value()
  3909. if ok:
  3910. if float(val) == 0:
  3911. self.inform.emit('[WARNING_NOTCL] %s' %
  3912. _("Please enter a tool diameter with non-zero value, in Float format."))
  3913. return
  3914. self.collection.get_active().on_tool_add(dia=float(val))
  3915. else:
  3916. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3917. else:
  3918. msgbox = QtWidgets.QMessageBox()
  3919. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3920. "Go to Preferences -> General - Show Advanced Options."))
  3921. msgbox.setWindowTitle("Tool adding ...")
  3922. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3923. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3924. msgbox.setDefaultButton(bt_ok)
  3925. msgbox.exec_()
  3926. # work only if the notebook tab on focus is the Tools_Tab
  3927. if notebook_widget_name == 'tool_tab':
  3928. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3929. # and only if the tool is NCC Tool
  3930. if tool_widget == self.ncclear_tool.toolName:
  3931. self.ncclear_tool.on_add_tool_by_key()
  3932. # and only if the tool is Paint Area Tool
  3933. elif tool_widget == self.paint_tool.toolName:
  3934. self.paint_tool.on_add_tool_by_key()
  3935. # and only if the tool is Solder Paste Dispensing Tool
  3936. elif tool_widget == self.paste_tool.toolName:
  3937. self.paste_tool.on_add_tool_by_key()
  3938. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3939. # See description below.
  3940. def on_delete_keypress(self):
  3941. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3942. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3943. if notebook_widget_name == 'selected_tab':
  3944. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3945. self.collection.get_active().on_tool_delete()
  3946. # work only if the notebook tab on focus is the Tools_Tab
  3947. elif notebook_widget_name == 'tool_tab':
  3948. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3949. # and only if the tool is NCC Tool
  3950. if tool_widget == self.ncclear_tool.toolName:
  3951. self.ncclear_tool.on_tool_delete()
  3952. # and only if the tool is Paint Tool
  3953. elif tool_widget == self.paint_tool.toolName:
  3954. self.paint_tool.on_tool_delete()
  3955. # and only if the tool is Solder Paste Dispensing Tool
  3956. elif tool_widget == self.paste_tool.toolName:
  3957. self.paste_tool.on_tool_delete()
  3958. else:
  3959. self.on_delete()
  3960. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3961. # some screens you have to be careful where you hover with your mouse.
  3962. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3963. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3964. # Complicated, I know :)
  3965. def on_delete(self, force_deletion=False):
  3966. """
  3967. Delete the currently selected FlatCAMObjs.
  3968. :param force_deletion: used by Tcl command
  3969. :return: None
  3970. """
  3971. self.defaults.report_usage("on_delete()")
  3972. response = None
  3973. bt_ok = None
  3974. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3975. # a geometry object before we update it.
  3976. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3977. and self.grb_editor.editor_active is False:
  3978. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3979. msgbox = QtWidgets.QMessageBox()
  3980. msgbox.setWindowTitle(_("Delete objects"))
  3981. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3982. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3983. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3984. "the selected objects?"))
  3985. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3986. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3987. msgbox.setDefaultButton(bt_ok)
  3988. msgbox.exec_()
  3989. response = msgbox.clickedButton()
  3990. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3991. response = bt_ok
  3992. if response == bt_ok:
  3993. if self.collection.get_active():
  3994. self.log.debug("App.on_delete()")
  3995. for obj_active in self.collection.get_selected():
  3996. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3997. if obj_active.kind == 'gerber':
  3998. for el in obj_active.mark_shapes:
  3999. obj_active.mark_shapes[el].clear(update=True)
  4000. obj_active.mark_shapes[el].enabled = False
  4001. # obj_active.mark_shapes[el] = None
  4002. del el
  4003. elif isinstance(obj_active, CNCJobObject):
  4004. try:
  4005. obj_active.text_col.enabled = False
  4006. del obj_active.text_col
  4007. obj_active.annotation.clear(update=True)
  4008. del obj_active.annotation
  4009. except AttributeError as e:
  4010. log.debug(
  4011. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4012. )
  4013. while self.collection.get_selected():
  4014. self.delete_first_selected()
  4015. self.inform.emit('%s...' % _("Object(s) deleted"))
  4016. # make sure that the selection shape is deleted, too
  4017. self.delete_selection_shape()
  4018. # if there are no longer objects delete also the exclusion areas shapes
  4019. if not self.collection.get_list():
  4020. self.exc_areas.clear_shapes()
  4021. else:
  4022. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4023. else:
  4024. self.inform.emit(_("Save the work in Editor and try again ..."))
  4025. def delete_first_selected(self):
  4026. # Keep this for later
  4027. try:
  4028. sel_obj = self.collection.get_active()
  4029. name = sel_obj.options["name"]
  4030. isPlotted = sel_obj.options["plot"]
  4031. except AttributeError:
  4032. self.log.debug("Nothing selected for deletion")
  4033. return
  4034. if self.is_legacy is True:
  4035. # Remove plot only if the object was plotted otherwise delaxes will fail
  4036. if isPlotted:
  4037. try:
  4038. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4039. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4040. except Exception as e:
  4041. log.debug("App.delete_first_selected() --> %s" % str(e))
  4042. self.plotcanvas.auto_adjust_axes()
  4043. # Remove from dictionary
  4044. self.collection.delete_active()
  4045. # Clear form
  4046. self.setup_component_editor()
  4047. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4048. def on_set_origin(self):
  4049. """
  4050. Set the origin to the left mouse click position
  4051. :return: None
  4052. """
  4053. # display the message for the user
  4054. # and ask him to click on the desired position
  4055. self.defaults.report_usage("on_set_origin()")
  4056. def origin_replot():
  4057. def worker_task():
  4058. with self.proc_container.new('%s...' % _("Plotting")):
  4059. for obj in self.collection.get_list():
  4060. obj.plot()
  4061. self.plotcanvas.fit_view()
  4062. if self.is_legacy:
  4063. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4064. else:
  4065. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4066. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4067. self.inform.emit(_('Click to set the origin ...'))
  4068. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4069. # first disconnect it as it may have been used by something else
  4070. try:
  4071. self.replot_signal.disconnect()
  4072. except TypeError:
  4073. pass
  4074. self.replot_signal[list].connect(origin_replot)
  4075. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4076. """
  4077. :param event:
  4078. :param location:
  4079. :param noplot:
  4080. :param use_thread:
  4081. :return:
  4082. """
  4083. noplot_sig = noplot
  4084. def worker_task():
  4085. with self.proc_container.new(_("Setting Origin...")):
  4086. obj_list = self.collection.get_list()
  4087. for obj in obj_list:
  4088. obj.offset((x, y))
  4089. self.object_changed.emit(obj)
  4090. # Update the object bounding box options
  4091. a, b, c, d = obj.bounds()
  4092. obj.options['xmin'] = a
  4093. obj.options['ymin'] = b
  4094. obj.options['xmax'] = c
  4095. obj.options['ymax'] = d
  4096. self.inform.emit('[success] %s...' % _('Origin set'))
  4097. for obj in obj_list:
  4098. out_name = obj.options["name"]
  4099. if obj.kind == 'gerber':
  4100. obj.source_file = self.export_gerber(
  4101. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4102. elif obj.kind == 'excellon':
  4103. obj.source_file = self.export_excellon(
  4104. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4105. if noplot_sig is False:
  4106. self.replot_signal.emit([])
  4107. if location is not None:
  4108. if len(location) != 2:
  4109. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4110. return 'fail'
  4111. x, y = location
  4112. if use_thread is True:
  4113. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4114. else:
  4115. worker_task()
  4116. self.should_we_save = True
  4117. return
  4118. if event.button == 1:
  4119. if self.is_legacy is False:
  4120. event_pos = event.pos
  4121. else:
  4122. event_pos = (event.xdata, event.ydata)
  4123. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4124. if self.grid_status():
  4125. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4126. else:
  4127. pos = pos_canvas
  4128. x = 0 - pos[0]
  4129. y = 0 - pos[1]
  4130. if use_thread is True:
  4131. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4132. else:
  4133. worker_task()
  4134. self.should_we_save = True
  4135. def on_move2origin(self, use_thread=True):
  4136. """
  4137. Move selected objects to origin.
  4138. :param use_thread: Control if to use threaded operation. Boolean.
  4139. :return:
  4140. """
  4141. def worker_task():
  4142. with self.proc_container.new(_("Moving to Origin...")):
  4143. obj_list = self.collection.get_selected()
  4144. if not obj_list:
  4145. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4146. return
  4147. xminlist = []
  4148. yminlist = []
  4149. # first get a bounding box to fit all
  4150. for obj in obj_list:
  4151. xmin, ymin, xmax, ymax = obj.bounds()
  4152. xminlist.append(xmin)
  4153. yminlist.append(ymin)
  4154. # get the minimum x,y for all objects selected
  4155. x = min(xminlist)
  4156. y = min(yminlist)
  4157. for obj in obj_list:
  4158. obj.offset((-x, -y))
  4159. self.object_changed.emit(obj)
  4160. # Update the object bounding box options
  4161. a, b, c, d = obj.bounds()
  4162. obj.options['xmin'] = a
  4163. obj.options['ymin'] = b
  4164. obj.options['xmax'] = c
  4165. obj.options['ymax'] = d
  4166. for obj in obj_list:
  4167. obj.plot()
  4168. for obj in obj_list:
  4169. out_name = obj.options["name"]
  4170. if obj.kind == 'gerber':
  4171. obj.source_file = self.export_gerber(
  4172. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4173. elif obj.kind == 'excellon':
  4174. obj.source_file = self.export_excellon(
  4175. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4176. self.inform.emit('[success] %s...' % _('Origin set'))
  4177. if use_thread is True:
  4178. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4179. else:
  4180. worker_task()
  4181. self.should_we_save = True
  4182. def on_jump_to(self, custom_location=None, fit_center=True):
  4183. """
  4184. Jump to a location by setting the mouse cursor location.
  4185. :param custom_location: Jump to a specified point. (x, y) tuple.
  4186. :param fit_center: If to fit view. Boolean.
  4187. :return:
  4188. """
  4189. self.defaults.report_usage("on_jump_to()")
  4190. if not custom_location:
  4191. dia_box_location = None
  4192. try:
  4193. dia_box_location = eval(self.clipboard.text())
  4194. except Exception:
  4195. pass
  4196. if type(dia_box_location) == tuple:
  4197. dia_box_location = str(dia_box_location)
  4198. else:
  4199. dia_box_location = None
  4200. # dia_box = Dialog_box(title=_("Jump to ..."),
  4201. # label=_("Enter the coordinates in format X,Y:"),
  4202. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4203. # initial_text=dia_box_location)
  4204. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4205. label=_("Enter the coordinates in format X,Y:"),
  4206. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4207. initial_text=dia_box_location,
  4208. reference=self.defaults['global_jump_ref'])
  4209. if dia_box.ok is True:
  4210. try:
  4211. location = eval(dia_box.location)
  4212. if not isinstance(location, tuple):
  4213. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4214. return
  4215. if dia_box.reference == 'rel':
  4216. rel_x = self.mouse[0] + location[0]
  4217. rel_y = self.mouse[1] + location[1]
  4218. location = (rel_x, rel_y)
  4219. self.defaults['global_jump_ref'] = dia_box.reference
  4220. except Exception:
  4221. return
  4222. else:
  4223. return
  4224. else:
  4225. location = custom_location
  4226. self.jump_signal.emit(location)
  4227. if fit_center:
  4228. self.plotcanvas.fit_center(loc=location)
  4229. cursor = QtGui.QCursor()
  4230. if self.is_legacy is False:
  4231. # I don't know where those differences come from but they are constant for the current
  4232. # execution of the application and they are multiples of a value around 0.0263mm.
  4233. # In a random way sometimes they are more sometimes they are less
  4234. # if units == 'MM':
  4235. # cal_factor = 0.0263
  4236. # else:
  4237. # cal_factor = 0.0263 / 25.4
  4238. cal_location = (location[0], location[1])
  4239. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4240. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4241. j_pos = (
  4242. int(canvas_origin.x() + round(jump_loc[0])),
  4243. int(canvas_origin.y() + round(jump_loc[1]))
  4244. )
  4245. cursor.setPos(j_pos[0], j_pos[1])
  4246. else:
  4247. # find the canvas origin which is in the top left corner
  4248. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4249. # determine the coordinates for the lowest left point of the canvas
  4250. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4251. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4252. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4253. # canvas) and the point (width, height) is in the top-right location
  4254. loc = self.plotcanvas.axes.transData.transform_point(location)
  4255. j_pos = (
  4256. int(x0 + loc[0]),
  4257. int(y0 - loc[1])
  4258. )
  4259. cursor.setPos(j_pos[0], j_pos[1])
  4260. self.plotcanvas.mouse = [location[0], location[1]]
  4261. if self.defaults["global_cursor_color_enabled"] is True:
  4262. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4263. else:
  4264. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4265. if self.grid_status():
  4266. # Update cursor
  4267. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4268. symbol='++', edge_color=self.cursor_color_3D,
  4269. edge_width=self.defaults["global_cursor_width"],
  4270. size=self.defaults["global_cursor_size"])
  4271. # Set the relative position label
  4272. dx = location[0] - float(self.rel_point1[0])
  4273. dy = location[1] - float(self.rel_point1[1])
  4274. # self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4275. # "<b>Y</b>: %.4f" % (location[0], location[1]))
  4276. # # Set the position label
  4277. #
  4278. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4279. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4280. units = self.defaults["units"].lower()
  4281. self.plotcanvas.text_hud.text = \
  4282. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4283. dx, units, dy, units, location[0], units, location[1], units)
  4284. self.inform.emit('[success] %s' % _("Done."))
  4285. return location
  4286. def on_locate(self, obj, fit_center=True):
  4287. """
  4288. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4289. :param obj: The object on which to locate certain points
  4290. :param fit_center: If to fit view. Boolean.
  4291. :return: A point location. (x, y) tuple.
  4292. """
  4293. self.defaults.report_usage("on_locate()")
  4294. if obj is None:
  4295. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4296. return 'fail'
  4297. class DialogBoxChoice(QtWidgets.QDialog):
  4298. def __init__(self, title=None, icon=None, choice='bl'):
  4299. """
  4300. :param title: string with the window title
  4301. """
  4302. super(DialogBoxChoice, self).__init__()
  4303. self.ok = False
  4304. self.setWindowIcon(icon)
  4305. self.setWindowTitle(str(title))
  4306. self.form = QtWidgets.QFormLayout(self)
  4307. self.ref_radio = RadioSet([
  4308. {"label": _("Bottom-Left"), "value": "bl"},
  4309. {"label": _("Top-Left"), "value": "tl"},
  4310. {"label": _("Bottom-Right"), "value": "br"},
  4311. {"label": _("Top-Right"), "value": "tr"},
  4312. {"label": _("Center"), "value": "c"}
  4313. ], orientation='vertical', stretch=False)
  4314. self.ref_radio.set_value(choice)
  4315. self.form.addRow(self.ref_radio)
  4316. self.button_box = QtWidgets.QDialogButtonBox(
  4317. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4318. Qt.Horizontal, parent=self)
  4319. self.form.addRow(self.button_box)
  4320. self.button_box.accepted.connect(self.accept)
  4321. self.button_box.rejected.connect(self.reject)
  4322. if self.exec_() == QtWidgets.QDialog.Accepted:
  4323. self.ok = True
  4324. self.location_point = self.ref_radio.get_value()
  4325. else:
  4326. self.ok = False
  4327. self.location_point = None
  4328. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4329. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4330. choice=self.defaults['global_locate_pt'])
  4331. if dia_box.ok is True:
  4332. try:
  4333. location_point = dia_box.location_point
  4334. self.defaults['global_locate_pt'] = dia_box.location_point
  4335. except Exception:
  4336. return
  4337. else:
  4338. return
  4339. loc_b = obj.bounds()
  4340. if location_point == 'bl':
  4341. location = (loc_b[0], loc_b[1])
  4342. elif location_point == 'tl':
  4343. location = (loc_b[0], loc_b[3])
  4344. elif location_point == 'br':
  4345. location = (loc_b[2], loc_b[1])
  4346. elif location_point == 'tr':
  4347. location = (loc_b[2], loc_b[3])
  4348. else:
  4349. # center
  4350. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4351. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4352. location = (cx, cy)
  4353. self.locate_signal.emit(location, location_point)
  4354. if fit_center:
  4355. self.plotcanvas.fit_center(loc=location)
  4356. cursor = QtGui.QCursor()
  4357. if self.is_legacy is False:
  4358. # I don't know where those differences come from but they are constant for the current
  4359. # execution of the application and they are multiples of a value around 0.0263mm.
  4360. # In a random way sometimes they are more sometimes they are less
  4361. # if units == 'MM':
  4362. # cal_factor = 0.0263
  4363. # else:
  4364. # cal_factor = 0.0263 / 25.4
  4365. cal_location = (location[0], location[1])
  4366. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4367. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4368. j_pos = (
  4369. int(canvas_origin.x() + round(jump_loc[0])),
  4370. int(canvas_origin.y() + round(jump_loc[1]))
  4371. )
  4372. cursor.setPos(j_pos[0], j_pos[1])
  4373. else:
  4374. # find the canvas origin which is in the top left corner
  4375. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4376. # determine the coordinates for the lowest left point of the canvas
  4377. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4378. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4379. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4380. # canvas) and the point (width, height) is in the top-right location
  4381. loc = self.plotcanvas.axes.transData.transform_point(location)
  4382. j_pos = (
  4383. int(x0 + loc[0]),
  4384. int(y0 - loc[1])
  4385. )
  4386. cursor.setPos(j_pos[0], j_pos[1])
  4387. self.plotcanvas.mouse = [location[0], location[1]]
  4388. if self.defaults["global_cursor_color_enabled"] is True:
  4389. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4390. else:
  4391. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4392. if self.grid_status():
  4393. # Update cursor
  4394. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4395. symbol='++', edge_color=self.cursor_color_3D,
  4396. edge_width=self.defaults["global_cursor_width"],
  4397. size=self.defaults["global_cursor_size"])
  4398. # Set the relative position label
  4399. self.dx = location[0] - float(self.rel_point1[0])
  4400. self.dy = location[1] - float(self.rel_point1[1])
  4401. # Set the position label
  4402. # self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4403. # "<b>Y</b>: %.4f" % (location[0], location[1]))
  4404. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4405. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4406. units = self.defaults["units"].lower()
  4407. self.plotcanvas.text_hud.text = \
  4408. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4409. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4410. self.inform.emit('[success] %s' % _("Done."))
  4411. return location
  4412. def on_copy_command(self):
  4413. """
  4414. Will copy a selection of objects, creating new objects.
  4415. :return:
  4416. """
  4417. self.defaults.report_usage("on_copy_command()")
  4418. def initialize(obj_init, app):
  4419. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4420. try:
  4421. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4422. except AttributeError:
  4423. pass
  4424. try:
  4425. obj_init.apertures = deepcopy(obj.apertures)
  4426. except AttributeError:
  4427. pass
  4428. try:
  4429. if obj.tools:
  4430. obj_init.tools = deepcopy(obj.tools)
  4431. except Exception as err:
  4432. log.debug("App.on_copy_command() --> %s" % str(err))
  4433. try:
  4434. obj_init.source_file = deepcopy(obj.source_file)
  4435. except (AttributeError, TypeError):
  4436. pass
  4437. def initialize_excellon(obj_init, app):
  4438. obj_init.source_file = deepcopy(obj.source_file)
  4439. obj_init.tools = deepcopy(obj.tools)
  4440. # drills are offset, so they need to be deep copied
  4441. obj_init.drills = deepcopy(obj.drills)
  4442. # slots are offset, so they need to be deep copied
  4443. obj_init.slots = deepcopy(obj.slots)
  4444. obj_init.create_geometry()
  4445. def initialize_script(obj_init, app_obj):
  4446. obj_init.source_file = deepcopy(obj.source_file)
  4447. def initialize_document(obj_init, app_obj):
  4448. obj_init.source_file = deepcopy(obj.source_file)
  4449. for obj in self.collection.get_selected():
  4450. obj_name = obj.options["name"]
  4451. try:
  4452. if isinstance(obj, ExcellonObject):
  4453. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4454. elif isinstance(obj, GerberObject):
  4455. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4456. elif isinstance(obj, GeometryObject):
  4457. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4458. elif isinstance(obj, ScriptObject):
  4459. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4460. elif isinstance(obj, DocumentObject):
  4461. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4462. except Exception as e:
  4463. return "Operation failed: %s" % str(e)
  4464. def on_copy_object2(self, custom_name):
  4465. def initialize_geometry(obj_init, app):
  4466. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4467. try:
  4468. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4469. except AttributeError:
  4470. pass
  4471. try:
  4472. obj_init.apertures = deepcopy(obj.apertures)
  4473. except AttributeError:
  4474. pass
  4475. try:
  4476. if obj.tools:
  4477. obj_init.tools = deepcopy(obj.tools)
  4478. except Exception as ee:
  4479. log.debug("on_copy_object2() --> %s" % str(ee))
  4480. def initialize_gerber(obj_init, app):
  4481. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4482. obj_init.apertures = deepcopy(obj.apertures)
  4483. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4484. def initialize_excellon(obj_init, app):
  4485. obj_init.tools = deepcopy(obj.tools)
  4486. # drills are offset, so they need to be deep copied
  4487. obj_init.drills = deepcopy(obj.drills)
  4488. # slots are offset, so they need to be deep copied
  4489. obj_init.slots = deepcopy(obj.slots)
  4490. obj_init.create_geometry()
  4491. for obj in self.collection.get_selected():
  4492. obj_name = obj.options["name"]
  4493. try:
  4494. if isinstance(obj, ExcellonObject):
  4495. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4496. elif isinstance(obj, GerberObject):
  4497. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4498. elif isinstance(obj, GeometryObject):
  4499. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4500. except Exception as er:
  4501. return "Operation failed: %s" % str(er)
  4502. def on_rename_object(self, text):
  4503. """
  4504. Will rename an object.
  4505. :param text: New name for the object.
  4506. :return:
  4507. """
  4508. self.defaults.report_usage("on_rename_object()")
  4509. named_obj = self.collection.get_active()
  4510. for obj in named_obj:
  4511. if obj is list:
  4512. self.on_rename_object(text)
  4513. else:
  4514. try:
  4515. obj.options['name'] = text
  4516. except Exception as e:
  4517. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4518. def convert_any2geo(self):
  4519. """
  4520. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4521. :return:
  4522. """
  4523. self.defaults.report_usage("convert_any2geo()")
  4524. def initialize(obj_init, app):
  4525. obj_init.solid_geometry = obj.solid_geometry
  4526. try:
  4527. obj_init.follow_geometry = obj.follow_geometry
  4528. except AttributeError:
  4529. pass
  4530. try:
  4531. obj_init.apertures = obj.apertures
  4532. except AttributeError:
  4533. pass
  4534. try:
  4535. if obj.tools:
  4536. obj_init.tools = obj.tools
  4537. except AttributeError:
  4538. pass
  4539. def initialize_excellon(obj_init, app):
  4540. # objs = self.collection.get_selected()
  4541. # GeometryObject.merge(objs, obj)
  4542. solid_geo = []
  4543. for tool in obj.tools:
  4544. for geo in obj.tools[tool]['solid_geometry']:
  4545. solid_geo.append(geo)
  4546. obj_init.solid_geometry = deepcopy(solid_geo)
  4547. if not self.collection.get_selected():
  4548. log.warning("App.convert_any2geo --> No object selected")
  4549. self.inform.emit('[WARNING_NOTCL] %s' %
  4550. _("No object is selected. Select an object and try again."))
  4551. return
  4552. for obj in self.collection.get_selected():
  4553. obj_name = obj.options["name"]
  4554. try:
  4555. if isinstance(obj, ExcellonObject):
  4556. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4557. else:
  4558. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4559. except Exception as e:
  4560. return "Operation failed: %s" % str(e)
  4561. def convert_any2gerber(self):
  4562. """
  4563. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4564. :return:
  4565. """
  4566. self.defaults.report_usage("convert_any2gerber()")
  4567. def initialize_geometry(obj_init, app):
  4568. apertures = {}
  4569. apid = 0
  4570. apertures[str(apid)] = {}
  4571. apertures[str(apid)]['geometry'] = []
  4572. for obj_orig in obj.solid_geometry:
  4573. new_elem = {}
  4574. new_elem['solid'] = obj_orig
  4575. try:
  4576. new_elem['follow'] = obj_orig.exterior
  4577. except AttributeError:
  4578. pass
  4579. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4580. apertures[str(apid)]['size'] = 0.0
  4581. apertures[str(apid)]['type'] = 'C'
  4582. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4583. obj_init.apertures = deepcopy(apertures)
  4584. def initialize_excellon(obj_init, app):
  4585. apertures = {}
  4586. apid = 10
  4587. for tool in obj.tools:
  4588. apertures[str(apid)] = {}
  4589. apertures[str(apid)]['geometry'] = []
  4590. for geo in obj.tools[tool]['solid_geometry']:
  4591. new_el = {}
  4592. new_el['solid'] = geo
  4593. new_el['follow'] = geo.exterior
  4594. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4595. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4596. apertures[str(apid)]['type'] = 'C'
  4597. apid += 1
  4598. # create solid_geometry
  4599. solid_geometry = []
  4600. for apid in apertures:
  4601. for geo_el in apertures[apid]['geometry']:
  4602. solid_geometry.append(geo_el['solid'])
  4603. solid_geometry = MultiPolygon(solid_geometry)
  4604. solid_geometry = solid_geometry.buffer(0.0000001)
  4605. obj_init.solid_geometry = deepcopy(solid_geometry)
  4606. obj_init.apertures = deepcopy(apertures)
  4607. # clear the working objects (perhaps not necessary due of Python GC)
  4608. apertures.clear()
  4609. if not self.collection.get_selected():
  4610. log.warning("App.convert_any2gerber --> No object selected")
  4611. self.inform.emit('[WARNING_NOTCL] %s' %
  4612. _("No object is selected. Select an object and try again."))
  4613. return
  4614. for obj in self.collection.get_selected():
  4615. obj_name = obj.options["name"]
  4616. try:
  4617. if isinstance(obj, ExcellonObject):
  4618. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4619. elif isinstance(obj, GeometryObject):
  4620. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4621. else:
  4622. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4623. except Exception as e:
  4624. return "Operation failed: %s" % str(e)
  4625. def abort_all_tasks(self):
  4626. """
  4627. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4628. on the first possible occasion.
  4629. :return:
  4630. """
  4631. if self.abort_flag is False:
  4632. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4633. self.abort_flag = True
  4634. self.cleanup.emit()
  4635. def app_is_idle(self):
  4636. if self.abort_flag:
  4637. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4638. self.abort_flag = False
  4639. def on_selectall(self):
  4640. """
  4641. Will draw a selection box shape around the selected objects.
  4642. :return:
  4643. """
  4644. self.defaults.report_usage("on_selectall()")
  4645. # delete the possible selection box around a possible selected object
  4646. self.delete_selection_shape()
  4647. for name in self.collection.get_names():
  4648. self.collection.set_active(name)
  4649. curr_sel_obj = self.collection.get_by_name(name)
  4650. # create the selection box around the selected object
  4651. if self.defaults['global_selection_shape'] is True:
  4652. self.draw_selection_shape(curr_sel_obj)
  4653. def on_preferences(self):
  4654. """
  4655. Adds the Preferences in a Tab in Plot Area
  4656. :return:
  4657. """
  4658. # add the tab if it was closed
  4659. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4660. # delete the absolute and relative position and messages in the infobar
  4661. # self.ui.position_label.setText("")
  4662. # self.ui.rel_position_label.setText("")
  4663. # Switch plot_area to preferences page
  4664. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4665. # self.ui.show()
  4666. # detect changes in the preferences
  4667. for idx in range(self.ui.pref_tab_area.count()):
  4668. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4669. try:
  4670. try:
  4671. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4672. except (TypeError, AttributeError):
  4673. pass
  4674. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4675. except AttributeError:
  4676. pass
  4677. try:
  4678. try:
  4679. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4680. except (TypeError, AttributeError):
  4681. pass
  4682. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4683. except AttributeError:
  4684. pass
  4685. try:
  4686. try:
  4687. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4688. except (TypeError, AttributeError):
  4689. pass
  4690. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4691. except AttributeError:
  4692. pass
  4693. try:
  4694. try:
  4695. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4696. except (TypeError, AttributeError):
  4697. pass
  4698. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4699. except AttributeError:
  4700. pass
  4701. try:
  4702. try:
  4703. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4704. except (TypeError, AttributeError):
  4705. pass
  4706. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4707. except AttributeError:
  4708. pass
  4709. def on_tools_database(self, source='app'):
  4710. """
  4711. Adds the Tools Database in a Tab in Plot Area.
  4712. :return:
  4713. """
  4714. for idx in range(self.ui.plot_tab_area.count()):
  4715. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4716. # there can be only one instance of Tools Database at one time
  4717. return
  4718. if source == 'app':
  4719. self.tools_db_tab = ToolsDB2(
  4720. app=self,
  4721. parent=self.ui,
  4722. callback_on_edited=self.on_tools_db_edited,
  4723. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4724. )
  4725. elif source == 'ncc':
  4726. self.tools_db_tab = ToolsDB2(
  4727. app=self,
  4728. parent=self.ui,
  4729. callback_on_edited=self.on_tools_db_edited,
  4730. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4731. )
  4732. elif source == 'paint':
  4733. self.tools_db_tab = ToolsDB2(
  4734. app=self,
  4735. parent=self.ui,
  4736. callback_on_edited=self.on_tools_db_edited,
  4737. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4738. )
  4739. # add the tab if it was closed
  4740. try:
  4741. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4742. self.tools_db_tab.setObjectName("database_tab")
  4743. except Exception as e:
  4744. log.debug("App.on_tools_database() --> %s" % str(e))
  4745. return
  4746. # delete the absolute and relative position and messages in the infobar
  4747. self.ui.position_label.setText("")
  4748. self.ui.rel_position_label.setText("")
  4749. # Switch plot_area to preferences page
  4750. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4751. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4752. self.tools_db_tab.ui_connect()
  4753. def on_tools_db_edited(self):
  4754. """
  4755. Executed whenever a tool is edited in Tools Database.
  4756. Will color the text of the Tools Database tab to Red color.
  4757. :return:
  4758. """
  4759. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4760. for idx in range(self.ui.plot_tab_area.count()):
  4761. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4762. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4763. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4764. self.tools_db_changed_flag = True
  4765. def on_geometry_tool_add_from_db_executed(self, tool):
  4766. """
  4767. Here add the tool from DB in the selected geometry object.
  4768. :return:
  4769. """
  4770. tool_from_db = deepcopy(tool)
  4771. obj = self.collection.get_active()
  4772. if isinstance(obj, GeometryObject):
  4773. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4774. # close the tab and delete it
  4775. for idx in range(self.ui.plot_tab_area.count()):
  4776. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4777. wdg = self.ui.plot_tab_area.widget(idx)
  4778. wdg.deleteLater()
  4779. self.ui.plot_tab_area.removeTab(idx)
  4780. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4781. else:
  4782. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4783. def on_plot_area_tab_closed(self, tab_obj_name):
  4784. """
  4785. Executed whenever a QTab is closed in the Plot Area.
  4786. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4787. :return:
  4788. """
  4789. if tab_obj_name == "preferences_tab":
  4790. self.preferencesUiManager.on_close_preferences_tab()
  4791. elif tab_obj_name == "database_tab":
  4792. # disconnect the signals from the table widget in tab
  4793. self.tools_db_tab.ui_disconnect()
  4794. if self.tools_db_changed_flag is True:
  4795. msgbox = QtWidgets.QMessageBox()
  4796. msgbox.setText(_("One or more Tools are edited.\n"
  4797. "Do you want to update the Tools Database?"))
  4798. msgbox.setWindowTitle(_("Save Tools Database"))
  4799. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4800. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4801. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4802. msgbox.setDefaultButton(bt_yes)
  4803. msgbox.exec_()
  4804. response = msgbox.clickedButton()
  4805. if response == bt_yes:
  4806. self.tools_db_tab.on_save_tools_db()
  4807. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4808. else:
  4809. self.tools_db_changed_flag = False
  4810. self.inform.emit('')
  4811. return
  4812. self.tools_db_tab.deleteLater()
  4813. elif tab_obj_name == "text_editor_tab":
  4814. self.toggle_codeeditor = False
  4815. elif tab_obj_name == "bookmarks_tab":
  4816. self.book_dialog_tab.rebuild_actions()
  4817. self.book_dialog_tab.deleteLater()
  4818. else:
  4819. return
  4820. # def on_plotarea_tab_closed(self, tab_idx):
  4821. # """
  4822. #
  4823. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4824. # :return:
  4825. # """
  4826. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4827. #
  4828. # if widget is not None:
  4829. # widget.deleteLater()
  4830. # self.ui.plot_tab_area.removeTab(tab_idx)
  4831. def on_flipy(self):
  4832. """
  4833. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4834. :return:
  4835. """
  4836. self.defaults.report_usage("on_flipy()")
  4837. obj_list = self.collection.get_selected()
  4838. xminlist = []
  4839. yminlist = []
  4840. xmaxlist = []
  4841. ymaxlist = []
  4842. if not obj_list:
  4843. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4844. else:
  4845. try:
  4846. # first get a bounding box to fit all
  4847. for obj in obj_list:
  4848. xmin, ymin, xmax, ymax = obj.bounds()
  4849. xminlist.append(xmin)
  4850. yminlist.append(ymin)
  4851. xmaxlist.append(xmax)
  4852. ymaxlist.append(ymax)
  4853. # get the minimum x,y and maximum x,y for all objects selected
  4854. xminimal = min(xminlist)
  4855. yminimal = min(yminlist)
  4856. xmaximal = max(xmaxlist)
  4857. ymaximal = max(ymaxlist)
  4858. px = 0.5 * (xminimal + xmaximal)
  4859. py = 0.5 * (yminimal + ymaximal)
  4860. # execute mirroring
  4861. for obj in obj_list:
  4862. obj.mirror('X', [px, py])
  4863. obj.plot()
  4864. self.object_changed.emit(obj)
  4865. self.inform.emit('[success] %s' %
  4866. _("Flip on Y axis done."))
  4867. except Exception as e:
  4868. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4869. return
  4870. def on_flipx(self):
  4871. """
  4872. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4873. :return:
  4874. """
  4875. self.defaults.report_usage("on_flipx()")
  4876. obj_list = self.collection.get_selected()
  4877. xminlist = []
  4878. yminlist = []
  4879. xmaxlist = []
  4880. ymaxlist = []
  4881. if not obj_list:
  4882. self.inform.emit('[WARNING_NOTCL] %s' %
  4883. _("No object selected to Flip on X axis."))
  4884. else:
  4885. try:
  4886. # first get a bounding box to fit all
  4887. for obj in obj_list:
  4888. xmin, ymin, xmax, ymax = obj.bounds()
  4889. xminlist.append(xmin)
  4890. yminlist.append(ymin)
  4891. xmaxlist.append(xmax)
  4892. ymaxlist.append(ymax)
  4893. # get the minimum x,y and maximum x,y for all objects selected
  4894. xminimal = min(xminlist)
  4895. yminimal = min(yminlist)
  4896. xmaximal = max(xmaxlist)
  4897. ymaximal = max(ymaxlist)
  4898. px = 0.5 * (xminimal + xmaximal)
  4899. py = 0.5 * (yminimal + ymaximal)
  4900. # execute mirroring
  4901. for obj in obj_list:
  4902. obj.mirror('Y', [px, py])
  4903. obj.plot()
  4904. self.object_changed.emit(obj)
  4905. self.inform.emit('[success] %s' %
  4906. _("Flip on X axis done."))
  4907. except Exception as e:
  4908. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4909. return
  4910. def on_rotate(self, silent=False, preset=None):
  4911. """
  4912. Executed when Options -> Rotate Selection menu entry is clicked.
  4913. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4914. :param preset: A value to be used as predefined angle for rotation.
  4915. :return:
  4916. """
  4917. self.defaults.report_usage("on_rotate()")
  4918. obj_list = self.collection.get_selected()
  4919. xminlist = []
  4920. yminlist = []
  4921. xmaxlist = []
  4922. ymaxlist = []
  4923. if not obj_list:
  4924. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4925. else:
  4926. if silent is False:
  4927. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4928. min=-360, max=360, decimals=4,
  4929. init_val=float(self.defaults['tools_transform_rotate']))
  4930. num, ok = rotatebox.get_value()
  4931. else:
  4932. num = preset
  4933. ok = True
  4934. if ok:
  4935. try:
  4936. # first get a bounding box to fit all
  4937. for obj in obj_list:
  4938. xmin, ymin, xmax, ymax = obj.bounds()
  4939. xminlist.append(xmin)
  4940. yminlist.append(ymin)
  4941. xmaxlist.append(xmax)
  4942. ymaxlist.append(ymax)
  4943. # get the minimum x,y and maximum x,y for all objects selected
  4944. xminimal = min(xminlist)
  4945. yminimal = min(yminlist)
  4946. xmaximal = max(xmaxlist)
  4947. ymaximal = max(ymaxlist)
  4948. px = 0.5 * (xminimal + xmaximal)
  4949. py = 0.5 * (yminimal + ymaximal)
  4950. for sel_obj in obj_list:
  4951. sel_obj.rotate(-float(num), point=(px, py))
  4952. sel_obj.plot()
  4953. self.object_changed.emit(sel_obj)
  4954. self.inform.emit('[success] %s' %
  4955. _("Rotation done."))
  4956. except Exception as e:
  4957. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4958. return
  4959. def on_skewx(self):
  4960. """
  4961. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4962. :return:
  4963. """
  4964. self.defaults.report_usage("on_skewx()")
  4965. obj_list = self.collection.get_selected()
  4966. xminlist = []
  4967. yminlist = []
  4968. if not obj_list:
  4969. self.inform.emit('[WARNING_NOTCL] %s' %
  4970. _("No object selected to Skew/Shear on X axis."))
  4971. else:
  4972. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4973. min=-360, max=360, decimals=4,
  4974. init_val=float(self.defaults['tools_transform_skew_x']))
  4975. num, ok = skewxbox.get_value()
  4976. if ok:
  4977. # first get a bounding box to fit all
  4978. for obj in obj_list:
  4979. xmin, ymin, xmax, ymax = obj.bounds()
  4980. xminlist.append(xmin)
  4981. yminlist.append(ymin)
  4982. # get the minimum x,y and maximum x,y for all objects selected
  4983. xminimal = min(xminlist)
  4984. yminimal = min(yminlist)
  4985. for obj in obj_list:
  4986. obj.skew(num, 0, point=(xminimal, yminimal))
  4987. obj.plot()
  4988. self.object_changed.emit(obj)
  4989. self.inform.emit('[success] %s' %
  4990. _("Skew on X axis done."))
  4991. def on_skewy(self):
  4992. """
  4993. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4994. :return:
  4995. """
  4996. self.defaults.report_usage("on_skewy()")
  4997. obj_list = self.collection.get_selected()
  4998. xminlist = []
  4999. yminlist = []
  5000. if not obj_list:
  5001. self.inform.emit('[WARNING_NOTCL] %s' %
  5002. _("No object selected to Skew/Shear on Y axis."))
  5003. else:
  5004. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5005. min=-360, max=360, decimals=4,
  5006. init_val=float(self.defaults['tools_transform_skew_y']))
  5007. num, ok = skewybox.get_value()
  5008. if ok:
  5009. # first get a bounding box to fit all
  5010. for obj in obj_list:
  5011. xmin, ymin, xmax, ymax = obj.bounds()
  5012. xminlist.append(xmin)
  5013. yminlist.append(ymin)
  5014. # get the minimum x,y and maximum x,y for all objects selected
  5015. xminimal = min(xminlist)
  5016. yminimal = min(yminlist)
  5017. for obj in obj_list:
  5018. obj.skew(0, num, point=(xminimal, yminimal))
  5019. obj.plot()
  5020. self.object_changed.emit(obj)
  5021. self.inform.emit('[success] %s' %
  5022. _("Skew on Y axis done."))
  5023. def on_plots_updated(self):
  5024. """
  5025. Callback used to report when the plots have changed.
  5026. Adjust axes and zooms to fit.
  5027. :return: None
  5028. """
  5029. if self.is_legacy is False:
  5030. self.plotcanvas.update()
  5031. else:
  5032. self.plotcanvas.auto_adjust_axes()
  5033. self.on_zoom_fit(None)
  5034. self.collection.update_view()
  5035. # self.inform.emit(_("Plots updated ..."))
  5036. def on_toolbar_replot(self):
  5037. """
  5038. Callback for toolbar button. Re-plots all objects.
  5039. :return: None
  5040. """
  5041. self.defaults.report_usage("on_toolbar_replot")
  5042. self.log.debug("on_toolbar_replot()")
  5043. try:
  5044. self.collection.get_active().read_form()
  5045. except AttributeError:
  5046. self.log.debug("on_toolbar_replot(): AttributeError")
  5047. pass
  5048. self.plot_all()
  5049. def on_row_activated(self, index):
  5050. if index.isValid():
  5051. if index.internalPointer().parent_item != self.collection.root_item:
  5052. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5053. self.collection.on_item_activated(index)
  5054. def on_row_selected(self, obj_name):
  5055. """
  5056. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5057. It mean we clicked outside of the items and deselected all
  5058. :param obj_name:
  5059. :return:
  5060. """
  5061. if obj_name == 'none':
  5062. for act in self.ui.menuobjects.actions():
  5063. act.setChecked(False)
  5064. return
  5065. # get the name of the selected objects and add them to a list
  5066. name_list = []
  5067. for obj in self.collection.get_selected():
  5068. name_list.append(obj.options['name'])
  5069. # set all actions as unchecked but the ones selected make them checked
  5070. for act in self.ui.menuobjects.actions():
  5071. act.setChecked(False)
  5072. if act.text() in name_list:
  5073. act.setChecked(True)
  5074. def on_collection_updated(self, obj, state, old_name):
  5075. """
  5076. Create a menu from the object loaded in the collection.
  5077. :param obj: object that was changed (added, deleted, renamed)
  5078. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5079. :param old_name: the old name of the object before the action that triggered this slot happened
  5080. :return: None
  5081. """
  5082. icon_files = {
  5083. "gerber": self.resource_location + "/flatcam_icon16.png",
  5084. "excellon": self.resource_location + "/drill16.png",
  5085. "cncjob": self.resource_location + "/cnc16.png",
  5086. "geometry": self.resource_location + "/geometry16.png",
  5087. "script": self.resource_location + "/script_new16.png",
  5088. "document": self.resource_location + "/notes16_1.png"
  5089. }
  5090. if state == 'append':
  5091. for act in self.ui.menuobjects.actions():
  5092. try:
  5093. act.triggered.disconnect()
  5094. except TypeError:
  5095. pass
  5096. self.ui.menuobjects.clear()
  5097. gerber_list = []
  5098. exc_list = []
  5099. cncjob_list = []
  5100. geo_list = []
  5101. script_list = []
  5102. doc_list = []
  5103. for name in self.collection.get_names():
  5104. obj_named = self.collection.get_by_name(name)
  5105. if obj_named.kind == 'gerber':
  5106. gerber_list.append(name)
  5107. elif obj_named.kind == 'excellon':
  5108. exc_list.append(name)
  5109. elif obj_named.kind == 'cncjob':
  5110. cncjob_list.append(name)
  5111. elif obj_named.kind == 'geometry':
  5112. geo_list.append(name)
  5113. elif obj_named.kind == 'script':
  5114. script_list.append(name)
  5115. elif obj_named.kind == 'document':
  5116. doc_list.append(name)
  5117. def add_act(o_name):
  5118. obj_for_icon = self.collection.get_by_name(o_name)
  5119. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5120. add_action.setCheckable(True)
  5121. add_action.setText(o_name)
  5122. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5123. add_action.triggered.connect(
  5124. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5125. self.collection.set_inactive(o_name))
  5126. self.ui.menuobjects.addAction(add_action)
  5127. for name in gerber_list:
  5128. add_act(name)
  5129. self.ui.menuobjects.addSeparator()
  5130. for name in exc_list:
  5131. add_act(name)
  5132. self.ui.menuobjects.addSeparator()
  5133. for name in cncjob_list:
  5134. add_act(name)
  5135. self.ui.menuobjects.addSeparator()
  5136. for name in geo_list:
  5137. add_act(name)
  5138. self.ui.menuobjects.addSeparator()
  5139. for name in script_list:
  5140. add_act(name)
  5141. self.ui.menuobjects.addSeparator()
  5142. for name in doc_list:
  5143. add_act(name)
  5144. self.ui.menuobjects.addSeparator()
  5145. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5146. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5147. _('Select All')
  5148. )
  5149. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5150. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5151. _('Deselect All')
  5152. )
  5153. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5154. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5155. elif state == 'delete':
  5156. for act in self.ui.menuobjects.actions():
  5157. if act.text() == obj.options['name']:
  5158. try:
  5159. act.triggered.disconnect()
  5160. except TypeError:
  5161. pass
  5162. self.ui.menuobjects.removeAction(act)
  5163. break
  5164. elif state == 'rename':
  5165. for act in self.ui.menuobjects.actions():
  5166. if act.text() == old_name:
  5167. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5168. add_action.setText(obj.options['name'])
  5169. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5170. add_action.triggered.connect(
  5171. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5172. self.collection.set_inactive(obj.options['name']))
  5173. self.ui.menuobjects.insertAction(act, add_action)
  5174. try:
  5175. act.triggered.disconnect()
  5176. except TypeError:
  5177. pass
  5178. self.ui.menuobjects.removeAction(act)
  5179. break
  5180. elif state == 'delete_all':
  5181. for act in self.ui.menuobjects.actions():
  5182. try:
  5183. act.triggered.disconnect()
  5184. except TypeError:
  5185. pass
  5186. self.ui.menuobjects.clear()
  5187. self.ui.menuobjects.addSeparator()
  5188. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5189. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5190. _('Select All')
  5191. )
  5192. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5193. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5194. _('Deselect All')
  5195. )
  5196. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5197. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5198. def on_objects_selection(self, on_off):
  5199. obj_list = self.collection.get_names()
  5200. if on_off is True:
  5201. self.collection.set_all_active()
  5202. for act in self.ui.menuobjects.actions():
  5203. try:
  5204. act.setChecked(True)
  5205. except Exception:
  5206. pass
  5207. if obj_list:
  5208. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5209. else:
  5210. self.collection.set_all_inactive()
  5211. for act in self.ui.menuobjects.actions():
  5212. try:
  5213. act.setChecked(False)
  5214. except Exception:
  5215. pass
  5216. if obj_list:
  5217. self.inform.emit('%s' % _("Objects selection is cleared."))
  5218. else:
  5219. self.inform.emit('')
  5220. def grid_status(self):
  5221. if self.ui.grid_snap_btn.isChecked():
  5222. return True
  5223. else:
  5224. return False
  5225. def populate_cmenu_grids(self):
  5226. units = self.defaults['units'].lower()
  5227. # for act in self.ui.cmenu_gridmenu.actions():
  5228. # act.triggered.disconnect()
  5229. self.ui.cmenu_gridmenu.clear()
  5230. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5231. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5232. _("Grid On/Off"))
  5233. grid_toggle.setCheckable(True)
  5234. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5235. self.ui.cmenu_gridmenu.addSeparator()
  5236. for grid in sorted_list:
  5237. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5238. "%s" % str(grid))
  5239. action.triggered.connect(self.set_grid)
  5240. self.ui.cmenu_gridmenu.addSeparator()
  5241. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5242. _("Add"))
  5243. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5244. _("Delete"))
  5245. grid_add.triggered.connect(self.on_grid_add)
  5246. grid_delete.triggered.connect(self.on_grid_delete)
  5247. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5248. def set_grid(self):
  5249. menu_action = self.sender()
  5250. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5251. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5252. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5253. def on_grid_add(self):
  5254. # ## Current application units in lower Case
  5255. units = self.defaults['units'].lower()
  5256. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5257. text=_('Enter a Grid Value:'),
  5258. min=0.0000, max=99.9999, decimals=4)
  5259. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5260. val, ok = grid_add_popup.get_value()
  5261. if ok:
  5262. if float(val) == 0:
  5263. self.inform.emit('[WARNING_NOTCL] %s' %
  5264. _("Please enter a grid value with non-zero value, in Float format."))
  5265. return
  5266. else:
  5267. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5268. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5269. self.inform.emit('[success] %s...' %
  5270. _("New Grid added"))
  5271. else:
  5272. self.inform.emit('[WARNING_NOTCL] %s...' %
  5273. _("Grid already exists"))
  5274. else:
  5275. self.inform.emit('[WARNING_NOTCL] %s...' %
  5276. _("Adding New Grid cancelled"))
  5277. def on_grid_delete(self):
  5278. # ## Current application units in lower Case
  5279. units = self.defaults['units'].lower()
  5280. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5281. text='Enter a Grid Value:',
  5282. min=0.0000, max=99.9999, decimals=4)
  5283. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5284. val, ok = grid_del_popup.get_value()
  5285. if ok:
  5286. if float(val) == 0:
  5287. self.inform.emit('[WARNING_NOTCL] %s' %
  5288. _("Please enter a grid value with non-zero value, in Float format."))
  5289. return
  5290. else:
  5291. try:
  5292. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5293. except ValueError:
  5294. self.inform.emit('[ERROR_NOTCL]%s...' %
  5295. _(" Grid Value does not exist"))
  5296. return
  5297. self.inform.emit('[success] %s...' %
  5298. _("Grid Value deleted"))
  5299. else:
  5300. self.inform.emit('[WARNING_NOTCL] %s...' %
  5301. _("Delete Grid value cancelled"))
  5302. def on_shortcut_list(self):
  5303. self.defaults.report_usage("on_shortcut_list()")
  5304. # add the tab if it was closed
  5305. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5306. # delete the absolute and relative position and messages in the infobar
  5307. self.ui.position_label.setText("")
  5308. self.ui.rel_position_label.setText("")
  5309. # Switch plot_area to preferences page
  5310. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5311. # self.ui.show()
  5312. def on_select_tab(self, name):
  5313. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5314. if self.ui.splitter.sizes()[0] == 0:
  5315. self.ui.splitter.setSizes([1, 1])
  5316. else:
  5317. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5318. self.ui.splitter.setSizes([0, 1])
  5319. if name == 'project':
  5320. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5321. elif name == 'selected':
  5322. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5323. elif name == 'tool':
  5324. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5325. def on_copy_name(self):
  5326. self.defaults.report_usage("on_copy_name()")
  5327. obj = self.collection.get_active()
  5328. try:
  5329. name = obj.options["name"]
  5330. except AttributeError:
  5331. log.debug("on_copy_name() --> No object selected to copy it's name")
  5332. self.inform.emit('[WARNING_NOTCL]%s' %
  5333. _(" No object selected to copy it's name"))
  5334. return
  5335. self.clipboard.setText(name)
  5336. self.inform.emit(_("Name copied on clipboard ..."))
  5337. def on_mouse_click_over_plot(self, event):
  5338. """
  5339. Default actions are:
  5340. :param event: Contains information about the event, like which button
  5341. was clicked, the pixel coordinates and the axes coordinates.
  5342. :return: None
  5343. """
  5344. self.pos = []
  5345. if self.is_legacy is False:
  5346. event_pos = event.pos
  5347. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5348. # # Set the mouse button for panning
  5349. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5350. else:
  5351. event_pos = (event.xdata, event.ydata)
  5352. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5353. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5354. # So it can receive key presses
  5355. self.plotcanvas.native.setFocus()
  5356. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5357. if self.grid_status():
  5358. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5359. else:
  5360. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5361. try:
  5362. if event.button == 1:
  5363. # Reset here the relative coordinates so there is a new reference on the click position
  5364. if self.rel_point1 is None:
  5365. self.rel_point1 = self.pos
  5366. else:
  5367. self.rel_point2 = copy(self.rel_point1)
  5368. self.rel_point1 = self.pos
  5369. self.on_mouse_move_over_plot(event, origin_click=True)
  5370. except Exception as e:
  5371. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5372. def on_mouse_double_click_over_plot(self, event):
  5373. if event.button == 1:
  5374. self.doubleclick = True
  5375. def on_mouse_move_over_plot(self, event, origin_click=None):
  5376. """
  5377. Callback for the mouse motion event over the plot.
  5378. :param event: Contains information about the event.
  5379. :param origin_click
  5380. :return: None
  5381. """
  5382. if self.is_legacy is False:
  5383. event_pos = event.pos
  5384. if self.defaults["global_pan_button"] == '2':
  5385. pan_button = 2
  5386. else:
  5387. pan_button = 3
  5388. self.event_is_dragging = event.is_dragging
  5389. else:
  5390. event_pos = (event.xdata, event.ydata)
  5391. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5392. if self.defaults["global_pan_button"] == '2':
  5393. pan_button = 3
  5394. else:
  5395. pan_button = 2
  5396. self.event_is_dragging = self.plotcanvas.is_dragging
  5397. # So it can receive key presses but not when the Tcl Shell is active
  5398. if not self.ui.shell_dock.isVisible():
  5399. if not self.plotcanvas.native.hasFocus():
  5400. self.plotcanvas.native.setFocus()
  5401. self.pos_jump = event_pos
  5402. self.ui.popMenu.mouse_is_panning = False
  5403. if origin_click is None:
  5404. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5405. if event.button == pan_button and self.event_is_dragging == 1:
  5406. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5407. if self.ui.popMenu.popup_active:
  5408. self.ui.popMenu.popup_active = False
  5409. return
  5410. self.ui.popMenu.mouse_is_panning = True
  5411. return
  5412. if self.rel_point1 is not None:
  5413. try: # May fail in case mouse not within axes
  5414. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5415. if pos_canvas[0] is None or pos_canvas[1] is None:
  5416. return
  5417. if self.grid_status():
  5418. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5419. # Update cursor
  5420. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5421. symbol='++', edge_color=self.cursor_color_3D,
  5422. edge_width=self.defaults["global_cursor_width"],
  5423. size=self.defaults["global_cursor_size"])
  5424. else:
  5425. pos = (pos_canvas[0], pos_canvas[1])
  5426. self.dx = pos[0] - float(self.rel_point1[0])
  5427. self.dy = pos[1] - float(self.rel_point1[1])
  5428. # self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5429. # "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5430. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5431. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5432. units = self.defaults["units"].lower()
  5433. self.plotcanvas.text_hud.text = \
  5434. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5435. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5436. self.mouse = [pos[0], pos[1]]
  5437. # if the mouse is moved and the LMB is clicked then the action is a selection
  5438. if self.event_is_dragging == 1 and event.button == 1:
  5439. self.delete_selection_shape()
  5440. if self.dx < 0:
  5441. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5442. face_color=self.defaults['global_alt_sel_fill'])
  5443. self.selection_type = False
  5444. elif self.dx >= 0:
  5445. self.draw_moving_selection_shape(self.pos, pos)
  5446. self.selection_type = True
  5447. else:
  5448. self.selection_type = None
  5449. else:
  5450. self.selection_type = None
  5451. # hover effect - enabled in Preferences -> General -> GUI Settings
  5452. if self.defaults['global_hover']:
  5453. for obj in self.collection.get_list():
  5454. try:
  5455. # select the object(s) only if it is enabled (plotted)
  5456. if obj.options['plot']:
  5457. if obj not in self.collection.get_selected():
  5458. poly_obj = Polygon(
  5459. [(obj.options['xmin'], obj.options['ymin']),
  5460. (obj.options['xmax'], obj.options['ymin']),
  5461. (obj.options['xmax'], obj.options['ymax']),
  5462. (obj.options['xmin'], obj.options['ymax'])]
  5463. )
  5464. if Point(pos).within(poly_obj):
  5465. if obj.isHovering is False:
  5466. obj.isHovering = True
  5467. obj.notHovering = True
  5468. # create the selection box around the selected object
  5469. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5470. else:
  5471. if obj.notHovering is True:
  5472. obj.notHovering = False
  5473. obj.isHovering = False
  5474. self.delete_hover_shape()
  5475. except Exception:
  5476. # the Exception here will happen if we try to select on screen and we have an
  5477. # newly (and empty) just created Geometry or Excellon object that do not have the
  5478. # xmin, xmax, ymin, ymax options.
  5479. # In this case poly_obj creation (see above) will fail
  5480. pass
  5481. except Exception as e:
  5482. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5483. # self.ui.position_label.setText("")
  5484. # self.ui.rel_position_label.setText("")
  5485. self.mouse = None
  5486. def on_mouse_click_release_over_plot(self, event):
  5487. """
  5488. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5489. and has been registered in ''self.__init__()''.
  5490. :param event: contains information about the event.
  5491. :return:
  5492. """
  5493. if self.is_legacy is False:
  5494. event_pos = event.pos
  5495. right_button = 2
  5496. else:
  5497. event_pos = (event.xdata, event.ydata)
  5498. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5499. right_button = 3
  5500. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5501. if self.grid_status():
  5502. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5503. else:
  5504. pos = (pos_canvas[0], pos_canvas[1])
  5505. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5506. # canvas menu
  5507. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5508. self.ui.popMenu.mouse_is_panning = False
  5509. self.cursor = QtGui.QCursor()
  5510. self.populate_cmenu_grids()
  5511. self.ui.popMenu.popup(self.cursor.pos())
  5512. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5513. # selection and then select a type of selection ("enclosing" or "touching")
  5514. if event.button == 1: # left click
  5515. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5516. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5517. if modifiers == QtCore.Qt.ShiftModifier:
  5518. # do not auto open the Project Tab
  5519. self.click_noproject = True
  5520. self.clipboard.setText(
  5521. self.defaults["global_point_clipboard_format"] %
  5522. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5523. )
  5524. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5525. return
  5526. if self.doubleclick is True:
  5527. self.doubleclick = False
  5528. if self.collection.get_selected():
  5529. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5530. if self.ui.splitter.sizes()[0] == 0:
  5531. self.ui.splitter.setSizes([1, 1])
  5532. try:
  5533. # delete the selection shape(S) as it may be in the way
  5534. self.delete_selection_shape()
  5535. self.delete_hover_shape()
  5536. except Exception as e:
  5537. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5538. return
  5539. else:
  5540. # WORKAROUND for LEGACY MODE
  5541. if self.is_legacy is True:
  5542. # if there is no move on canvas then we have no dragging selection
  5543. if self.dx == 0 or self.dy == 0:
  5544. self.selection_type = None
  5545. if self.selection_type is not None:
  5546. try:
  5547. self.selection_area_handler(self.pos, pos, self.selection_type)
  5548. self.selection_type = None
  5549. except Exception as e:
  5550. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5551. return
  5552. else:
  5553. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5554. if key_modifier == QtCore.Qt.ShiftModifier:
  5555. mod_key = 'Shift'
  5556. elif key_modifier == QtCore.Qt.ControlModifier:
  5557. mod_key = 'Control'
  5558. else:
  5559. mod_key = None
  5560. try:
  5561. if self.command_active is None:
  5562. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5563. # deselect, and if it's not selected then it will be selected
  5564. # If there is no active command (self.command_active is None) then we check if we clicked
  5565. # on a object by checking the bounding limits against mouse click position
  5566. if mod_key == self.defaults["global_mselect_key"]:
  5567. self.select_objects(key='multisel')
  5568. else:
  5569. # If there is no active command (self.command_active is None) then we check if
  5570. # we clicked on a object by checking the bounding limits against mouse click position
  5571. self.select_objects()
  5572. self.delete_hover_shape()
  5573. except Exception as e:
  5574. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5575. return
  5576. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5577. """
  5578. :param start_pos: mouse position when the selection LMB click was done
  5579. :param end_pos: mouse position when the left mouse button is released
  5580. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5581. :return:
  5582. """
  5583. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5584. # delete previous selection shape
  5585. self.delete_selection_shape()
  5586. # make all objects inactive
  5587. self.collection.set_all_inactive()
  5588. for obj in self.collection.get_list():
  5589. try:
  5590. # select the object(s) only if it is enabled (plotted)
  5591. if obj.options['plot']:
  5592. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5593. (obj.options['xmax'], obj.options['ymin']),
  5594. (obj.options['xmax'], obj.options['ymax']),
  5595. (obj.options['xmin'], obj.options['ymax'])])
  5596. if sel_type is True:
  5597. if poly_obj.within(poly_selection):
  5598. # create the selection box around the selected object
  5599. if self.defaults['global_selection_shape'] is True:
  5600. self.draw_selection_shape(obj)
  5601. self.collection.set_active(obj.options['name'])
  5602. else:
  5603. if poly_selection.intersects(poly_obj):
  5604. # create the selection box around the selected object
  5605. if self.defaults['global_selection_shape'] is True:
  5606. self.draw_selection_shape(obj)
  5607. self.collection.set_active(obj.options['name'])
  5608. obj.selection_shape_drawn = True
  5609. except Exception as e:
  5610. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5611. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5612. # In this case poly_obj creation (see above) will fail
  5613. log.debug("App.selection_area_handler() --> %s" % str(e))
  5614. def select_objects(self, key=None):
  5615. """
  5616. Will select objects clicked on canvas
  5617. :param key: for future use in cumulative selection
  5618. :return:
  5619. """
  5620. # list where we store the overlapped objects under our mouse left click position
  5621. if key is None:
  5622. self.objects_under_the_click_list = []
  5623. # Populate the list with the overlapped objects on the click position
  5624. curr_x, curr_y = self.pos
  5625. for obj in self.all_objects_list:
  5626. # ScriptObject and DocumentObject objects can't be selected
  5627. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5628. continue
  5629. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5630. continue
  5631. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5632. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5633. if obj.options['name'] not in self.objects_under_the_click_list:
  5634. if obj.options['plot']:
  5635. # add objects to the objects_under_the_click list only if the object is plotted
  5636. # (active and not disabled)
  5637. self.objects_under_the_click_list.append(obj.options['name'])
  5638. try:
  5639. if self.objects_under_the_click_list:
  5640. curr_sel_obj = self.collection.get_active()
  5641. # case when there is only an object under the click and we toggle it
  5642. if len(self.objects_under_the_click_list) == 1:
  5643. if curr_sel_obj is None:
  5644. self.collection.set_active(self.objects_under_the_click_list[0])
  5645. curr_sel_obj = self.collection.get_active()
  5646. # create the selection box around the selected object
  5647. if self.defaults['global_selection_shape'] is True:
  5648. self.draw_selection_shape(curr_sel_obj)
  5649. curr_sel_obj.selection_shape_drawn = True
  5650. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5651. self.on_objects_selection(False)
  5652. self.delete_selection_shape()
  5653. curr_sel_obj.selection_shape_drawn = False
  5654. self.collection.set_active(self.objects_under_the_click_list[0])
  5655. curr_sel_obj = self.collection.get_active()
  5656. # create the selection box around the selected object
  5657. if self.defaults['global_selection_shape'] is True:
  5658. self.draw_selection_shape(curr_sel_obj)
  5659. curr_sel_obj.selection_shape_drawn = True
  5660. self.selected_message(curr_sel_obj=curr_sel_obj)
  5661. elif curr_sel_obj.selection_shape_drawn is False:
  5662. if self.defaults['global_selection_shape'] is True:
  5663. self.draw_selection_shape(curr_sel_obj)
  5664. curr_sel_obj.selection_shape_drawn = True
  5665. else:
  5666. self.on_objects_selection(False)
  5667. self.delete_selection_shape()
  5668. if self.call_source != 'app':
  5669. self.call_source = 'app'
  5670. self.selected_message(curr_sel_obj=curr_sel_obj)
  5671. else:
  5672. # If there is no selected object
  5673. # make active the first element of the overlapped objects list
  5674. if self.collection.get_active() is None:
  5675. self.collection.set_active(self.objects_under_the_click_list[0])
  5676. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5677. name_sel_obj = self.collection.get_active().options['name']
  5678. # In case that there is a selected object but it is not in the overlapped object list
  5679. # make that object inactive and activate the first element in the overlapped object list
  5680. if name_sel_obj not in self.objects_under_the_click_list:
  5681. self.collection.set_inactive(name_sel_obj)
  5682. name_sel_obj = self.objects_under_the_click_list[0]
  5683. self.collection.set_active(name_sel_obj)
  5684. else:
  5685. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5686. self.collection.set_all_inactive()
  5687. self.collection.set_active(
  5688. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5689. curr_sel_obj = self.collection.get_active()
  5690. # delete the possible selection box around a possible selected object
  5691. self.delete_selection_shape()
  5692. curr_sel_obj.selection_shape_drawn = False
  5693. # create the selection box around the selected object
  5694. if self.defaults['global_selection_shape'] is True:
  5695. self.draw_selection_shape(curr_sel_obj)
  5696. curr_sel_obj.selection_shape_drawn = True
  5697. self.selected_message(curr_sel_obj=curr_sel_obj)
  5698. else:
  5699. # deselect everything
  5700. self.on_objects_selection(False)
  5701. # delete the possible selection box around a possible selected object
  5702. self.delete_selection_shape()
  5703. for o in self.collection.get_list():
  5704. o.selection_shape_drawn = False
  5705. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5706. # only when working on App
  5707. if self.call_source == 'app':
  5708. if self.click_noproject is False:
  5709. # if the Tool Tab is in focus don't change focus to Project Tab
  5710. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5711. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5712. else:
  5713. # restore auto open the Project Tab
  5714. self.click_noproject = False
  5715. # delete any text in the status bar, implicitly the last object name that was selected
  5716. # self.inform.emit("")
  5717. else:
  5718. self.call_source = 'app'
  5719. except Exception as e:
  5720. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5721. def selected_message(self, curr_sel_obj):
  5722. if curr_sel_obj:
  5723. if curr_sel_obj.kind == 'gerber':
  5724. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5725. color='green',
  5726. name=str(curr_sel_obj.options['name']),
  5727. tx=_("selected"))
  5728. )
  5729. elif curr_sel_obj.kind == 'excellon':
  5730. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5731. color='brown',
  5732. name=str(curr_sel_obj.options['name']),
  5733. tx=_("selected"))
  5734. )
  5735. elif curr_sel_obj.kind == 'cncjob':
  5736. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5737. color='blue',
  5738. name=str(curr_sel_obj.options['name']),
  5739. tx=_("selected"))
  5740. )
  5741. elif curr_sel_obj.kind == 'geometry':
  5742. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5743. color='red',
  5744. name=str(curr_sel_obj.options['name']),
  5745. tx=_("selected"))
  5746. )
  5747. def delete_hover_shape(self):
  5748. self.hover_shapes.clear()
  5749. self.hover_shapes.redraw()
  5750. def draw_hover_shape(self, sel_obj, color=None):
  5751. """
  5752. :param sel_obj: The object for which the hover shape must be drawn
  5753. :param color: The color of the hover shape
  5754. :return: None
  5755. """
  5756. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5757. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5758. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5759. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5760. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5761. if self.defaults['units'].upper() == 'MM':
  5762. hover_rect = hover_rect.buffer(-0.1)
  5763. hover_rect = hover_rect.buffer(0.2)
  5764. else:
  5765. hover_rect = hover_rect.buffer(-0.00393)
  5766. hover_rect = hover_rect.buffer(0.00787)
  5767. # if color:
  5768. # face = Color(color)
  5769. # face.alpha = 0.2
  5770. # outline = Color(color, alpha=0.8)
  5771. # else:
  5772. # face = Color(self.defaults['global_sel_fill'])
  5773. # face.alpha = 0.2
  5774. # outline = self.defaults['global_sel_line']
  5775. if color:
  5776. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5777. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5778. else:
  5779. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5780. outline = self.defaults['global_sel_line']
  5781. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5782. if self.is_legacy is True:
  5783. self.hover_shapes.redraw()
  5784. def delete_selection_shape(self):
  5785. self.move_tool.sel_shapes.clear()
  5786. self.move_tool.sel_shapes.redraw()
  5787. def draw_selection_shape(self, sel_obj, color=None):
  5788. """
  5789. Will draw a selection shape around the selected object.
  5790. :param sel_obj: The object for which the selection shape must be drawn
  5791. :param color: The color for the selection shape.
  5792. :return: None
  5793. """
  5794. if sel_obj is None:
  5795. return
  5796. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5797. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5798. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5799. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5800. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5801. if self.defaults['units'].upper() == 'MM':
  5802. sel_rect = sel_rect.buffer(-0.1)
  5803. sel_rect = sel_rect.buffer(0.2)
  5804. else:
  5805. sel_rect = sel_rect.buffer(-0.00393)
  5806. sel_rect = sel_rect.buffer(0.00787)
  5807. if color:
  5808. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5809. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5810. else:
  5811. if self.is_legacy is False:
  5812. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5813. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5814. else:
  5815. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5816. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5817. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5818. color=outline,
  5819. face_color=face,
  5820. update=True,
  5821. layer=0,
  5822. tolerance=None))
  5823. if self.is_legacy is True:
  5824. self.move_tool.sel_shapes.redraw()
  5825. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5826. """
  5827. Will draw a selection shape when dragging mouse on canvas.
  5828. :param old_coords: Old coordinates
  5829. :param coords: New coordinates
  5830. :param kwargs: Keyword arguments
  5831. :return:
  5832. """
  5833. if 'color' in kwargs:
  5834. color = kwargs['color']
  5835. else:
  5836. color = self.defaults['global_sel_line']
  5837. if 'face_color' in kwargs:
  5838. face_color = kwargs['face_color']
  5839. else:
  5840. face_color = self.defaults['global_sel_fill']
  5841. if 'face_alpha' in kwargs:
  5842. face_alpha = kwargs['face_alpha']
  5843. else:
  5844. face_alpha = 0.3
  5845. x0, y0 = old_coords
  5846. x1, y1 = coords
  5847. pt1 = (x0, y0)
  5848. pt2 = (x1, y0)
  5849. pt3 = (x1, y1)
  5850. pt4 = (x0, y1)
  5851. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5852. # color_t = Color(face_color)
  5853. # color_t.alpha = face_alpha
  5854. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5855. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5856. layer=0, tolerance=None)
  5857. if self.is_legacy is True:
  5858. self.move_tool.sel_shapes.redraw()
  5859. def on_file_new_click(self):
  5860. """
  5861. Callback for menu item File -> New.
  5862. Executed on clicking the Menu -> File -> New Project
  5863. :return:
  5864. """
  5865. if self.collection.get_list() and self.should_we_save:
  5866. msgbox = QtWidgets.QMessageBox()
  5867. # msgbox.setText("<B>Save changes ...</B>")
  5868. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5869. "Creating a New project will delete them.\n"
  5870. "Do you want to Save the project?"))
  5871. msgbox.setWindowTitle(_("Save changes"))
  5872. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5873. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5874. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5875. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5876. msgbox.setDefaultButton(bt_yes)
  5877. msgbox.exec_()
  5878. response = msgbox.clickedButton()
  5879. if response == bt_yes:
  5880. self.on_file_saveprojectas()
  5881. elif response == bt_cancel:
  5882. return
  5883. elif response == bt_no:
  5884. self.on_file_new()
  5885. else:
  5886. self.on_file_new()
  5887. self.inform.emit('[success] %s...' % _("New Project created"))
  5888. def on_file_new(self, cli=None):
  5889. """
  5890. Returns the application to its startup state. This method is thread-safe.
  5891. :param cli: Boolean. If True this method was run from command line
  5892. :return: None
  5893. """
  5894. self.defaults.report_usage("on_file_new")
  5895. # Remove everything from memory
  5896. App.log.debug("on_file_new()")
  5897. # close any editor that might be open
  5898. if self.call_source != 'app':
  5899. self.editor2object(cleanup=True)
  5900. # ## EDITOR section
  5901. self.geo_editor = FlatCAMGeoEditor(self)
  5902. self.exc_editor = FlatCAMExcEditor(self)
  5903. self.grb_editor = FlatCAMGrbEditor(self)
  5904. # Clear pool
  5905. self.clear_pool()
  5906. for obj in self.collection.get_list():
  5907. # delete shapes left drawn from mark shape_collections, if any
  5908. if isinstance(obj, GerberObject):
  5909. try:
  5910. for el in obj.mark_shapes:
  5911. obj.mark_shapes[el].clear(update=True)
  5912. obj.mark_shapes[el].enabled = False
  5913. del el
  5914. except AttributeError:
  5915. pass
  5916. # also delete annotation shapes, if any
  5917. elif isinstance(obj, CNCJobObject):
  5918. try:
  5919. obj.text_col.enabled = False
  5920. del obj.text_col
  5921. obj.annotation.clear(update=True)
  5922. del obj.annotation
  5923. except AttributeError:
  5924. pass
  5925. # delete the exclusion areas
  5926. self.exc_areas.clear_shapes()
  5927. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5928. self.shell.init_tcl()
  5929. # delete any selection shape on canvas
  5930. self.delete_selection_shape()
  5931. # delete all FlatCAM objects
  5932. self.collection.delete_all()
  5933. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5934. self.setup_component_editor()
  5935. # Clear project filename
  5936. self.project_filename = None
  5937. # Load the application defaults
  5938. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5939. # Re-fresh project options
  5940. self.on_options_app2project()
  5941. # Init FlatCAMTools
  5942. self.init_tools()
  5943. # Try to close all tabs in the PlotArea but only if the GUI is active (CLI is None)
  5944. if cli is None:
  5945. # we need to go in reverse because once we remove a tab then the index changes
  5946. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5947. # and so on. Therefore the deletion should be done in reverse
  5948. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5949. for index in range(wdg_count, -1, -1):
  5950. try:
  5951. self.ui.plot_tab_area.closeTab(index)
  5952. except Exception as e:
  5953. log.debug("App.on_file_new() --> %s" % str(e))
  5954. # # And then add again the Plot Area
  5955. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5956. self.ui.plot_tab_area.protectTab(0)
  5957. # take the focus of the Notebook on Project Tab.
  5958. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5959. self.set_ui_title(name=_("New Project - Not saved"))
  5960. def obj_properties(self):
  5961. """
  5962. Will launch the object Properties Tool
  5963. :return:
  5964. """
  5965. self.defaults.report_usage("obj_properties()")
  5966. self.properties_tool.run(toggle=False)
  5967. def on_project_context_save(self):
  5968. """
  5969. Wrapper, will save the object function of it's type
  5970. :return:
  5971. """
  5972. obj = self.collection.get_active()
  5973. if type(obj) == GeometryObject:
  5974. self.on_file_exportdxf()
  5975. elif type(obj) == ExcellonObject:
  5976. self.on_file_saveexcellon()
  5977. elif type(obj) == CNCJobObject:
  5978. obj.on_exportgcode_button_click()
  5979. elif type(obj) == GerberObject:
  5980. self.on_file_savegerber()
  5981. elif type(obj) == ScriptObject:
  5982. self.on_file_savescript()
  5983. elif type(obj) == DocumentObject:
  5984. self.on_file_savedocument()
  5985. def obj_move(self):
  5986. """
  5987. Callback for the Move menu entry in various Context Menu's.
  5988. :return:
  5989. """
  5990. self.defaults.report_usage("obj_move()")
  5991. self.move_tool.run(toggle=False)
  5992. def on_fileopengerber(self, signal, name=None):
  5993. """
  5994. File menu callback for opening a Gerber.
  5995. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5996. :param name:
  5997. :return: None
  5998. """
  5999. self.defaults.report_usage("on_fileopengerber")
  6000. App.log.debug("on_fileopengerber()")
  6001. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6002. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6003. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6004. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6005. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6006. "*.mil);;" \
  6007. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6008. "Allegro Files (*.art);;" \
  6009. "Mentor Files (*.pho *.gdo);;" \
  6010. "All Files (*.*)"
  6011. if name is None:
  6012. try:
  6013. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6014. directory=self.get_last_folder(),
  6015. filter=_filter_)
  6016. except TypeError:
  6017. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6018. filenames = [str(filename) for filename in filenames]
  6019. else:
  6020. filenames = [name]
  6021. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6022. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6023. _("Opening Gerber file.")),
  6024. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6025. color=QtGui.QColor("gray"))
  6026. if len(filenames) == 0:
  6027. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6028. else:
  6029. for filename in filenames:
  6030. if filename != '':
  6031. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6032. def on_fileopenexcellon(self, signal, name=None):
  6033. """
  6034. File menu callback for opening an Excellon file.
  6035. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6036. :param name:
  6037. :return: None
  6038. """
  6039. self.defaults.report_usage("on_fileopenexcellon")
  6040. App.log.debug("on_fileopenexcellon()")
  6041. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6042. "All Files (*.*)"
  6043. if name is None:
  6044. try:
  6045. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6046. directory=self.get_last_folder(),
  6047. filter=_filter_)
  6048. except TypeError:
  6049. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6050. filenames = [str(filename) for filename in filenames]
  6051. else:
  6052. filenames = [str(name)]
  6053. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6054. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6055. _("Opening Excellon file.")),
  6056. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6057. color=QtGui.QColor("gray"))
  6058. if len(filenames) == 0:
  6059. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6060. else:
  6061. for filename in filenames:
  6062. if filename != '':
  6063. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6064. def on_fileopengcode(self, signal, name=None):
  6065. """
  6066. File menu call back for opening gcode.
  6067. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6068. :param name:
  6069. :return:
  6070. """
  6071. self.defaults.report_usage("on_fileopengcode")
  6072. App.log.debug("on_fileopengcode()")
  6073. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6074. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6075. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6076. "All Files (*.*)"
  6077. if name is None:
  6078. try:
  6079. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6080. directory=self.get_last_folder(),
  6081. filter=_filter_)
  6082. except TypeError:
  6083. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6084. filenames = [str(filename) for filename in filenames]
  6085. else:
  6086. filenames = [name]
  6087. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6088. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6089. _("Opening G-Code file.")),
  6090. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6091. color=QtGui.QColor("gray"))
  6092. if len(filenames) == 0:
  6093. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6094. else:
  6095. for filename in filenames:
  6096. if filename != '':
  6097. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6098. def on_file_openproject(self, signal):
  6099. """
  6100. File menu callback for opening a project.
  6101. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6102. :return: None
  6103. """
  6104. self.defaults.report_usage("on_file_openproject")
  6105. App.log.debug("on_file_openproject()")
  6106. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6107. try:
  6108. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6109. directory=self.get_last_folder(), filter=_filter_)
  6110. except TypeError:
  6111. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6112. # The Qt methods above will return a QString which can cause problems later.
  6113. # So far json.dump() will fail to serialize it.
  6114. # TODO: Improve the serialization methods and remove this fix.
  6115. filename = str(filename)
  6116. if filename == "":
  6117. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6118. else:
  6119. # self.worker_task.emit({'fcn': self.open_project,
  6120. # 'params': [filename]})
  6121. # The above was failing because open_project() is not
  6122. # thread safe. The new_project()
  6123. self.open_project(filename)
  6124. def on_fileopenhpgl2(self, signal, name=None):
  6125. """
  6126. File menu callback for opening a HPGL2.
  6127. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6128. :param name:
  6129. :return: None
  6130. """
  6131. self.defaults.report_usage("on_fileopenhpgl2")
  6132. App.log.debug("on_fileopenhpgl2()")
  6133. _filter_ = "HPGL2 Files (*.plt);;" \
  6134. "All Files (*.*)"
  6135. if name is None:
  6136. try:
  6137. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6138. directory=self.get_last_folder(),
  6139. filter=_filter_)
  6140. except TypeError:
  6141. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6142. filenames = [str(filename) for filename in filenames]
  6143. else:
  6144. filenames = [name]
  6145. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6146. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6147. _("Opening HPGL2 file.")),
  6148. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6149. color=QtGui.QColor("gray"))
  6150. if len(filenames) == 0:
  6151. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6152. else:
  6153. for filename in filenames:
  6154. if filename != '':
  6155. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6156. def on_file_openconfig(self, signal):
  6157. """
  6158. File menu callback for opening a config file.
  6159. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6160. :return: None
  6161. """
  6162. self.defaults.report_usage("on_file_openconfig")
  6163. App.log.debug("on_file_openconfig()")
  6164. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6165. try:
  6166. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6167. directory=self.data_path, filter=_filter_)
  6168. except TypeError:
  6169. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6170. filter=_filter_)
  6171. if filename == "":
  6172. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6173. else:
  6174. self.open_config_file(filename)
  6175. def on_file_exportsvg(self):
  6176. """
  6177. Callback for menu item File->Export SVG.
  6178. :return: None
  6179. """
  6180. self.defaults.report_usage("on_file_exportsvg")
  6181. App.log.debug("on_file_exportsvg()")
  6182. obj = self.collection.get_active()
  6183. if obj is None:
  6184. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6185. msg = _("Please Select a Geometry object to export")
  6186. msgbox = QtWidgets.QMessageBox()
  6187. msgbox.setInformativeText(msg)
  6188. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6189. msgbox.setDefaultButton(bt_ok)
  6190. msgbox.exec_()
  6191. return
  6192. # Check for more compatible types and add as required
  6193. if (not isinstance(obj, GeometryObject)
  6194. and not isinstance(obj, GerberObject)
  6195. and not isinstance(obj, CNCJobObject)
  6196. and not isinstance(obj, ExcellonObject)):
  6197. msg = '[ERROR_NOTCL] %s' % \
  6198. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6199. msgbox = QtWidgets.QMessageBox()
  6200. msgbox.setInformativeText(msg)
  6201. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6202. msgbox.setDefaultButton(bt_ok)
  6203. msgbox.exec_()
  6204. return
  6205. name = obj.options["name"]
  6206. _filter = "SVG File (*.svg);;All Files (*.*)"
  6207. try:
  6208. filename, _f = FCFileSaveDialog.get_saved_filename(
  6209. caption=_("Export SVG"),
  6210. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6211. filter=_filter)
  6212. except TypeError:
  6213. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6214. filename = str(filename)
  6215. if filename == "":
  6216. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6217. return
  6218. else:
  6219. self.export_svg(name, filename)
  6220. if self.defaults["global_open_style"] is False:
  6221. self.file_opened.emit("SVG", filename)
  6222. self.file_saved.emit("SVG", filename)
  6223. def on_file_exportpng(self):
  6224. self.defaults.report_usage("on_file_exportpng")
  6225. App.log.debug("on_file_exportpng()")
  6226. self.date = str(datetime.today()).rpartition('.')[0]
  6227. self.date = ''.join(c for c in self.date if c not in ':-')
  6228. self.date = self.date.replace(' ', '_')
  6229. if self.is_legacy is False:
  6230. image = _screenshot()
  6231. data = np.asarray(image)
  6232. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6233. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6234. return
  6235. filter_ = "PNG File (*.png);;All Files (*.*)"
  6236. try:
  6237. filename, _f = FCFileSaveDialog.get_saved_filename(
  6238. caption=_("Export PNG Image"),
  6239. directory=self.get_last_save_folder() + '/png_' + self.date,
  6240. filter=filter_)
  6241. except TypeError:
  6242. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6243. filename = str(filename)
  6244. if filename == "":
  6245. self.inform.emit(_("Cancelled."))
  6246. return
  6247. else:
  6248. if self.is_legacy is False:
  6249. write_png(filename, data)
  6250. else:
  6251. self.plotcanvas.figure.savefig(filename)
  6252. if self.defaults["global_open_style"] is False:
  6253. self.file_opened.emit("png", filename)
  6254. self.file_saved.emit("png", filename)
  6255. def on_file_savegerber(self):
  6256. """
  6257. Callback for menu item in Project context menu.
  6258. :return: None
  6259. """
  6260. self.defaults.report_usage("on_file_savegerber")
  6261. App.log.debug("on_file_savegerber()")
  6262. obj = self.collection.get_active()
  6263. if obj is None:
  6264. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6265. return
  6266. # Check for more compatible types and add as required
  6267. if not isinstance(obj, GerberObject):
  6268. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6269. return
  6270. name = self.collection.get_active().options["name"]
  6271. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6272. try:
  6273. filename, _f = FCFileSaveDialog.get_saved_filename(
  6274. caption="Save Gerber source file",
  6275. directory=self.get_last_save_folder() + '/' + name,
  6276. filter=_filter)
  6277. except TypeError:
  6278. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6279. filename = str(filename)
  6280. if filename == "":
  6281. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6282. return
  6283. else:
  6284. self.save_source_file(name, filename)
  6285. if self.defaults["global_open_style"] is False:
  6286. self.file_opened.emit("Gerber", filename)
  6287. self.file_saved.emit("Gerber", filename)
  6288. def on_file_savescript(self):
  6289. """
  6290. Callback for menu item in Project context menu.
  6291. :return: None
  6292. """
  6293. self.defaults.report_usage("on_file_savescript")
  6294. App.log.debug("on_file_savescript()")
  6295. obj = self.collection.get_active()
  6296. if obj is None:
  6297. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6298. return
  6299. # Check for more compatible types and add as required
  6300. if not isinstance(obj, ScriptObject):
  6301. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6302. return
  6303. name = self.collection.get_active().options["name"]
  6304. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6305. try:
  6306. filename, _f = FCFileSaveDialog.get_saved_filename(
  6307. caption="Save Script source file",
  6308. directory=self.get_last_save_folder() + '/' + name,
  6309. filter=_filter)
  6310. except TypeError:
  6311. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6312. filename = str(filename)
  6313. if filename == "":
  6314. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6315. return
  6316. else:
  6317. self.save_source_file(name, filename)
  6318. if self.defaults["global_open_style"] is False:
  6319. self.file_opened.emit("Script", filename)
  6320. self.file_saved.emit("Script", filename)
  6321. def on_file_savedocument(self):
  6322. """
  6323. Callback for menu item in Project context menu.
  6324. :return: None
  6325. """
  6326. self.defaults.report_usage("on_file_savedocument")
  6327. App.log.debug("on_file_savedocument()")
  6328. obj = self.collection.get_active()
  6329. if obj is None:
  6330. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6331. return
  6332. # Check for more compatible types and add as required
  6333. if not isinstance(obj, ScriptObject):
  6334. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6335. return
  6336. name = self.collection.get_active().options["name"]
  6337. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6338. try:
  6339. filename, _f = FCFileSaveDialog.get_saved_filename(
  6340. caption="Save Document source file",
  6341. directory=self.get_last_save_folder() + '/' + name,
  6342. filter=_filter)
  6343. except TypeError:
  6344. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6345. filename = str(filename)
  6346. if filename == "":
  6347. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6348. return
  6349. else:
  6350. self.save_source_file(name, filename)
  6351. if self.defaults["global_open_style"] is False:
  6352. self.file_opened.emit("Document", filename)
  6353. self.file_saved.emit("Document", filename)
  6354. def on_file_saveexcellon(self):
  6355. """
  6356. Callback for menu item in project context menu.
  6357. :return: None
  6358. """
  6359. self.defaults.report_usage("on_file_saveexcellon")
  6360. App.log.debug("on_file_saveexcellon()")
  6361. obj = self.collection.get_active()
  6362. if obj is None:
  6363. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6364. return
  6365. # Check for more compatible types and add as required
  6366. if not isinstance(obj, ExcellonObject):
  6367. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6368. return
  6369. name = self.collection.get_active().options["name"]
  6370. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6371. try:
  6372. filename, _f = FCFileSaveDialog.get_saved_filename(
  6373. caption=_("Save Excellon source file"),
  6374. directory=self.get_last_save_folder() + '/' + name,
  6375. filter=_filter)
  6376. except TypeError:
  6377. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6378. filename = str(filename)
  6379. if filename == "":
  6380. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6381. return
  6382. else:
  6383. self.save_source_file(name, filename)
  6384. if self.defaults["global_open_style"] is False:
  6385. self.file_opened.emit("Excellon", filename)
  6386. self.file_saved.emit("Excellon", filename)
  6387. def on_file_exportexcellon(self):
  6388. """
  6389. Callback for menu item File->Export->Excellon.
  6390. :return: None
  6391. """
  6392. self.defaults.report_usage("on_file_exportexcellon")
  6393. App.log.debug("on_file_exportexcellon()")
  6394. obj = self.collection.get_active()
  6395. if obj is None:
  6396. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6397. return
  6398. # Check for more compatible types and add as required
  6399. if not isinstance(obj, ExcellonObject):
  6400. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6401. return
  6402. name = self.collection.get_active().options["name"]
  6403. _filter = self.defaults["excellon_save_filters"]
  6404. try:
  6405. filename, _f = FCFileSaveDialog.get_saved_filename(
  6406. caption=_("Export Excellon"),
  6407. directory=self.get_last_save_folder() + '/' + name,
  6408. filter=_filter)
  6409. except TypeError:
  6410. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6411. filename = str(filename)
  6412. if filename == "":
  6413. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6414. return
  6415. else:
  6416. used_extension = filename.rpartition('.')[2]
  6417. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6418. self.export_excellon(name, filename)
  6419. if self.defaults["global_open_style"] is False:
  6420. self.file_opened.emit("Excellon", filename)
  6421. self.file_saved.emit("Excellon", filename)
  6422. def on_file_exportgerber(self):
  6423. """
  6424. Callback for menu item File->Export->Gerber.
  6425. :return: None
  6426. """
  6427. self.defaults.report_usage("on_file_exportgerber")
  6428. App.log.debug("on_file_exportgerber()")
  6429. obj = self.collection.get_active()
  6430. if obj is None:
  6431. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6432. return
  6433. # Check for more compatible types and add as required
  6434. if not isinstance(obj, GerberObject):
  6435. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6436. return
  6437. name = self.collection.get_active().options["name"]
  6438. _filter_ = self.defaults['gerber_save_filters']
  6439. try:
  6440. filename, _f = FCFileSaveDialog.get_saved_filename(
  6441. caption=_("Export Gerber"),
  6442. directory=self.get_last_save_folder() + '/' + name,
  6443. filter=_filter_)
  6444. except TypeError:
  6445. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6446. filename = str(filename)
  6447. if filename == "":
  6448. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6449. return
  6450. else:
  6451. used_extension = filename.rpartition('.')[2]
  6452. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6453. self.export_gerber(name, filename)
  6454. if self.defaults["global_open_style"] is False:
  6455. self.file_opened.emit("Gerber", filename)
  6456. self.file_saved.emit("Gerber", filename)
  6457. def on_file_exportdxf(self):
  6458. """
  6459. Callback for menu item File->Export DXF.
  6460. :return: None
  6461. """
  6462. self.defaults.report_usage("on_file_exportdxf")
  6463. App.log.debug("on_file_exportdxf()")
  6464. obj = self.collection.get_active()
  6465. if obj is None:
  6466. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6467. msg = _("Please Select a Geometry object to export")
  6468. msgbox = QtWidgets.QMessageBox()
  6469. msgbox.setInformativeText(msg)
  6470. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6471. msgbox.setDefaultButton(bt_ok)
  6472. msgbox.exec_()
  6473. return
  6474. # Check for more compatible types and add as required
  6475. if not isinstance(obj, GeometryObject):
  6476. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6477. msgbox = QtWidgets.QMessageBox()
  6478. msgbox.setInformativeText(msg)
  6479. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6480. msgbox.setDefaultButton(bt_ok)
  6481. msgbox.exec_()
  6482. return
  6483. name = self.collection.get_active().options["name"]
  6484. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6485. try:
  6486. filename, _f = FCFileSaveDialog.get_saved_filename(
  6487. caption=_("Export DXF"),
  6488. directory=self.get_last_save_folder() + '/' + name,
  6489. filter=_filter_)
  6490. except TypeError:
  6491. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6492. filename = str(filename)
  6493. if filename == "":
  6494. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6495. return
  6496. else:
  6497. self.export_dxf(name, filename)
  6498. if self.defaults["global_open_style"] is False:
  6499. self.file_opened.emit("DXF", filename)
  6500. self.file_saved.emit("DXF", filename)
  6501. def on_file_importsvg(self, type_of_obj):
  6502. """
  6503. Callback for menu item File->Import SVG.
  6504. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6505. :type type_of_obj: str
  6506. :return: None
  6507. """
  6508. self.defaults.report_usage("on_file_importsvg")
  6509. App.log.debug("on_file_importsvg()")
  6510. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6511. try:
  6512. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6513. directory=self.get_last_folder(), filter=_filter_)
  6514. except TypeError:
  6515. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6516. filter=_filter_)
  6517. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6518. type_of_obj = "geometry"
  6519. filenames = [str(filename) for filename in filenames]
  6520. if len(filenames) == 0:
  6521. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6522. else:
  6523. for filename in filenames:
  6524. if filename != '':
  6525. self.worker_task.emit({'fcn': self.import_svg,
  6526. 'params': [filename, type_of_obj]})
  6527. def on_file_importdxf(self, type_of_obj):
  6528. """
  6529. Callback for menu item File->Import DXF.
  6530. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6531. :type type_of_obj: str
  6532. :return: None
  6533. """
  6534. self.defaults.report_usage("on_file_importdxf")
  6535. App.log.debug("on_file_importdxf()")
  6536. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6537. try:
  6538. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6539. directory=self.get_last_folder(),
  6540. filter=_filter_)
  6541. except TypeError:
  6542. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6543. filter=_filter_)
  6544. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6545. type_of_obj = "geometry"
  6546. filenames = [str(filename) for filename in filenames]
  6547. if len(filenames) == 0:
  6548. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6549. else:
  6550. for filename in filenames:
  6551. if filename != '':
  6552. self.worker_task.emit({'fcn': self.import_dxf,
  6553. 'params': [filename, type_of_obj]})
  6554. # ###############################################################################################################
  6555. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6556. # ###############################################################################################################
  6557. def init_code_editor(self, name):
  6558. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6559. # add the tab if it was closed
  6560. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6561. self.text_editor_tab.setObjectName('text_editor_tab')
  6562. # delete the absolute and relative position and messages in the infobar
  6563. self.ui.position_label.setText("")
  6564. self.ui.rel_position_label.setText("")
  6565. # first clear previous text in text editor (if any)
  6566. self.text_editor_tab.code_editor.clear()
  6567. self.text_editor_tab.code_editor.setReadOnly(False)
  6568. self.toggle_codeeditor = True
  6569. self.text_editor_tab.code_editor.completer_enable = False
  6570. self.text_editor_tab.buttonRun.hide()
  6571. # make sure to keep a reference to the code editor
  6572. self.reference_code_editor = self.text_editor_tab.code_editor
  6573. # Switch plot_area to CNCJob tab
  6574. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6575. def on_view_source(self):
  6576. """
  6577. Called when the user wants to see the source file of the selected object
  6578. :return:
  6579. """
  6580. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6581. self.proc_container.view.set_busy(_("Loading..."))
  6582. try:
  6583. obj = self.collection.get_active()
  6584. except Exception as e:
  6585. log.debug("App.on_view_source() --> %s" % str(e))
  6586. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6587. return 'fail'
  6588. if obj is None:
  6589. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6590. return 'fail'
  6591. flt = "All Files (*.*)"
  6592. if obj.kind == 'gerber':
  6593. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6594. elif obj.kind == 'excellon':
  6595. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6596. elif obj.kind == 'cncjob':
  6597. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6598. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6599. # add the tab if it was closed
  6600. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6601. self.source_editor_tab.setObjectName('source_editor_tab')
  6602. # delete the absolute and relative position and messages in the infobar
  6603. self.ui.position_label.setText("")
  6604. self.ui.rel_position_label.setText("")
  6605. # first clear previous text in text editor (if any)
  6606. self.source_editor_tab.code_editor.clear()
  6607. self.source_editor_tab.code_editor.setReadOnly(False)
  6608. self.source_editor_tab.code_editor.completer_enable = False
  6609. self.source_editor_tab.buttonRun.hide()
  6610. # Switch plot_area to CNCJob tab
  6611. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6612. try:
  6613. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6614. except TypeError:
  6615. pass
  6616. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6617. try:
  6618. self.source_editor_tab.buttonSave.clicked.disconnect()
  6619. except TypeError:
  6620. pass
  6621. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6622. # then append the text from GCode to the text editor
  6623. if obj.kind == 'cncjob':
  6624. try:
  6625. file = obj.export_gcode(
  6626. preamble=self.defaults["cncjob_prepend"],
  6627. postamble=self.defaults["cncjob_append"],
  6628. to_file=True)
  6629. if file == 'fail':
  6630. return 'fail'
  6631. except AttributeError:
  6632. self.inform.emit('[WARNING_NOTCL] %s' %
  6633. _("There is no selected object for which to see it's source file code."))
  6634. return 'fail'
  6635. else:
  6636. try:
  6637. file = StringIO(obj.source_file)
  6638. except (AttributeError, TypeError):
  6639. self.inform.emit('[WARNING_NOTCL] %s' %
  6640. _("There is no selected object for which to see it's source file code."))
  6641. return 'fail'
  6642. self.source_editor_tab.t_frame.hide()
  6643. try:
  6644. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6645. # for line in file:
  6646. # QtWidgets.QApplication.processEvents()
  6647. # proc_line = str(line).strip('\n')
  6648. # self.source_editor_tab.code_editor.append(proc_line)
  6649. except Exception as e:
  6650. log.debug('App.on_view_source() -->%s' % str(e))
  6651. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6652. return
  6653. self.source_editor_tab.handleTextChanged()
  6654. self.source_editor_tab.t_frame.show()
  6655. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6656. self.proc_container.view.set_idle()
  6657. # self.ui.show()
  6658. def on_toggle_code_editor(self):
  6659. self.defaults.report_usage("on_toggle_code_editor()")
  6660. if self.toggle_codeeditor is False:
  6661. self.init_code_editor(name=_("Code Editor"))
  6662. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6663. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6664. self.text_editor_tab.buttonSave.clicked.disconnect()
  6665. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6666. else:
  6667. for idx in range(self.ui.plot_tab_area.count()):
  6668. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6669. self.ui.plot_tab_area.closeTab(idx)
  6670. break
  6671. self.toggle_codeeditor = False
  6672. def on_code_editor_close(self):
  6673. self.toggle_codeeditor = False
  6674. def goto_text_line(self):
  6675. """
  6676. Will scroll a text to the specified text line.
  6677. :return: None
  6678. """
  6679. dia_box = Dialog_box(title=_("Go to Line ..."),
  6680. label=_("Line:"),
  6681. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6682. initial_text='')
  6683. try:
  6684. line = int(dia_box.location) - 1
  6685. except (ValueError, TypeError):
  6686. line = 0
  6687. if dia_box.ok:
  6688. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6689. # at the top of the window
  6690. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6691. # get the document() of the TextEditor
  6692. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6693. # create a Text Cursor based on the searched line
  6694. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6695. # set cursor of the code editor with the cursor at the searcehd line
  6696. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6697. def on_filenewscript(self, silent=False):
  6698. """
  6699. Will create a new script file and open it in the Code Editor
  6700. :param silent: if True will not display status messages
  6701. :param name: if specified will be the name of the new script
  6702. :param text: pass a source file to the newly created script to be loaded in it
  6703. :return: None
  6704. """
  6705. if silent is False:
  6706. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6707. # delete the absolute and relative position and messages in the infobar
  6708. self.ui.position_label.setText("")
  6709. self.ui.rel_position_label.setText("")
  6710. self.new_script_object()
  6711. # script_text = script_obj.source_file
  6712. #
  6713. # self.proc_container.view.set_busy(_("Loading..."))
  6714. # script_obj.script_editor_tab.t_frame.hide()
  6715. #
  6716. # script_obj.script_editor_tab.t_frame.show()
  6717. # self.proc_container.view.set_idle()
  6718. def on_fileopenscript(self, name=None, silent=False):
  6719. """
  6720. Will open a Tcl script file into the Code Editor
  6721. :param silent: if True will not display status messages
  6722. :param name: name of a Tcl script file to open
  6723. :return: None
  6724. """
  6725. self.defaults.report_usage("on_fileopenscript")
  6726. App.log.debug("on_fileopenscript()")
  6727. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6728. "All Files (*.*)"
  6729. if name:
  6730. filenames = [name]
  6731. else:
  6732. try:
  6733. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6734. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6735. except TypeError:
  6736. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6737. if len(filenames) == 0:
  6738. if silent is False:
  6739. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6740. else:
  6741. for filename in filenames:
  6742. if filename != '':
  6743. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6744. def on_fileopenscript_example(self, name=None, silent=False):
  6745. """
  6746. Will open a Tcl script file into the Code Editor
  6747. :param silent: if True will not display status messages
  6748. :param name: name of a Tcl script file to open
  6749. :return:
  6750. """
  6751. self.defaults.report_usage("on_fileopenscript_example")
  6752. log.debug("on_fileopenscript_example()")
  6753. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6754. "All Files (*.*)"
  6755. # test if the app was frozen and choose the path for the configuration file
  6756. if getattr(sys, "frozen", False) is True:
  6757. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6758. else:
  6759. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6760. if name:
  6761. filenames = [name]
  6762. else:
  6763. try:
  6764. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6765. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6766. except TypeError:
  6767. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6768. if len(filenames) == 0:
  6769. if silent is False:
  6770. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6771. else:
  6772. for filename in filenames:
  6773. if filename != '':
  6774. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6775. def on_filerunscript(self, name=None, silent=False):
  6776. """
  6777. File menu callback for loading and running a TCL script.
  6778. :param silent: if True will not display status messages
  6779. :param name: name of a Tcl script file to be run by FlatCAM
  6780. :return: None
  6781. """
  6782. self.defaults.report_usage("on_filerunscript")
  6783. App.log.debug("on_file_runscript()")
  6784. if name:
  6785. filename = name
  6786. if self.cmd_line_headless != 1:
  6787. self.splash.showMessage('%s: %ssec\n%s' %
  6788. (_("Canvas initialization started.\n"
  6789. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6790. _("Executing ScriptObject file.")
  6791. ),
  6792. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6793. color=QtGui.QColor("gray"))
  6794. else:
  6795. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6796. "All Files (*.*)"
  6797. try:
  6798. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6799. directory=self.get_last_folder(), filter=_filter_)
  6800. except TypeError:
  6801. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6802. # The Qt methods above will return a QString which can cause problems later.
  6803. # So far json.dump() will fail to serialize it.
  6804. filename = str(filename)
  6805. if filename == "":
  6806. if silent is False:
  6807. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6808. else:
  6809. if self.cmd_line_headless != 1:
  6810. if self.ui.shell_dock.isHidden():
  6811. self.ui.shell_dock.show()
  6812. try:
  6813. with open(filename, "r") as tcl_script:
  6814. cmd_line_shellfile_content = tcl_script.read()
  6815. if self.cmd_line_headless != 1:
  6816. self.shell.exec_command(cmd_line_shellfile_content)
  6817. else:
  6818. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6819. if silent is False:
  6820. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6821. except Exception as e:
  6822. log.debug("App.on_filerunscript() -> %s" % str(e))
  6823. sys.exit(2)
  6824. def on_file_saveproject(self, silent=False):
  6825. """
  6826. Callback for menu item File->Save Project. Saves the project to
  6827. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6828. if set to None. The project is saved by calling ``self.save_project()``.
  6829. :param silent: if True will not display status messages
  6830. :return: None
  6831. """
  6832. self.defaults.report_usage("on_file_saveproject")
  6833. if self.project_filename is None:
  6834. self.on_file_saveprojectas()
  6835. else:
  6836. self.worker_task.emit({'fcn': self.save_project,
  6837. 'params': [self.project_filename, silent]})
  6838. if self.defaults["global_open_style"] is False:
  6839. self.file_opened.emit("project", self.project_filename)
  6840. self.file_saved.emit("project", self.project_filename)
  6841. self.set_ui_title(name=self.project_filename)
  6842. self.should_we_save = False
  6843. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6844. """
  6845. Callback for menu item File->Save Project As... Opens a file
  6846. chooser and saves the project to the given file via
  6847. ``self.save_project()``.
  6848. :param make_copy if to be create a copy of the project; boolean
  6849. :param use_thread: if to be run in a separate thread; boolean
  6850. :param quit_action: if to be followed by quiting the application; boolean
  6851. :return: None
  6852. """
  6853. self.defaults.report_usage("on_file_saveprojectas")
  6854. self.date = str(datetime.today()).rpartition('.')[0]
  6855. self.date = ''.join(c for c in self.date if c not in ':-')
  6856. self.date = self.date.replace(' ', '_')
  6857. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6858. try:
  6859. filename, _f = FCFileSaveDialog.get_saved_filename(
  6860. caption=_("Save Project As ..."),
  6861. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6862. proj=_("Project")),
  6863. filter=filter_
  6864. )
  6865. except TypeError:
  6866. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6867. filename = str(filename)
  6868. if filename == '':
  6869. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6870. return
  6871. if use_thread is True:
  6872. self.worker_task.emit({'fcn': self.save_project,
  6873. 'params': [filename, quit_action]})
  6874. else:
  6875. self.save_project(filename, quit_action)
  6876. # self.save_project(filename)
  6877. if self.defaults["global_open_style"] is False:
  6878. self.file_opened.emit("project", filename)
  6879. self.file_saved.emit("project", filename)
  6880. if not make_copy:
  6881. self.project_filename = filename
  6882. self.set_ui_title(name=self.project_filename)
  6883. self.should_we_save = False
  6884. def on_file_save_objects_pdf(self, use_thread=True):
  6885. self.date = str(datetime.today()).rpartition('.')[0]
  6886. self.date = ''.join(c for c in self.date if c not in ':-')
  6887. self.date = self.date.replace(' ', '_')
  6888. try:
  6889. obj_selection = self.collection.get_selected()
  6890. if len(obj_selection) == 1:
  6891. obj_name = str(obj_selection[0].options['name'])
  6892. else:
  6893. obj_name = _("FlatCAM objects print")
  6894. except AttributeError as err:
  6895. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6896. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6897. return
  6898. if not obj_selection:
  6899. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6900. return
  6901. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6902. try:
  6903. filename, _f = FCFileSaveDialog.get_saved_filename(
  6904. caption=_("Save Object as PDF ..."),
  6905. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6906. obj_name=obj_name,
  6907. date=self.date),
  6908. filter=filter_
  6909. )
  6910. except TypeError:
  6911. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  6912. filename = str(filename)
  6913. if filename == '':
  6914. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6915. return
  6916. if use_thread is True:
  6917. self.proc_container.new(_("Printing PDF ... Please wait."))
  6918. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6919. else:
  6920. self.save_pdf(filename, obj_selection)
  6921. # self.save_project(filename)
  6922. if self.defaults["global_open_style"] is False:
  6923. self.file_opened.emit("pdf", filename)
  6924. self.file_saved.emit("pdf", filename)
  6925. def save_pdf(self, file_name, obj_selection):
  6926. p_size = self.defaults['global_workspaceT']
  6927. orientation = self.defaults['global_workspace_orientation']
  6928. color = 'black'
  6929. transparency_level = 1.0
  6930. self.pagesize = {}
  6931. self.pagesize.update(
  6932. {
  6933. 'Bounds': None,
  6934. 'A0': (841 * mm, 1189 * mm),
  6935. 'A1': (594 * mm, 841 * mm),
  6936. 'A2': (420 * mm, 594 * mm),
  6937. 'A3': (297 * mm, 420 * mm),
  6938. 'A4': (210 * mm, 297 * mm),
  6939. 'A5': (148 * mm, 210 * mm),
  6940. 'A6': (105 * mm, 148 * mm),
  6941. 'A7': (74 * mm, 105 * mm),
  6942. 'A8': (52 * mm, 74 * mm),
  6943. 'A9': (37 * mm, 52 * mm),
  6944. 'A10': (26 * mm, 37 * mm),
  6945. 'B0': (1000 * mm, 1414 * mm),
  6946. 'B1': (707 * mm, 1000 * mm),
  6947. 'B2': (500 * mm, 707 * mm),
  6948. 'B3': (353 * mm, 500 * mm),
  6949. 'B4': (250 * mm, 353 * mm),
  6950. 'B5': (176 * mm, 250 * mm),
  6951. 'B6': (125 * mm, 176 * mm),
  6952. 'B7': (88 * mm, 125 * mm),
  6953. 'B8': (62 * mm, 88 * mm),
  6954. 'B9': (44 * mm, 62 * mm),
  6955. 'B10': (31 * mm, 44 * mm),
  6956. 'C0': (917 * mm, 1297 * mm),
  6957. 'C1': (648 * mm, 917 * mm),
  6958. 'C2': (458 * mm, 648 * mm),
  6959. 'C3': (324 * mm, 458 * mm),
  6960. 'C4': (229 * mm, 324 * mm),
  6961. 'C5': (162 * mm, 229 * mm),
  6962. 'C6': (114 * mm, 162 * mm),
  6963. 'C7': (81 * mm, 114 * mm),
  6964. 'C8': (57 * mm, 81 * mm),
  6965. 'C9': (40 * mm, 57 * mm),
  6966. 'C10': (28 * mm, 40 * mm),
  6967. # American paper sizes
  6968. 'LETTER': (8.5 * inch, 11 * inch),
  6969. 'LEGAL': (8.5 * inch, 14 * inch),
  6970. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6971. # From https://en.wikipedia.org/wiki/Paper_size
  6972. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6973. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6974. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6975. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6976. 'LEDGER': (17 * inch, 11 * inch),
  6977. }
  6978. )
  6979. exported_svg = []
  6980. for obj in obj_selection:
  6981. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6982. scale_factor_x=None, scale_factor_y=None,
  6983. skew_factor_x=None, skew_factor_y=None,
  6984. mirror=None)
  6985. if obj.kind.lower() == 'gerber':
  6986. # color = self.defaults["gerber_plot_fill"][:-2]
  6987. color = obj.fill_color[:-2]
  6988. elif obj.kind.lower() == 'excellon':
  6989. color = '#C40000'
  6990. elif obj.kind.lower() == 'geometry':
  6991. color = self.defaults["global_draw_color"]
  6992. # Change the attributes of the exported SVG
  6993. # We don't need stroke-width
  6994. # We set opacity to maximum
  6995. # We set the colour to WHITE
  6996. root = ET.fromstring(svg_obj)
  6997. for child in root:
  6998. child.set('fill', str(color))
  6999. child.set('opacity', str(transparency_level))
  7000. child.set('stroke', str(color))
  7001. exported_svg.append(ET.tostring(root))
  7002. xmin = Inf
  7003. ymin = Inf
  7004. xmax = -Inf
  7005. ymax = -Inf
  7006. for obj in obj_selection:
  7007. try:
  7008. gxmin, gymin, gxmax, gymax = obj.bounds()
  7009. xmin = min([xmin, gxmin])
  7010. ymin = min([ymin, gymin])
  7011. xmax = max([xmax, gxmax])
  7012. ymax = max([ymax, gymax])
  7013. except Exception as e:
  7014. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7015. # Determine bounding area for svg export
  7016. bounds = [xmin, ymin, xmax, ymax]
  7017. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7018. # This contain the measure units
  7019. uom = obj_selection[0].units.lower()
  7020. # Define a boundary around SVG of about 1.0mm (~39mils)
  7021. if uom in "mm":
  7022. boundary = 1.0
  7023. else:
  7024. boundary = 0.0393701
  7025. # Convert everything to strings for use in the xml doc
  7026. svgwidth = str(size[0] + (2 * boundary))
  7027. svgheight = str(size[1] + (2 * boundary))
  7028. minx = str(bounds[0] - boundary)
  7029. miny = str(bounds[1] + boundary + size[1])
  7030. # Add a SVG Header and footer to the svg output from shapely
  7031. # The transform flips the Y Axis so that everything renders
  7032. # properly within svg apps such as inkscape
  7033. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7034. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7035. svg_header += 'width="' + svgwidth + uom + '" '
  7036. svg_header += 'height="' + svgheight + uom + '" '
  7037. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7038. svg_header += '>'
  7039. svg_header += '<g transform="scale(1,-1)">'
  7040. svg_footer = '</g> </svg>'
  7041. svg_elem = str(svg_header)
  7042. for svg_item in exported_svg:
  7043. svg_elem += str(svg_item)
  7044. svg_elem += str(svg_footer)
  7045. # Parse the xml through a xml parser just to add line feeds
  7046. # and to make it look more pretty for the output
  7047. doc = parse_xml_string(svg_elem)
  7048. doc_final = doc.toprettyxml()
  7049. try:
  7050. if self.defaults['units'].upper() == 'IN':
  7051. unit = inch
  7052. else:
  7053. unit = mm
  7054. doc_final = StringIO(doc_final)
  7055. drawing = svg2rlg(doc_final)
  7056. if p_size == 'Bounds':
  7057. renderPDF.drawToFile(drawing, file_name)
  7058. else:
  7059. if orientation == 'p':
  7060. page_size = portrait(self.pagesize[p_size])
  7061. else:
  7062. page_size = landscape(self.pagesize[p_size])
  7063. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7064. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7065. renderPDF.draw(drawing, my_canvas, 0, 0)
  7066. my_canvas.save()
  7067. except Exception as e:
  7068. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7069. return 'fail'
  7070. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7071. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7072. """
  7073. Exports a Geometry Object to an SVG file.
  7074. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7075. :param filename: Path to the SVG file to save to.
  7076. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7077. :return:
  7078. """
  7079. self.defaults.report_usage("export_svg()")
  7080. if filename is None:
  7081. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7082. is not None else self.defaults["global_last_folder"]
  7083. self.log.debug("export_svg()")
  7084. try:
  7085. obj = self.collection.get_by_name(str(obj_name))
  7086. except Exception:
  7087. # TODO: The return behavior has not been established... should raise exception?
  7088. return "Could not retrieve object: %s" % obj_name
  7089. with self.proc_container.new(_("Exporting SVG")) as proc:
  7090. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7091. # Determine bounding area for svg export
  7092. bounds = obj.bounds()
  7093. size = obj.size()
  7094. # Convert everything to strings for use in the xml doc
  7095. svgwidth = str(size[0])
  7096. svgheight = str(size[1])
  7097. minx = str(bounds[0])
  7098. miny = str(bounds[1] - size[1])
  7099. uom = obj.units.lower()
  7100. # Add a SVG Header and footer to the svg output from shapely
  7101. # The transform flips the Y Axis so that everything renders
  7102. # properly within svg apps such as inkscape
  7103. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7104. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7105. svg_header += 'width="' + svgwidth + uom + '" '
  7106. svg_header += 'height="' + svgheight + uom + '" '
  7107. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7108. svg_header += '<g transform="scale(1,-1)">'
  7109. svg_footer = '</g> </svg>'
  7110. svg_elem = svg_header + exported_svg + svg_footer
  7111. # Parse the xml through a xml parser just to add line feeds
  7112. # and to make it look more pretty for the output
  7113. svgcode = parse_xml_string(svg_elem)
  7114. svgcode = svgcode.toprettyxml()
  7115. try:
  7116. with open(filename, 'w') as fp:
  7117. fp.write(svgcode)
  7118. except PermissionError:
  7119. self.inform.emit('[WARNING] %s' %
  7120. _("Permission denied, saving not possible.\n"
  7121. "Most likely another app is holding the file open and not accessible."))
  7122. return 'fail'
  7123. if self.defaults["global_open_style"] is False:
  7124. self.file_opened.emit("SVG", filename)
  7125. self.file_saved.emit("SVG", filename)
  7126. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7127. def save_source_file(self, obj_name, filename, use_thread=True):
  7128. """
  7129. Exports a FlatCAM Object to an Gerber/Excellon file.
  7130. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7131. :param filename: Path to the Gerber file to save to.
  7132. :param use_thread: if to be run in a separate thread
  7133. :return:
  7134. """
  7135. self.defaults.report_usage("save source file()")
  7136. if filename is None:
  7137. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7138. is not None else self.defaults["global_last_folder"]
  7139. self.log.debug("save source file()")
  7140. obj = self.collection.get_by_name(obj_name)
  7141. file_string = StringIO(obj.source_file)
  7142. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7143. if file_string.getvalue() == '':
  7144. self.inform.emit('[ERROR_NOTCL] %s' %
  7145. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7146. return 'fail'
  7147. try:
  7148. with open(filename, 'w') as file:
  7149. file.writelines('G04*\n')
  7150. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7151. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7152. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7153. file.writelines('G04 Created on : %s*\n' % time_string)
  7154. for line in file_string:
  7155. file.writelines(line)
  7156. except PermissionError:
  7157. self.inform.emit('[WARNING] %s' %
  7158. _("Permission denied, saving not possible.\n"
  7159. "Most likely another app is holding the file open and not accessible."))
  7160. return 'fail'
  7161. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7162. """
  7163. Exports a Excellon Object to an Excellon file.
  7164. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7165. :param filename: Path to the Excellon file to save to.
  7166. :param local_use:
  7167. :param use_thread: if to be run in a separate thread
  7168. :return:
  7169. """
  7170. self.defaults.report_usage("export_excellon()")
  7171. if filename is None:
  7172. if self.defaults["global_last_save_folder"]:
  7173. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7174. else:
  7175. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7176. self.log.debug("export_excellon()")
  7177. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7178. self.defaults["excellon_exp_decimals"]
  7179. )
  7180. if local_use is None:
  7181. try:
  7182. obj = self.collection.get_by_name(str(obj_name))
  7183. except Exception:
  7184. return "Could not retrieve object: %s" % obj_name
  7185. else:
  7186. obj = local_use
  7187. if not isinstance(obj, ExcellonObject):
  7188. self.inform.emit('[ERROR_NOTCL] %s' %
  7189. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7190. return
  7191. # updated units
  7192. eunits = self.defaults["excellon_exp_units"]
  7193. ewhole = self.defaults["excellon_exp_integer"]
  7194. efract = self.defaults["excellon_exp_decimals"]
  7195. ezeros = self.defaults["excellon_exp_zeros"]
  7196. eformat = self.defaults["excellon_exp_format"]
  7197. slot_type = self.defaults["excellon_exp_slot_type"]
  7198. fc_units = self.defaults['units'].upper()
  7199. if fc_units == 'MM':
  7200. factor = 1 if eunits == 'METRIC' else 0.03937
  7201. else:
  7202. factor = 25.4 if eunits == 'METRIC' else 1
  7203. def make_excellon():
  7204. try:
  7205. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7206. header = 'M48\n'
  7207. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7208. (str(self.version), str(self.version_date))
  7209. header += ';Filename: %s' % str(obj_name) + '\n'
  7210. header += ';Created on : %s' % time_str + '\n'
  7211. if eformat == 'dec':
  7212. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7213. header += eunits + '\n'
  7214. for tool in obj.tools:
  7215. if eunits == 'METRIC':
  7216. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7217. tool=str(tool),
  7218. dec=2)
  7219. else:
  7220. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7221. tool=str(tool),
  7222. dec=4)
  7223. else:
  7224. if ezeros == 'LZ':
  7225. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7226. form='ndec', e_zeros='LZ', factor=factor,
  7227. slot_type=slot_type)
  7228. header += '%s,%s\n' % (eunits, 'LZ')
  7229. header += format_exc
  7230. for tool in obj.tools:
  7231. if eunits == 'METRIC':
  7232. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7233. tool=str(tool),
  7234. dec=2)
  7235. else:
  7236. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7237. tool=str(tool),
  7238. dec=4)
  7239. else:
  7240. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7241. form='ndec', e_zeros='TZ', factor=factor,
  7242. slot_type=slot_type)
  7243. header += '%s,%s\n' % (eunits, 'TZ')
  7244. header += format_exc
  7245. for tool in obj.tools:
  7246. if eunits == 'METRIC':
  7247. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7248. tool=str(tool),
  7249. dec=2)
  7250. else:
  7251. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7252. tool=str(tool),
  7253. dec=4)
  7254. header += '%\n'
  7255. footer = 'M30\n'
  7256. exported_excellon = header
  7257. exported_excellon += excellon_code
  7258. exported_excellon += footer
  7259. if local_use is None:
  7260. try:
  7261. with open(filename, 'w') as fp:
  7262. fp.write(exported_excellon)
  7263. except PermissionError:
  7264. self.inform.emit('[WARNING] %s' %
  7265. _("Permission denied, saving not possible.\n"
  7266. "Most likely another app is holding the file open and not accessible."))
  7267. return 'fail'
  7268. if self.defaults["global_open_style"] is False:
  7269. self.file_opened.emit("Excellon", filename)
  7270. self.file_saved.emit("Excellon", filename)
  7271. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7272. else:
  7273. return exported_excellon
  7274. except Exception as e:
  7275. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7276. return 'fail'
  7277. if use_thread is True:
  7278. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7279. def job_thread_exc(app_obj):
  7280. ret = make_excellon()
  7281. if ret == 'fail':
  7282. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7283. return
  7284. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7285. else:
  7286. eret = make_excellon()
  7287. if eret == 'fail':
  7288. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7289. return 'fail'
  7290. if local_use is not None:
  7291. return eret
  7292. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7293. """
  7294. Exports a Gerber Object to an Gerber file.
  7295. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7296. :param filename: Path to the Gerber file to save to.
  7297. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7298. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7299. :param use_thread: if to be run in a separate thread
  7300. :return:
  7301. """
  7302. self.defaults.report_usage("export_gerber()")
  7303. if filename is None:
  7304. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7305. is not None else self.defaults["global_last_folder"]
  7306. self.log.debug("export_gerber()")
  7307. if local_use is None:
  7308. try:
  7309. obj = self.collection.get_by_name(str(obj_name))
  7310. except Exception:
  7311. return "Could not retrieve object: %s" % obj_name
  7312. else:
  7313. obj = local_use
  7314. # updated units
  7315. gunits = self.defaults["gerber_exp_units"]
  7316. gwhole = self.defaults["gerber_exp_integer"]
  7317. gfract = self.defaults["gerber_exp_decimals"]
  7318. gzeros = self.defaults["gerber_exp_zeros"]
  7319. fc_units = self.defaults['units'].upper()
  7320. if fc_units == 'MM':
  7321. factor = 1 if gunits == 'MM' else 0.03937
  7322. else:
  7323. factor = 25.4 if gunits == 'MM' else 1
  7324. def make_gerber():
  7325. try:
  7326. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7327. header = 'G04*\n'
  7328. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7329. (str(self.version), str(self.version_date))
  7330. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7331. header += 'G04 Created on : %s*' % time_str + '\n'
  7332. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7333. header += "%MO{units}*%\n".format(units=gunits)
  7334. for apid in obj.apertures:
  7335. if obj.apertures[apid]['type'] == 'C':
  7336. header += "%ADD{apid}{type},{size}*%\n".format(
  7337. apid=str(apid),
  7338. type='C',
  7339. size=(factor * obj.apertures[apid]['size'])
  7340. )
  7341. elif obj.apertures[apid]['type'] == 'R':
  7342. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7343. apid=str(apid),
  7344. type='R',
  7345. width=(factor * obj.apertures[apid]['width']),
  7346. height=(factor * obj.apertures[apid]['height'])
  7347. )
  7348. elif obj.apertures[apid]['type'] == 'O':
  7349. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7350. apid=str(apid),
  7351. type='O',
  7352. width=(factor * obj.apertures[apid]['width']),
  7353. height=(factor * obj.apertures[apid]['height'])
  7354. )
  7355. header += '\n'
  7356. # obsolete units but some software may need it
  7357. if gunits == 'IN':
  7358. header += 'G70*\n'
  7359. else:
  7360. header += 'G71*\n'
  7361. # Absolute Mode
  7362. header += 'G90*\n'
  7363. header += 'G01*\n'
  7364. # positive polarity
  7365. header += '%LPD*%\n'
  7366. footer = 'M02*\n'
  7367. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7368. exported_gerber = header
  7369. exported_gerber += gerber_code
  7370. exported_gerber += footer
  7371. if local_use is None:
  7372. try:
  7373. with open(filename, 'w') as fp:
  7374. fp.write(exported_gerber)
  7375. except PermissionError:
  7376. self.inform.emit('[WARNING] %s' %
  7377. _("Permission denied, saving not possible.\n"
  7378. "Most likely another app is holding the file open and not accessible."))
  7379. return 'fail'
  7380. if self.defaults["global_open_style"] is False:
  7381. self.file_opened.emit("Gerber", filename)
  7382. self.file_saved.emit("Gerber", filename)
  7383. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7384. else:
  7385. return exported_gerber
  7386. except Exception as e:
  7387. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7388. return 'fail'
  7389. if use_thread is True:
  7390. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7391. def job_thread_grb(app_obj):
  7392. ret = make_gerber()
  7393. if ret == 'fail':
  7394. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7395. return
  7396. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7397. else:
  7398. gret = make_gerber()
  7399. if gret == 'fail':
  7400. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7401. return 'fail'
  7402. if local_use is not None:
  7403. return gret
  7404. def export_dxf(self, obj_name, filename, use_thread=True):
  7405. """
  7406. Exports a Geometry Object to an DXF file.
  7407. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7408. :param filename: Path to the DXF file to save to.
  7409. :param use_thread: if to be run in a separate thread
  7410. :return:
  7411. """
  7412. self.defaults.report_usage("export_dxf()")
  7413. if filename is None:
  7414. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7415. is not None else self.defaults["global_last_folder"]
  7416. self.log.debug("export_dxf()")
  7417. try:
  7418. obj = self.collection.get_by_name(str(obj_name))
  7419. except Exception:
  7420. # TODO: The return behavior has not been established... should raise exception?
  7421. return "Could not retrieve object: %s" % obj_name
  7422. def make_dxf():
  7423. try:
  7424. dxf_code = obj.export_dxf()
  7425. dxf_code.saveas(filename)
  7426. if self.defaults["global_open_style"] is False:
  7427. self.file_opened.emit("DXF", filename)
  7428. self.file_saved.emit("DXF", filename)
  7429. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7430. except Exception:
  7431. return 'fail'
  7432. if use_thread is True:
  7433. with self.proc_container.new(_("Exporting DXF")) as proc:
  7434. def job_thread_exc(app_obj):
  7435. ret_dxf_val = make_dxf()
  7436. if ret_dxf_val == 'fail':
  7437. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7438. return
  7439. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7440. else:
  7441. ret = make_dxf()
  7442. if ret == 'fail':
  7443. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7444. return
  7445. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7446. """
  7447. Adds a new Geometry Object to the projects and populates
  7448. it with shapes extracted from the SVG file.
  7449. :param plot: If True then the resulting object will be plotted on canvas
  7450. :param filename: Path to the SVG file.
  7451. :param geo_type: Type of FlatCAM object that will be created from SVG
  7452. :param outname: The name given to the resulting FlatCAM object
  7453. :return:
  7454. """
  7455. self.defaults.report_usage("import_svg()")
  7456. log.debug("App.import_svg()")
  7457. obj_type = ""
  7458. if geo_type is None or geo_type == "geometry":
  7459. obj_type = "geometry"
  7460. elif geo_type == "gerber":
  7461. obj_type = "gerber"
  7462. else:
  7463. self.inform.emit('[ERROR_NOTCL] %s' %
  7464. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7465. return
  7466. units = self.defaults['units'].upper()
  7467. def obj_init(geo_obj, app_obj):
  7468. geo_obj.import_svg(filename, obj_type, units=units)
  7469. geo_obj.multigeo = False
  7470. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7471. with self.proc_container.new(_("Importing SVG")) as proc:
  7472. # Object name
  7473. name = outname or filename.split('/')[-1].split('\\')[-1]
  7474. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7475. if ret == 'fail':
  7476. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7477. return 'fail'
  7478. # Register recent file
  7479. self.file_opened.emit("svg", filename)
  7480. # GUI feedback
  7481. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7482. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7483. """
  7484. Adds a new Geometry Object to the projects and populates
  7485. it with shapes extracted from the DXF file.
  7486. :param filename: Path to the DXF file.
  7487. :param geo_type: Type of FlatCAM object that will be created from DXF
  7488. :param outname: Name for the imported Geometry
  7489. :param plot: If True then the resulting object will be plotted on canvas
  7490. :return:
  7491. """
  7492. self.defaults.report_usage("import_dxf()")
  7493. obj_type = ""
  7494. if geo_type is None or geo_type == "geometry":
  7495. obj_type = "geometry"
  7496. elif geo_type == "gerber":
  7497. obj_type = geo_type
  7498. else:
  7499. self.inform.emit('[ERROR_NOTCL] %s' %
  7500. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7501. return
  7502. units = self.defaults['units'].upper()
  7503. def obj_init(geo_obj, app_obj):
  7504. geo_obj.import_dxf(filename, obj_type, units=units)
  7505. geo_obj.multigeo = False
  7506. with self.proc_container.new(_("Importing DXF")):
  7507. # Object name
  7508. name = outname or filename.split('/')[-1].split('\\')[-1]
  7509. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7510. if ret == 'fail':
  7511. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7512. return 'fail'
  7513. # Register recent file
  7514. self.file_opened.emit("dxf", filename)
  7515. # GUI feedback
  7516. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7517. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7518. """
  7519. Opens a Gerber file, parses it and creates a new object for
  7520. it in the program. Thread-safe.
  7521. :param outname: Name of the resulting object. None causes the
  7522. name to be that of the file. Str.
  7523. :param filename: Gerber file filename
  7524. :type filename: str
  7525. :param plot: boolean, to plot or not the resulting object
  7526. :param from_tcl: True if run from Tcl Shell
  7527. :return: None
  7528. """
  7529. # How the object should be initialized
  7530. def obj_init(gerber_obj, app_obj):
  7531. assert isinstance(gerber_obj, GerberObject), \
  7532. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7533. # Opening the file happens here
  7534. try:
  7535. gerber_obj.parse_file(filename)
  7536. except IOError:
  7537. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7538. return "fail"
  7539. except ParseError as err:
  7540. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7541. app_obj.log.error(str(err))
  7542. return "fail"
  7543. except Exception as e:
  7544. log.debug("App.open_gerber() --> %s" % str(e))
  7545. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7546. msg += traceback.format_exc()
  7547. app_obj.inform.emit(msg)
  7548. return "fail"
  7549. if gerber_obj.is_empty():
  7550. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7551. _("Object is not Gerber file or empty. Aborting object creation."))
  7552. return "fail"
  7553. App.log.debug("open_gerber()")
  7554. with self.proc_container.new(_("Opening Gerber")):
  7555. # Object name
  7556. name = outname or filename.split('/')[-1].split('\\')[-1]
  7557. # # ## Object creation # ##
  7558. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7559. if ret_val == 'fail':
  7560. if from_tcl:
  7561. filename = self.defaults['global_tcl_path'] + '/' + name
  7562. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7563. if ret_val == 'fail':
  7564. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7565. return 'fail'
  7566. # Register recent file
  7567. self.file_opened.emit("gerber", filename)
  7568. # GUI feedback
  7569. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7570. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7571. """
  7572. Opens an Excellon file, parses it and creates a new object for
  7573. it in the program. Thread-safe.
  7574. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7575. :param filename: Excellon file filename
  7576. :type filename: str
  7577. :param plot: boolean, to plot or not the resulting object
  7578. :param from_tcl: True if run from Tcl Shell
  7579. :return: None
  7580. """
  7581. App.log.debug("open_excellon()")
  7582. # How the object should be initialized
  7583. def obj_init(excellon_obj, app_obj):
  7584. try:
  7585. ret = excellon_obj.parse_file(filename=filename)
  7586. if ret == "fail":
  7587. log.debug("Excellon parsing failed.")
  7588. self.inform.emit('[ERROR_NOTCL] %s' %
  7589. _("This is not Excellon file."))
  7590. return "fail"
  7591. except IOError:
  7592. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7593. (_("Cannot open file"), filename))
  7594. log.debug("Could not open Excellon object.")
  7595. return "fail"
  7596. except Exception:
  7597. msg = '[ERROR_NOTCL] %s' % \
  7598. _("An internal error has occurred. See shell.\n")
  7599. msg += traceback.format_exc()
  7600. app_obj.inform.emit(msg)
  7601. return "fail"
  7602. ret = excellon_obj.create_geometry()
  7603. if ret == 'fail':
  7604. log.debug("Could not create geometry for Excellon object.")
  7605. return "fail"
  7606. for tool in excellon_obj.tools:
  7607. if excellon_obj.tools[tool]['solid_geometry']:
  7608. return
  7609. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7610. return "fail"
  7611. with self.proc_container.new(_("Opening Excellon.")):
  7612. # Object name
  7613. name = outname or filename.split('/')[-1].split('\\')[-1]
  7614. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7615. if ret_val == 'fail':
  7616. if from_tcl:
  7617. filename = self.defaults['global_tcl_path'] + '/' + name
  7618. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7619. if ret_val == 'fail':
  7620. self.inform.emit('[ERROR_NOTCL] %s' %
  7621. _('Open Excellon file failed. Probable not an Excellon file.'))
  7622. return
  7623. # Register recent file
  7624. self.file_opened.emit("excellon", filename)
  7625. # GUI feedback
  7626. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7627. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7628. """
  7629. Opens a G-gcode file, parses it and creates a new object for
  7630. it in the program. Thread-safe.
  7631. :param filename: G-code file filename
  7632. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7633. :param force_parsing:
  7634. :param plot: If True plot the object on canvas
  7635. :param from_tcl: True if run from Tcl Shell
  7636. :return: None
  7637. """
  7638. App.log.debug("open_gcode()")
  7639. # How the object should be initialized
  7640. def obj_init(job_obj, app_obj_):
  7641. """
  7642. :param job_obj: the resulting object
  7643. :type app_obj_: App
  7644. """
  7645. assert isinstance(app_obj_, App), \
  7646. "Initializer expected App, got %s" % type(app_obj_)
  7647. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7648. try:
  7649. f = open(filename)
  7650. gcode = f.read()
  7651. f.close()
  7652. except IOError:
  7653. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7654. return "fail"
  7655. job_obj.gcode = gcode
  7656. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7657. if gcode_ret == "fail":
  7658. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7659. return "fail"
  7660. job_obj.create_geometry()
  7661. with self.proc_container.new(_("Opening G-Code.")):
  7662. # Object name
  7663. name = outname or filename.split('/')[-1].split('\\')[-1]
  7664. # New object creation and file processing
  7665. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7666. if ret_val == 'fail':
  7667. if from_tcl:
  7668. filename = self.defaults['global_tcl_path'] + '/' + name
  7669. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7670. if ret_val == 'fail':
  7671. self.inform.emit('[ERROR_NOTCL] %s' %
  7672. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7673. "Try to load it from File menu.\n "
  7674. "Attempting to create a FlatCAM CNCJob Object from "
  7675. "G-Code file failed during processing"))
  7676. return "fail"
  7677. # Register recent file
  7678. self.file_opened.emit("cncjob", filename)
  7679. # GUI feedback
  7680. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7681. def open_hpgl2(self, filename, outname=None):
  7682. """
  7683. Opens a HPGL2 file, parses it and creates a new object for
  7684. it in the program. Thread-safe.
  7685. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7686. :param filename: HPGL2 file filename
  7687. :return: None
  7688. """
  7689. filename = filename
  7690. # How the object should be initialized
  7691. def obj_init(geo_obj, app_obj):
  7692. assert isinstance(geo_obj, GeometryObject), \
  7693. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7694. # Opening the file happens here
  7695. obj = HPGL2(self)
  7696. try:
  7697. HPGL2.parse_file(obj, filename)
  7698. except IOError:
  7699. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7700. return "fail"
  7701. except ParseError as err:
  7702. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7703. app_obj.log.error(str(err))
  7704. return "fail"
  7705. except Exception as e:
  7706. log.debug("App.open_hpgl2() --> %s" % str(e))
  7707. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7708. msg += traceback.format_exc()
  7709. app_obj.inform.emit(msg)
  7710. return "fail"
  7711. geo_obj.multigeo = True
  7712. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7713. geo_obj.tools = deepcopy(obj.tools)
  7714. geo_obj.source_file = deepcopy(obj.source_file)
  7715. del obj
  7716. if not geo_obj.solid_geometry:
  7717. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7718. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7719. return "fail"
  7720. App.log.debug("open_hpgl2()")
  7721. with self.proc_container.new(_("Opening HPGL2")):
  7722. # Object name
  7723. name = outname or filename.split('/')[-1].split('\\')[-1]
  7724. # # ## Object creation # ##
  7725. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7726. if ret == 'fail':
  7727. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7728. return 'fail'
  7729. # Register recent file
  7730. self.file_opened.emit("geometry", filename)
  7731. # GUI feedback
  7732. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7733. def open_script(self, filename, outname=None, silent=False):
  7734. """
  7735. Opens a Script file, parses it and creates a new object for
  7736. it in the program. Thread-safe.
  7737. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7738. :param filename: Script file filename
  7739. :param silent: If True there will be no messages printed to StatusBar
  7740. :return: None
  7741. """
  7742. def obj_init(script_obj, app_obj):
  7743. assert isinstance(script_obj, ScriptObject), \
  7744. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7745. if silent is False:
  7746. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7747. try:
  7748. script_obj.parse_file(filename)
  7749. except IOError:
  7750. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7751. return "fail"
  7752. except ParseError as err:
  7753. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7754. app_obj.log.error(str(err))
  7755. return "fail"
  7756. except Exception as e:
  7757. log.debug("App.open_script() -> %s" % str(e))
  7758. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7759. msg += traceback.format_exc()
  7760. app_obj.inform.emit(msg)
  7761. return "fail"
  7762. App.log.debug("open_script()")
  7763. with self.proc_container.new(_("Opening TCL Script...")):
  7764. # Object name
  7765. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7766. # Object creation
  7767. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7768. if ret_val == 'fail':
  7769. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7770. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7771. if ret_val == 'fail':
  7772. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7773. return 'fail'
  7774. # Register recent file
  7775. self.file_opened.emit("script", filename)
  7776. # GUI feedback
  7777. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7778. def open_config_file(self, filename, run_from_arg=None):
  7779. """
  7780. Loads a config file from the specified file.
  7781. :param filename: Name of the file from which to load.
  7782. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7783. :return: None
  7784. """
  7785. App.log.debug("Opening config file: " + filename)
  7786. if run_from_arg:
  7787. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7788. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7789. _("Opening FlatCAM Config file.")),
  7790. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7791. color=QtGui.QColor("gray"))
  7792. # # add the tab if it was closed
  7793. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7794. # # first clear previous text in text editor (if any)
  7795. # self.ui.text_editor_tab.code_editor.clear()
  7796. #
  7797. # # Switch plot_area to CNCJob tab
  7798. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7799. # close the Code editor if already open
  7800. if self.toggle_codeeditor:
  7801. self.on_toggle_code_editor()
  7802. self.on_toggle_code_editor()
  7803. try:
  7804. if filename:
  7805. f = QtCore.QFile(filename)
  7806. if f.open(QtCore.QIODevice.ReadOnly):
  7807. stream = QtCore.QTextStream(f)
  7808. code_edited = stream.readAll()
  7809. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7810. f.close()
  7811. except IOError:
  7812. App.log.error("Failed to open config file: %s" % filename)
  7813. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7814. (_("Failed to open config file"), filename))
  7815. return
  7816. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7817. """
  7818. Loads a project from the specified file.
  7819. 1) Loads and parses file
  7820. 2) Registers the file as recently opened.
  7821. 3) Calls on_file_new()
  7822. 4) Updates options
  7823. 5) Calls new_object() with the object's from_dict() as init method.
  7824. 6) Calls plot_all() if plot=True
  7825. :param filename: Name of the file from which to load.
  7826. :param run_from_arg: True if run for arguments
  7827. :param plot: If True plot all objects in the project
  7828. :param cli: Run from command line
  7829. :param from_tcl: True if run from Tcl Sehll
  7830. :return: None
  7831. """
  7832. App.log.debug("Opening project: " + filename)
  7833. # block autosaving while a project is loaded
  7834. self.block_autosave = True
  7835. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7836. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7837. if cli is None:
  7838. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7839. if run_from_arg:
  7840. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7841. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7842. _("Opening FlatCAM Project file.")),
  7843. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7844. color=QtGui.QColor("gray"))
  7845. # Open and parse an uncompressed Project file
  7846. try:
  7847. f = open(filename, 'r')
  7848. except IOError:
  7849. if from_tcl:
  7850. name = filename.split('/')[-1].split('\\')[-1]
  7851. filename = self.defaults['global_tcl_path'] + '/' + name
  7852. try:
  7853. f = open(filename, 'r')
  7854. except IOError:
  7855. log.error("Failed to open project file: %s" % filename)
  7856. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7857. return
  7858. else:
  7859. log.error("Failed to open project file: %s" % filename)
  7860. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7861. return
  7862. try:
  7863. d = json.load(f, object_hook=dict2obj)
  7864. except Exception as e:
  7865. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7866. (filename, str(e)))
  7867. f.close()
  7868. # Open and parse a compressed Project file
  7869. try:
  7870. with lzma.open(filename) as f:
  7871. file_content = f.read().decode('utf-8')
  7872. d = json.loads(file_content, object_hook=dict2obj)
  7873. except Exception as e:
  7874. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7875. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7876. return
  7877. # Clear the current project
  7878. # # NOT THREAD SAFE # ##
  7879. if run_from_arg is True:
  7880. pass
  7881. elif cli is True:
  7882. self.delete_selection_shape()
  7883. else:
  7884. self.on_file_new()
  7885. # Project options
  7886. self.options.update(d['options'])
  7887. self.project_filename = filename
  7888. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7889. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7890. if cli is None:
  7891. self.set_screen_units(self.options["units"])
  7892. # Re create objects
  7893. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7894. for obj in d['objs']:
  7895. try:
  7896. def obj_init(obj_inst, app_inst):
  7897. obj_inst.from_dict(obj)
  7898. App.log.debug("Recreating from opened project an %s object: %s" %
  7899. (obj['kind'].capitalize(), obj['options']['name']))
  7900. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7901. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7902. if cli is None:
  7903. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7904. obj['kind'].upper(),
  7905. obj['options']['name']
  7906. )
  7907. )
  7908. self.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7909. except Exception as e:
  7910. print('App.open_project() --> ' + str(e))
  7911. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7912. self.should_we_save = False
  7913. self.file_opened.emit("project", filename)
  7914. # restore autosaving after a project was loaded
  7915. self.block_autosave = False
  7916. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7917. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7918. if cli is None:
  7919. self.set_ui_title(name=self.project_filename)
  7920. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7921. def plot_all(self, fit_view=True, use_thread=True):
  7922. """
  7923. Re-generates all plots from all objects.
  7924. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7925. :param use_thread: if True will use threading for plotting the objects
  7926. :return: None
  7927. """
  7928. self.log.debug("Plot_all()")
  7929. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7930. for plot_obj in self.collection.get_list():
  7931. def worker_task(obj):
  7932. with self.proc_container.new("Plotting"):
  7933. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7934. if fit_view is True:
  7935. self.object_plotted.emit(obj)
  7936. if use_thread is True:
  7937. # Send to worker
  7938. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7939. else:
  7940. worker_task(plot_obj)
  7941. def register_folder(self, filename):
  7942. """
  7943. Register the last folder used by the app to open something
  7944. :param filename: the last folder is extracted from the filename
  7945. :return: None
  7946. """
  7947. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7948. def register_save_folder(self, filename):
  7949. """
  7950. Register the last folder used by the app to save something
  7951. :param filename: the last folder is extracted from the filename
  7952. :return: None
  7953. """
  7954. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7955. # def set_progress_bar(self, percentage, text=""):
  7956. # """
  7957. # Set a progress bar to a value (percentage)
  7958. #
  7959. # :param percentage: Value set to the progressbar
  7960. # :param text: Not used
  7961. # :return: None
  7962. # """
  7963. # self.ui.progress_bar.setValue(int(percentage))
  7964. def setup_recent_items(self):
  7965. """
  7966. Setup a dictionary with the recent files accessed, organized by type
  7967. :return:
  7968. """
  7969. icons = {
  7970. "gerber": self.resource_location + "/flatcam_icon16.png",
  7971. "excellon": self.resource_location + "/drill16.png",
  7972. 'geometry': self.resource_location + "/geometry16.png",
  7973. "cncjob": self.resource_location + "/cnc16.png",
  7974. "script": self.resource_location + "/script_new24.png",
  7975. "document": self.resource_location + "/notes16_1.png",
  7976. "project": self.resource_location + "/project16.png",
  7977. "svg": self.resource_location + "/geometry16.png",
  7978. "dxf": self.resource_location + "/dxf16.png",
  7979. "pdf": self.resource_location + "/pdf32.png",
  7980. "image": self.resource_location + "/image16.png"
  7981. }
  7982. try:
  7983. image_opener = self.image_tool.import_image
  7984. except AttributeError:
  7985. image_opener = None
  7986. openers = {
  7987. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7988. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7989. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7990. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7991. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7992. "document": None,
  7993. 'project': self.open_project,
  7994. 'svg': self.import_svg,
  7995. 'dxf': self.import_dxf,
  7996. 'image': image_opener,
  7997. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7998. }
  7999. # Open recent file for files
  8000. try:
  8001. f = open(self.data_path + '/recent.json')
  8002. except IOError:
  8003. App.log.error("Failed to load recent item list.")
  8004. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8005. return
  8006. try:
  8007. self.recent = json.load(f)
  8008. except json.errors.JSONDecodeError:
  8009. App.log.error("Failed to parse recent item list.")
  8010. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8011. f.close()
  8012. return
  8013. f.close()
  8014. # Open recent file for projects
  8015. try:
  8016. fp = open(self.data_path + '/recent_projects.json')
  8017. except IOError:
  8018. App.log.error("Failed to load recent project item list.")
  8019. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8020. return
  8021. try:
  8022. self.recent_projects = json.load(fp)
  8023. except json.errors.JSONDecodeError:
  8024. App.log.error("Failed to parse recent project item list.")
  8025. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8026. fp.close()
  8027. return
  8028. fp.close()
  8029. # Closure needed to create callbacks in a loop.
  8030. # Otherwise late binding occurs.
  8031. def make_callback(func, fname):
  8032. def opener():
  8033. func(fname)
  8034. return opener
  8035. def reset_recent_files():
  8036. # Reset menu
  8037. self.ui.recent.clear()
  8038. self.recent = []
  8039. try:
  8040. ff = open(self.data_path + '/recent.json', 'w')
  8041. except IOError:
  8042. App.log.error("Failed to open recent items file for writing.")
  8043. return
  8044. json.dump(self.recent, ff)
  8045. def reset_recent_projects():
  8046. # Reset menu
  8047. self.ui.recent_projects.clear()
  8048. self.recent_projects = []
  8049. try:
  8050. frp = open(self.data_path + '/recent_projects.json', 'w')
  8051. except IOError:
  8052. App.log.error("Failed to open recent projects items file for writing.")
  8053. return
  8054. json.dump(self.recent, frp)
  8055. # Reset menu
  8056. self.ui.recent.clear()
  8057. self.ui.recent_projects.clear()
  8058. # Create menu items for projects
  8059. for recent in self.recent_projects:
  8060. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8061. if recent['kind'] == 'project':
  8062. try:
  8063. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8064. # Attach callback
  8065. o = make_callback(openers[recent["kind"]], recent['filename'])
  8066. action.triggered.connect(o)
  8067. self.ui.recent_projects.addAction(action)
  8068. except KeyError:
  8069. App.log.error("Unsupported file type: %s" % recent["kind"])
  8070. # Last action in Recent Files menu is one that Clear the content
  8071. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8072. (_("Clear Recent projects")), self)
  8073. clear_action_proj.triggered.connect(reset_recent_projects)
  8074. self.ui.recent_projects.addSeparator()
  8075. self.ui.recent_projects.addAction(clear_action_proj)
  8076. # Create menu items for files
  8077. for recent in self.recent:
  8078. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8079. if recent['kind'] != 'project':
  8080. try:
  8081. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8082. # Attach callback
  8083. o = make_callback(openers[recent["kind"]], recent['filename'])
  8084. action.triggered.connect(o)
  8085. self.ui.recent.addAction(action)
  8086. except KeyError:
  8087. App.log.error("Unsupported file type: %s" % recent["kind"])
  8088. # Last action in Recent Files menu is one that Clear the content
  8089. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8090. (_("Clear Recent files")), self)
  8091. clear_action.triggered.connect(reset_recent_files)
  8092. self.ui.recent.addSeparator()
  8093. self.ui.recent.addAction(clear_action)
  8094. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8095. # self.ui.menufilerecent.set_submenu(recent_menu)
  8096. # recent_menu.show_all()
  8097. # self.ui.recent.show()
  8098. self.log.debug("Recent items list has been populated.")
  8099. def setup_component_editor(self):
  8100. """
  8101. Default text for the Selected tab when is not taken by the Object UI.
  8102. :return:
  8103. """
  8104. # label = QtWidgets.QLabel("Choose an item from Project")
  8105. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8106. sel_title = QtWidgets.QTextEdit(
  8107. _('<b>Shortcut Key List</b>'))
  8108. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8109. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8110. f_settings = QSettings("Open Source", "FlatCAM")
  8111. if f_settings.contains("notebook_font_size"):
  8112. fsize = f_settings.value('notebook_font_size', type=int)
  8113. else:
  8114. fsize = 12
  8115. tsize = fsize + int(fsize / 2)
  8116. # selected_text = (_('''
  8117. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8118. # </p>
  8119. #
  8120. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8121. # The normal flow when working in FlatCAM is the following:</span></p>
  8122. #
  8123. # <ol>
  8124. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8125. # file into
  8126. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8127. # even dragging and dropping the files on the GUI.<br />
  8128. # <br />
  8129. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8130. # drop of the
  8131. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8132. # &nbsp;</li>
  8133. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8134. # and then
  8135. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8136. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8137. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8138. # <br />
  8139. # If the selection of the object is done on the canvas by single click instead, and the
  8140. # <strong>SELECTED TAB</strong>
  8141. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8142. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8143. # it even if it was out of focus.<br />
  8144. # <br />
  8145. # You can change the parameters in this screen and the flow direction is like this:<br />
  8146. # <br />
  8147. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8148. # <strong> Geometry Object
  8149. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8150. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8151. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8152. # </ol>
  8153. #
  8154. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8155. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8156. # <strong>F3</strong>.</span></p>
  8157. #
  8158. # ''').format(fsize=fsize, tsize=tsize))
  8159. selected_text = '''
  8160. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8161. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8162. {s1}</span></p>
  8163. <ol>
  8164. <li><span style="font-size:{fsize}px">{s2}<br />
  8165. <br />
  8166. {s3}</span><br />
  8167. &nbsp;</li>
  8168. <li><span style="font-size:{fsize}px">{s4}<br />
  8169. &nbsp;</li>
  8170. <br />
  8171. <li><span style="font-size:{fsize}px">{s5}<br />
  8172. &nbsp;</li>
  8173. <br />
  8174. <li><span style="font-size:{fsize}px">{s6}<br />
  8175. <br />
  8176. {s7}</span></li>
  8177. </ol>
  8178. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8179. '''.format(
  8180. title=_("Selected Tab - Choose an Item from Project Tab"),
  8181. subtitle=_("Details"),
  8182. s1=_("The normal flow when working in FlatCAM is the following:"),
  8183. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8184. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8185. "files on the GUI."),
  8186. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8187. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8188. "actions offered within the app."),
  8189. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8190. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8191. "SELECTED TAB will be updated with the object properties according to its kind: "
  8192. "Gerber, Excellon, Geometry or CNCJob object."),
  8193. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8194. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8195. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8196. "the SELECTED TAB and populate it even if it was out of focus."),
  8197. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8198. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8199. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8200. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8201. "(again, done in SELECTED TAB) --> Save GCode."),
  8202. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8203. "or through its own key shortcut: <b>F3</b>."),
  8204. tsize=tsize,
  8205. fsize=fsize
  8206. )
  8207. sel_title.setText(selected_text)
  8208. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8209. self.ui.selected_scroll_area.setWidget(sel_title)
  8210. def setup_obj_classes(self):
  8211. """
  8212. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8213. class.
  8214. :return: None
  8215. """
  8216. FlatCAMObj.app = self
  8217. ObjectCollection.app = self
  8218. Gerber.app = self
  8219. Excellon.app = self
  8220. Geometry.app = self
  8221. CNCjob.app = self
  8222. FCProcess.app = self
  8223. FCProcessContainer.app = self
  8224. OptionsGroupUI.app = self
  8225. def version_check(self):
  8226. """
  8227. Checks for the latest version of the program. Alerts the
  8228. user if theirs is outdated. This method is meant to be run
  8229. in a separate thread.
  8230. :return: None
  8231. """
  8232. self.log.debug("version_check()")
  8233. if self.defaults["global_send_stats"] is True:
  8234. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8235. App.version_url,
  8236. str(self.defaults['global_serial']),
  8237. str(self.version),
  8238. str(self.os),
  8239. urllib.parse.urlencode(self.defaults["global_stats"])
  8240. )
  8241. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8242. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8243. # urllib.parse.urlencode(self.defaults["global_stats"])
  8244. else:
  8245. # no_stats dict; just so it won't break things on website
  8246. no_ststs_dict = {}
  8247. no_ststs_dict["global_ststs"] = {}
  8248. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8249. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8250. App.log.debug("Checking for updates @ %s" % full_url)
  8251. # ## Get the data
  8252. try:
  8253. f = urllib.request.urlopen(full_url)
  8254. except Exception:
  8255. # App.log.warning("Failed checking for latest version. Could not connect.")
  8256. self.log.warning("Failed checking for latest version. Could not connect.")
  8257. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8258. return
  8259. try:
  8260. data = json.load(f)
  8261. except Exception as e:
  8262. App.log.error("Could not parse information about latest version.")
  8263. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8264. App.log.debug("json.load(): %s" % str(e))
  8265. f.close()
  8266. return
  8267. f.close()
  8268. # ## Latest version?
  8269. if self.version >= data["version"]:
  8270. App.log.debug("FlatCAM is up to date!")
  8271. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8272. return
  8273. App.log.debug("Newer version available.")
  8274. self.message.emit(
  8275. _("Newer Version Available"),
  8276. '%s<br><br>><b>%s</b><br>%s' % (
  8277. _("There is a newer version of FlatCAM available for download:"),
  8278. str(data["name"]),
  8279. str(data["message"])
  8280. ),
  8281. _("info")
  8282. )
  8283. def on_plotcanvas_setup(self, container=None):
  8284. """
  8285. This is doing the setup for the plot area (canvas).
  8286. :param container: QT Widget where to install the canvas
  8287. :return: None
  8288. """
  8289. if container:
  8290. plot_container = container
  8291. else:
  8292. plot_container = self.ui.right_layout
  8293. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8294. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8295. self.is_legacy = True
  8296. self.defaults["global_graphic_engine"] = "2D"
  8297. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8298. else:
  8299. try:
  8300. self.plotcanvas = PlotCanvas(plot_container, self)
  8301. except Exception as er:
  8302. msg_txt = traceback.format_exc()
  8303. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8304. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8305. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8306. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8307. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8308. msg += msg_txt
  8309. self.inform.emit(msg)
  8310. return 'fail'
  8311. # So it can receive key presses
  8312. self.plotcanvas.native.setFocus()
  8313. if self.is_legacy is False:
  8314. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8315. # Set the mouse button for panning
  8316. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8317. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8318. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8319. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8320. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8321. # Keys over plot enabled
  8322. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8323. if self.defaults['global_cursor_type'] == 'small':
  8324. self.app_cursor = self.plotcanvas.new_cursor()
  8325. else:
  8326. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8327. if self.ui.grid_snap_btn.isChecked():
  8328. self.app_cursor.enabled = True
  8329. else:
  8330. self.app_cursor.enabled = False
  8331. if self.is_legacy is False:
  8332. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8333. else:
  8334. # will use the default Matplotlib axes
  8335. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8336. def on_zoom_fit(self, event):
  8337. """
  8338. Callback for zoom-fit request. This can be either from the corresponding
  8339. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8340. with axes limits from the geometry bounds of all objects.
  8341. :param event: Ignored.
  8342. :return: None
  8343. """
  8344. if self.is_legacy is False:
  8345. self.plotcanvas.fit_view()
  8346. else:
  8347. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8348. width = xmax - xmin
  8349. height = ymax - ymin
  8350. xmin -= 0.05 * width
  8351. xmax += 0.05 * width
  8352. ymin -= 0.05 * height
  8353. ymax += 0.05 * height
  8354. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8355. def on_zoom_in(self):
  8356. """
  8357. Callback for zoom-in request.
  8358. :return:
  8359. """
  8360. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8361. def on_zoom_out(self):
  8362. """
  8363. Callback for zoom-out request.
  8364. :return:
  8365. """
  8366. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8367. def disable_all_plots(self):
  8368. self.defaults.report_usage("disable_all_plots()")
  8369. self.disable_plots(self.collection.get_list())
  8370. self.inform.emit('[success] %s' %
  8371. _("All plots disabled."))
  8372. def disable_other_plots(self):
  8373. self.defaults.report_usage("disable_other_plots()")
  8374. self.disable_plots(self.collection.get_non_selected())
  8375. self.inform.emit('[success] %s' %
  8376. _("All non selected plots disabled."))
  8377. def enable_all_plots(self):
  8378. self.defaults.report_usage("enable_all_plots()")
  8379. self.enable_plots(self.collection.get_list())
  8380. self.inform.emit('[success] %s' %
  8381. _("All plots enabled."))
  8382. def on_enable_sel_plots(self):
  8383. log.debug("App.on_enable_sel_plot()")
  8384. object_list = self.collection.get_selected()
  8385. self.enable_plots(objects=object_list)
  8386. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8387. def on_disable_sel_plots(self):
  8388. log.debug("App.on_disable_sel_plot()")
  8389. # self.inform.emit(_("Disabling plots ..."))
  8390. object_list = self.collection.get_selected()
  8391. self.disable_plots(objects=object_list)
  8392. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8393. def enable_plots(self, objects):
  8394. """
  8395. Enable plots
  8396. :param objects: list of Objects to be enabled
  8397. :return:
  8398. """
  8399. log.debug("Enabling plots ...")
  8400. # self.inform.emit(_("Working ..."))
  8401. for obj in objects:
  8402. if obj.options['plot'] is False:
  8403. obj.options.set_change_callback(lambda x: None)
  8404. obj.options['plot'] = True
  8405. try:
  8406. # only the Gerber obj has on_plot_cb_click() method
  8407. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8408. # disable this cb while disconnected,
  8409. # in case the operation takes time the user is not allowed to change it
  8410. obj.ui.plot_cb.setDisabled(True)
  8411. except AttributeError:
  8412. pass
  8413. obj.set_form_item("plot")
  8414. try:
  8415. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8416. obj.ui.plot_cb.setDisabled(False)
  8417. except AttributeError:
  8418. pass
  8419. obj.options.set_change_callback(obj.on_options_change)
  8420. def worker_task(objs):
  8421. with self.proc_container.new(_("Enabling plots ...")):
  8422. for plot_obj in objs:
  8423. # obj.options['plot'] = True
  8424. if isinstance(plot_obj, CNCJobObject):
  8425. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8426. else:
  8427. plot_obj.plot(visible=True)
  8428. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8429. # self.plots_updated.emit()
  8430. def disable_plots(self, objects):
  8431. """
  8432. Disables plots
  8433. :param objects: list of Objects to be disabled
  8434. :return:
  8435. """
  8436. # if no objects selected then do nothing
  8437. if not self.collection.get_selected():
  8438. return
  8439. log.debug("Disabling plots ...")
  8440. # self.inform.emit(_("Working ..."))
  8441. for obj in objects:
  8442. if obj.options['plot'] is True:
  8443. obj.options.set_change_callback(lambda x: None)
  8444. obj.options['plot'] = False
  8445. try:
  8446. # only the Gerber obj has on_plot_cb_click() method
  8447. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8448. obj.ui.plot_cb.setDisabled(True)
  8449. except AttributeError:
  8450. pass
  8451. obj.set_form_item("plot")
  8452. try:
  8453. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8454. obj.ui.plot_cb.setDisabled(False)
  8455. except AttributeError:
  8456. pass
  8457. obj.options.set_change_callback(obj.on_options_change)
  8458. try:
  8459. self.delete_selection_shape()
  8460. except Exception as e:
  8461. log.debug("App.disable_plots() --> %s" % str(e))
  8462. # self.plots_updated.emit()
  8463. def worker_task(objs):
  8464. with self.proc_container.new(_("Disabling plots ...")):
  8465. for plot_obj in objs:
  8466. # obj.options['plot'] = True
  8467. if isinstance(plot_obj, CNCJobObject):
  8468. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8469. else:
  8470. plot_obj.plot(visible=False)
  8471. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8472. def toggle_plots(self, objects):
  8473. """
  8474. Toggle plots visibility
  8475. :param objects: list of Objects for which to be toggled the visibility
  8476. :return: None
  8477. """
  8478. # if no objects selected then do nothing
  8479. if not self.collection.get_selected():
  8480. return
  8481. log.debug("Toggling plots ...")
  8482. self.inform.emit(_("Working ..."))
  8483. for obj in objects:
  8484. if obj.options['plot'] is False:
  8485. obj.options['plot'] = True
  8486. else:
  8487. obj.options['plot'] = False
  8488. self.plots_updated.emit()
  8489. def clear_plots(self):
  8490. """
  8491. Clear the plots
  8492. :return: None
  8493. """
  8494. objects = self.collection.get_list()
  8495. for obj in objects:
  8496. obj.clear(obj == objects[-1])
  8497. # Clear pool to free memory
  8498. self.clear_pool()
  8499. def on_set_color_action_triggered(self):
  8500. """
  8501. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8502. :return:
  8503. """
  8504. new_color = self.defaults['gerber_plot_fill']
  8505. clicked_action = self.sender()
  8506. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8507. act_name = clicked_action.text()
  8508. sel_obj_list = self.collection.get_selected()
  8509. if not sel_obj_list:
  8510. return
  8511. # a default value, I just chose this one
  8512. alpha_level = 'BF'
  8513. for sel_obj in sel_obj_list:
  8514. if sel_obj.kind == 'excellon':
  8515. alpha_level = self.defaults["excellon_plot_fill"][7:]
  8516. elif sel_obj.kind == 'gerber':
  8517. alpha_level = self.defaults["gerber_plot_fill"][7:]
  8518. elif sel_obj.kind == 'geometry':
  8519. alpha_level = 'FF'
  8520. else:
  8521. log.debug(
  8522. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8523. continue
  8524. sel_obj.alpha_level = alpha_level
  8525. if act_name == _('Red'):
  8526. new_color = '#FF0000' + alpha_level
  8527. if act_name == _('Blue'):
  8528. new_color = '#0000FF' + alpha_level
  8529. if act_name == _('Yellow'):
  8530. new_color = '#FFDF00' + alpha_level
  8531. if act_name == _('Green'):
  8532. new_color = '#00FF00' + alpha_level
  8533. if act_name == _('Purple'):
  8534. new_color = '#FF00FF' + alpha_level
  8535. if act_name == _('Brown'):
  8536. new_color = '#A52A2A' + alpha_level
  8537. if act_name == _('White'):
  8538. new_color = '#FFFFFF' + alpha_level
  8539. if act_name == _('Black'):
  8540. new_color = '#000000' + alpha_level
  8541. if act_name == _('Custom'):
  8542. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8543. c_dialog = QtWidgets.QColorDialog()
  8544. plot_fill_color = c_dialog.getColor(initial=new_color)
  8545. if plot_fill_color.isValid() is False:
  8546. return
  8547. new_color = str(plot_fill_color.name()) + alpha_level
  8548. if act_name == _("Default"):
  8549. for sel_obj in sel_obj_list:
  8550. if sel_obj.kind == 'excellon':
  8551. new_color = self.defaults['excellon_plot_fill']
  8552. new_line_color = self.defaults['excellon_plot_line']
  8553. elif sel_obj.kind == 'gerber':
  8554. new_color = self.defaults['gerber_plot_fill']
  8555. new_line_color = self.defaults['gerber_plot_line']
  8556. elif sel_obj.kind == 'geometry':
  8557. new_color = self.defaults['geometry_plot_line']
  8558. new_line_color = self.defaults['geometry_plot_line']
  8559. else:
  8560. log.debug(
  8561. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8562. continue
  8563. sel_obj.fill_color = new_color
  8564. sel_obj.outline_color = new_line_color
  8565. sel_obj.shapes.redraw(
  8566. update_colors=(new_color, new_line_color)
  8567. )
  8568. return
  8569. if act_name == _("Opacity"):
  8570. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8571. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8572. if ok_button:
  8573. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8574. for sel_obj in sel_obj_list:
  8575. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8576. sel_obj.shapes.redraw(
  8577. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8578. )
  8579. return
  8580. new_line_color = color_variant(new_color[:7], 0.7)
  8581. if act_name == _("White"):
  8582. new_line_color = color_variant("#dedede", 0.7)
  8583. for sel_obj in sel_obj_list:
  8584. sel_obj.fill_color = new_color
  8585. sel_obj.outline_color = new_line_color
  8586. sel_obj.shapes.redraw(
  8587. update_colors=(new_color, new_line_color)
  8588. )
  8589. def generate_cnc_job(self, objects):
  8590. """
  8591. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8592. :param objects: Selected objects in the Project Tab
  8593. :return:
  8594. """
  8595. self.defaults.report_usage("generate_cnc_job()")
  8596. # for obj in objects:
  8597. # obj.generatecncjob()
  8598. for obj in objects:
  8599. obj.on_generatecnc_button_click()
  8600. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8601. """
  8602. Saves the current project to the specified file.
  8603. :param filename: Name of the file in which to save.
  8604. :type filename: str
  8605. :param quit_action: if the project saving will be followed by an app quit; boolean
  8606. :param silent: if True will not display status messages
  8607. :param from_tcl True is run from Tcl Shell
  8608. :return: None
  8609. """
  8610. self.log.debug("save_project()")
  8611. self.save_in_progress = True
  8612. with self.proc_container.new(_("Saving FlatCAM Project")):
  8613. # Capture the latest changes
  8614. # Current object
  8615. try:
  8616. current_object = self.collection.get_active()
  8617. if current_object:
  8618. current_object.read_form()
  8619. except Exception as e:
  8620. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8621. pass
  8622. # Serialize the whole project
  8623. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8624. "options": self.options,
  8625. "version": self.version}
  8626. if self.defaults["global_save_compressed"] is True:
  8627. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8628. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8629. # # Write
  8630. f.write(g)
  8631. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8632. else:
  8633. # Open file
  8634. try:
  8635. f = open(filename, 'w')
  8636. except IOError:
  8637. App.log.error("Failed to open file for saving: %s", filename)
  8638. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8639. return
  8640. # Write
  8641. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8642. f.close()
  8643. # verification of the saved project
  8644. # Open and parse
  8645. try:
  8646. saved_f = open(filename, 'r')
  8647. except IOError:
  8648. if silent is False:
  8649. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8650. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8651. return
  8652. try:
  8653. saved_d = json.load(saved_f, object_hook=dict2obj)
  8654. except Exception:
  8655. if silent is False:
  8656. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8657. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8658. f.close()
  8659. return
  8660. saved_f.close()
  8661. if silent is False:
  8662. if 'version' in saved_d:
  8663. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8664. else:
  8665. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8666. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8667. tb_settings = QSettings("Open Source", "FlatCAM")
  8668. lock_state = self.ui.lock_action.isChecked()
  8669. tb_settings.setValue('toolbar_lock', lock_state)
  8670. # This will write the setting to the platform specific storage.
  8671. del tb_settings
  8672. # if quit:
  8673. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8674. # t.start()
  8675. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8676. def start_delayed_quit(self, delay, filename, should_quit=None):
  8677. """
  8678. :param delay: period of checking if project file size is more than zero; in seconds
  8679. :param filename: the name of the project file to be checked periodically for size more than zero
  8680. :param should_quit: if the task finished will be followed by an app quit; boolean
  8681. :return:
  8682. """
  8683. to_quit = should_quit
  8684. self.save_timer = QtCore.QTimer()
  8685. self.save_timer.setInterval(delay)
  8686. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8687. self.save_timer.start()
  8688. def check_project_file_size(self, filename, should_quit=None):
  8689. """
  8690. :param filename: the name of the project file to be checked periodically for size more than zero
  8691. :param should_quit: will quit the app if True; boolean
  8692. :return:
  8693. """
  8694. try:
  8695. if os.stat(filename).st_size > 0:
  8696. self.save_in_progress = False
  8697. self.save_timer.stop()
  8698. if should_quit:
  8699. self.app_quit.emit()
  8700. except Exception:
  8701. traceback.print_exc()
  8702. def save_project_auto(self):
  8703. """
  8704. Called periodically to save the project.
  8705. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  8706. # progress.
  8707. :return:
  8708. """
  8709. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8710. self.on_file_saveproject()
  8711. def save_project_auto_update(self):
  8712. """
  8713. Update the auto save time interval value.
  8714. :return:
  8715. """
  8716. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8717. try:
  8718. if self.autosave_timer.isActive():
  8719. self.autosave_timer.stop()
  8720. except Exception:
  8721. pass
  8722. if self.defaults['global_autosave'] is True:
  8723. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8724. self.autosave_timer.start()
  8725. def on_options_app2project(self):
  8726. """
  8727. Callback for Options->Transfer Options->App=>Project. Copies options
  8728. from application defaults to project defaults.
  8729. :return: None
  8730. """
  8731. self.defaults.report_usage("on_options_app2project")
  8732. self.preferencesUiManager.defaults_read_form()
  8733. self.options.update(self.defaults)
  8734. def toggle_shell(self):
  8735. """
  8736. Toggle shell: if is visible close it, if it is closed then open it
  8737. :return: None
  8738. """
  8739. self.defaults.report_usage("toggle_shell()")
  8740. if self.ui.shell_dock.isVisible():
  8741. self.ui.shell_dock.hide()
  8742. self.plotcanvas.native.setFocus()
  8743. else:
  8744. self.ui.shell_dock.show()
  8745. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8746. # self.shell._edit.setFocus()
  8747. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8748. # HACK - simulate a mouse click - alternative
  8749. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8750. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8751. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8752. # no_km)
  8753. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8754. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8755. # no_km)
  8756. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8757. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8758. """
  8759. Shows a message on the FlatCAM Shell
  8760. :param msg: Message to display.
  8761. :param show: Opens the shell.
  8762. :param error: Shows the message as an error.
  8763. :param warning: Shows the message as an warning.
  8764. :param success: Shows the message as an success.
  8765. :param selected: Indicate that something was selected on canvas
  8766. :return: None
  8767. """
  8768. if show:
  8769. self.ui.shell_dock.show()
  8770. try:
  8771. if error:
  8772. self.shell.append_error(msg + "\n")
  8773. elif warning:
  8774. self.shell.append_warning(msg + "\n")
  8775. elif success:
  8776. self.shell.append_success(msg + "\n")
  8777. elif selected:
  8778. self.shell.append_selected(msg + "\n")
  8779. else:
  8780. self.shell.append_output(msg + "\n")
  8781. except AttributeError:
  8782. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8783. class ArgsThread(QtCore.QObject):
  8784. open_signal = pyqtSignal(list)
  8785. start = pyqtSignal()
  8786. stop = pyqtSignal()
  8787. if sys.platform == 'win32':
  8788. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8789. else:
  8790. address = ('/tmp/testipc', 'AF_UNIX')
  8791. def __init__(self):
  8792. super(ArgsThread, self).__init__()
  8793. self.listener = None
  8794. self.thread_exit = False
  8795. self.start.connect(self.run)
  8796. self.stop.connect(self.close_listener)
  8797. def my_loop(self, address):
  8798. try:
  8799. self.listener = Listener(*address)
  8800. while self.thread_exit is False:
  8801. conn = self.listener.accept()
  8802. self.serve(conn)
  8803. except socket.error:
  8804. try:
  8805. conn = Client(*address)
  8806. conn.send(sys.argv)
  8807. conn.send('close')
  8808. # close the current instance only if there are args
  8809. if len(sys.argv) > 1:
  8810. try:
  8811. self.listener.close()
  8812. except Exception:
  8813. pass
  8814. sys.exit()
  8815. except ConnectionRefusedError:
  8816. if sys.platform == 'win32':
  8817. pass
  8818. else:
  8819. os.system('rm /tmp/testipc')
  8820. self.listener = Listener(*address)
  8821. while True:
  8822. conn = self.listener.accept()
  8823. self.serve(conn)
  8824. def serve(self, conn):
  8825. while self.thread_exit is False:
  8826. msg = conn.recv()
  8827. if msg == 'close':
  8828. break
  8829. self.open_signal.emit(msg)
  8830. conn.close()
  8831. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8832. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8833. @pyqtSlot()
  8834. def run(self):
  8835. self.my_loop(self.address)
  8836. @pyqtSlot()
  8837. def close_listener(self):
  8838. self.thread_exit = True
  8839. self.listener.close()
  8840. # end of file