FlatCAMApp.py 478 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809
  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 shapely.geometry import Point, MultiPolygon
  21. from io import StringIO
  22. from reportlab.graphics import renderPDF
  23. from reportlab.pdfgen import canvas
  24. from reportlab.lib.units import inch, mm
  25. from reportlab.lib.pagesizes import landscape, portrait
  26. from svglib.svglib import svg2rlg
  27. import gc
  28. from xml.dom.minidom import parseString as parse_xml_string
  29. from multiprocessing.connection import Listener, Client
  30. from multiprocessing import Pool
  31. import socket
  32. # ####################################################################################################################
  33. # ################################### Imports part of FlatCAM #############################################
  34. # ####################################################################################################################
  35. # Diverse
  36. from FlatCAMCommon import LoudDict, color_variant
  37. from FlatCAMBookmark import BookmarkManager
  38. from FlatCAMDB import ToolsDB2
  39. from vispy.gloo.util import _screenshot
  40. from vispy.io import write_png
  41. # FlatCAM Objects
  42. from defaults import FlatCAMDefaults
  43. from flatcamObjects.ObjectCollection import *
  44. from flatcamObjects.FlatCAMObj import FlatCAMObj
  45. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  46. from flatcamObjects.FlatCAMDocument import DocumentObject
  47. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  48. from flatcamObjects.FlatCAMGeometry import GeometryObject
  49. from flatcamObjects.FlatCAMGerber import GerberObject
  50. from flatcamObjects.FlatCAMScript import ScriptObject
  51. # FlatCAM Parsing files
  52. from flatcamParsers.ParseExcellon import Excellon
  53. from flatcamParsers.ParseGerber import Gerber
  54. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  55. # FlatCAM GUI
  56. from flatcamGUI.PlotCanvas import *
  57. from flatcamGUI.PlotCanvasLegacy import *
  58. from flatcamGUI.FlatCAMGUI import *
  59. from flatcamGUI.GUIElements import FCFileSaveDialog
  60. # FlatCAM Pre-processors
  61. from FlatCAMPostProc import load_preprocessors
  62. # FlatCAM Editors
  63. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  64. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  65. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  66. from flatcamEditors.FlatCAMTextEditor import TextEditor
  67. from flatcamParsers.ParseHPGL2 import HPGL2
  68. # FlatCAM Workers
  69. from FlatCAMProcess import *
  70. from FlatCAMWorkerStack import WorkerStack
  71. # FlatCAM Tools
  72. from flatcamTools import *
  73. # FlatCAM Translation
  74. import gettext
  75. import FlatCAMTranslation as fcTranslate
  76. import builtins
  77. if sys.platform == 'win32':
  78. import winreg
  79. fcTranslate.apply_language('strings')
  80. if '_' not in builtins.__dict__:
  81. _ = gettext.gettext
  82. class App(QtCore.QObject):
  83. """
  84. The main application class. The constructor starts the GUI.
  85. """
  86. # ###############################################################################################################
  87. # ########################################## App ################################################################
  88. # ###############################################################################################################
  89. # ###############################################################################################################
  90. # ######################################### LOGGING #############################################################
  91. # ###############################################################################################################
  92. log = logging.getLogger('base')
  93. log.setLevel(logging.DEBUG)
  94. # log.setLevel(logging.WARNING)
  95. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  96. handler = logging.StreamHandler()
  97. handler.setFormatter(formatter)
  98. log.addHandler(handler)
  99. # ###############################################################################################################
  100. # #################################### Get Cmd Line Options #####################################################
  101. # ###############################################################################################################
  102. cmd_line_shellfile = ''
  103. cmd_line_shellvar = ''
  104. cmd_line_headless = None
  105. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  106. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  107. "FlatCam.py --headless=1"
  108. try:
  109. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  110. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  111. "shellvar=",
  112. "headless=",
  113. "multiprocessing-fork="])
  114. except getopt.GetoptError:
  115. print(cmd_line_help)
  116. sys.exit(2)
  117. for opt, arg in cmd_line_options:
  118. if opt == '-h':
  119. print(cmd_line_help)
  120. sys.exit()
  121. elif opt == '--shellfile':
  122. cmd_line_shellfile = arg
  123. elif opt == '--shellvar':
  124. cmd_line_shellvar = arg
  125. elif opt == '--headless':
  126. try:
  127. cmd_line_headless = eval(arg)
  128. except NameError:
  129. pass
  130. # ###############################################################################################################
  131. # ################################### Version and VERSION DATE ##################################################
  132. # ###############################################################################################################
  133. version = 8.992
  134. version_date = "2020/05/01"
  135. beta = True
  136. engine = '3D'
  137. # current date now
  138. date = str(datetime.today()).rpartition('.')[0]
  139. date = ''.join(c for c in date if c not in ':-')
  140. date = date.replace(' ', '_')
  141. # ###############################################################################################################
  142. # ############################################ URLS's ###########################################################
  143. # ###############################################################################################################
  144. # URL for update checks and statistics
  145. version_url = "http://flatcam.org/version"
  146. # App URL
  147. app_url = "http://flatcam.org"
  148. # Manual URL
  149. manual_url = "http://flatcam.org/manual/index.html"
  150. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  151. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  152. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  153. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  154. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  155. # this variable will hold the project status
  156. # if True it will mean that the project was modified and not saved
  157. should_we_save = False
  158. # flag is True if saving action has been triggered
  159. save_in_progress = False
  160. # ###############################################################################################################
  161. # ####################################### APP Signals ######################################################
  162. # ###############################################################################################################
  163. # Inform the user
  164. # Handled by:
  165. # * App.info() --> Print on the status bar
  166. inform = QtCore.pyqtSignal(str)
  167. app_quit = QtCore.pyqtSignal()
  168. # General purpose background task
  169. worker_task = QtCore.pyqtSignal(dict)
  170. # File opened
  171. # Handled by:
  172. # * register_folder()
  173. # * register_recent()
  174. # Note: Setting the parameters to unicode does not seem
  175. # to have an effect. Then are received as Qstring
  176. # anyway.
  177. # File type and filename
  178. file_opened = QtCore.pyqtSignal(str, str)
  179. # File type and filename
  180. file_saved = QtCore.pyqtSignal(str, str)
  181. # Percentage of progress
  182. progress = QtCore.pyqtSignal(int)
  183. plots_updated = QtCore.pyqtSignal()
  184. # Emitted by new_object() and passes the new object as argument, plot flag.
  185. # on_object_created() adds the object to the collection, plots on appropriate flag
  186. # and emits new_object_available.
  187. object_created = QtCore.pyqtSignal(object, bool, bool)
  188. # Emitted when a object has been changed (like scaled, mirrored)
  189. object_changed = QtCore.pyqtSignal(object)
  190. # Emitted after object has been plotted.
  191. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  192. object_plotted = QtCore.pyqtSignal(object)
  193. # Emitted when a new object has been added or deleted from/to the collection
  194. object_status_changed = QtCore.pyqtSignal(object, str, str)
  195. message = QtCore.pyqtSignal(str, str, str)
  196. # Emmited when shell command is finished(one command only)
  197. shell_command_finished = QtCore.pyqtSignal(object)
  198. # Emitted when multiprocess pool has been recreated
  199. pool_recreated = QtCore.pyqtSignal(object)
  200. # Emitted when an unhandled exception happens
  201. # in the worker task.
  202. thread_exception = QtCore.pyqtSignal(object)
  203. # used to signal that there are arguments for the app
  204. args_at_startup = QtCore.pyqtSignal(list)
  205. # a reusable signal to replot a list of objects
  206. # should be disconnected after use so it can be reused
  207. replot_signal = pyqtSignal(list)
  208. # signal emitted when jumping
  209. jump_signal = pyqtSignal(tuple)
  210. # signal emitted when jumping
  211. locate_signal = pyqtSignal(tuple, str)
  212. # close app signal
  213. close_app_signal = pyqtSignal()
  214. # will perform the cleanup operation after a Graceful Exit
  215. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  216. # graphic residues behind
  217. cleanup = pyqtSignal()
  218. def __init__(self, user_defaults=True):
  219. """
  220. Starts the application.
  221. :return: app
  222. :rtype: App
  223. """
  224. App.log.info("FlatCAM Starting...")
  225. self.main_thread = QtWidgets.QApplication.instance().thread()
  226. # ############################################################################################################
  227. # ################# Setup the listening thread for another instance launching with args ######################
  228. # ############################################################################################################
  229. if sys.platform == 'win32' or sys.platform == 'linux':
  230. # make sure the thread is stored by using a self. otherwise it's garbage collected
  231. self.th = QtCore.QThread()
  232. self.th.start(priority=QtCore.QThread.LowestPriority)
  233. self.new_launch = ArgsThread()
  234. self.new_launch.open_signal[list].connect(self.on_startup_args)
  235. self.new_launch.moveToThread(self.th)
  236. self.new_launch.start.emit()
  237. # ############################################################################################################
  238. # # ######################################## OS-specific #####################################################
  239. # ############################################################################################################
  240. portable = False
  241. # Folder for user settings.
  242. if sys.platform == 'win32':
  243. from win32comext.shell import shell, shellcon
  244. if platform.architecture()[0] == '32bit':
  245. App.log.debug("Win32!")
  246. else:
  247. App.log.debug("Win64!")
  248. # #######################################################################################################
  249. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  250. # #######################################################################################################
  251. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  252. try:
  253. with open(config_file, 'r'):
  254. pass
  255. except FileNotFoundError:
  256. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  257. try:
  258. with open(config_file, 'r') as f:
  259. try:
  260. for line in f:
  261. param = str(line).replace('\n', '').rpartition('=')
  262. if param[0] == 'portable':
  263. try:
  264. portable = eval(param[2])
  265. except NameError:
  266. portable = False
  267. if param[0] == 'headless':
  268. if param[2].lower() == 'true':
  269. self.cmd_line_headless = 1
  270. else:
  271. self.cmd_line_headless = None
  272. except Exception as e:
  273. log.debug('App.__init__() -->%s' % str(e))
  274. return
  275. except FileNotFoundError as e:
  276. log.debug(str(e))
  277. pass
  278. if portable is False:
  279. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  280. else:
  281. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  282. self.os = 'windows'
  283. else: # Linux/Unix/MacOS
  284. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  285. self.os = 'unix'
  286. # ############################################################################################################
  287. # ################################# Setup folders and files ##################################################
  288. # ############################################################################################################
  289. if not os.path.exists(self.data_path):
  290. os.makedirs(self.data_path)
  291. App.log.debug('Created data folder: ' + self.data_path)
  292. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  293. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  294. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  295. if not os.path.exists(self.preprocessorpaths):
  296. os.makedirs(self.preprocessorpaths)
  297. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  298. # create geo_tools_db.FlatDB file if there is none
  299. try:
  300. f = open(self.data_path + '/geo_tools_db.FlatDB')
  301. f.close()
  302. except IOError:
  303. App.log.debug('Creating empty geo_tool_db.FlatDB')
  304. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  305. json.dump({}, f)
  306. f.close()
  307. # create current_defaults.FlatConfig file if there is none
  308. try:
  309. f = open(self.data_path + '/current_defaults.FlatConfig')
  310. f.close()
  311. except IOError:
  312. App.log.debug('Creating empty current_defaults.FlatConfig')
  313. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  314. json.dump({}, f)
  315. f.close()
  316. # Write factory_defaults.FlatConfig file to disk
  317. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  318. # create a recent files json file if there is none
  319. try:
  320. f = open(self.data_path + '/recent.json')
  321. f.close()
  322. except IOError:
  323. App.log.debug('Creating empty recent.json')
  324. f = open(self.data_path + '/recent.json', 'w')
  325. json.dump([], f)
  326. f.close()
  327. # create a recent projects json file if there is none
  328. try:
  329. fp = open(self.data_path + '/recent_projects.json')
  330. fp.close()
  331. except IOError:
  332. App.log.debug('Creating empty recent_projects.json')
  333. fp = open(self.data_path + '/recent_projects.json', 'w')
  334. json.dump([], fp)
  335. fp.close()
  336. # Application directory. CHDIR to it. Otherwise, trying to load
  337. # GUI icons will fail as their path is relative.
  338. # This will fail under cx_freeze ...
  339. self.app_home = os.path.dirname(os.path.realpath(__file__))
  340. App.log.debug("Application path is " + self.app_home)
  341. App.log.debug("Started in " + os.getcwd())
  342. # cx_freeze workaround
  343. if os.path.isfile(self.app_home):
  344. self.app_home = os.path.dirname(self.app_home)
  345. os.chdir(self.app_home)
  346. # ############################################################################################################
  347. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  348. # ############################################################################################################
  349. self.defaults = FlatCAMDefaults()
  350. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  351. if user_defaults:
  352. self.defaults.load(filename=current_defaults_path)
  353. if self.defaults["global_gray_icons"] is False:
  354. self.resource_location = 'share'
  355. else:
  356. self.resource_location = 'share/dark_resources'
  357. if self.defaults['units'] == 'MM':
  358. self.decimals = int(self.defaults['decimals_metric'])
  359. else:
  360. self.decimals = int(self.defaults['decimals_inch'])
  361. self.current_units = self.defaults['units']
  362. # ###########################################################################################################
  363. # #################################### SETUP OBJECT CLASSES #################################################
  364. # ###########################################################################################################
  365. self.setup_obj_classes()
  366. # ###########################################################################################################
  367. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  368. # ###########################################################################################################
  369. self.pool = Pool()
  370. # ###########################################################################################################
  371. # ###################################### Setting the Splash Screen ##########################################
  372. # ###########################################################################################################
  373. splash_settings = QSettings("Open Source", "FlatCAM")
  374. if splash_settings.contains("splash_screen"):
  375. show_splash = splash_settings.value("splash_screen")
  376. else:
  377. splash_settings.setValue('splash_screen', 1)
  378. # This will write the setting to the platform specific storage.
  379. del splash_settings
  380. show_splash = 1
  381. if show_splash and self.cmd_line_headless != 1:
  382. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  383. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  384. # self.splash.setMask(splash_pix.mask())
  385. # move splashscreen to the current monitor
  386. desktop = QtWidgets.QApplication.desktop()
  387. screen = desktop.screenNumber(QtGui.QCursor.pos())
  388. current_screen_center = desktop.availableGeometry(screen).center()
  389. self.splash.move(current_screen_center - self.splash.rect().center())
  390. self.splash.show()
  391. self.splash.showMessage(_("FlatCAM is initializing ..."),
  392. alignment=Qt.AlignBottom | Qt.AlignLeft,
  393. color=QtGui.QColor("gray"))
  394. else:
  395. show_splash = 0
  396. # ###########################################################################################################
  397. # ######################################### Initialize GUI ##################################################
  398. # ###########################################################################################################
  399. # FlatCAM colors used in plotting
  400. self.FC_light_green = '#BBF268BF'
  401. self.FC_dark_green = '#006E20BF'
  402. self.FC_light_blue = '#a5a5ffbf'
  403. self.FC_dark_blue = '#0000ffbf'
  404. QtCore.QObject.__init__(self)
  405. self.ui = FlatCAMGUI(self)
  406. self.on_grid_snap_triggered(state=True)
  407. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  408. if theme_settings.contains("theme"):
  409. theme = theme_settings.value('theme', type=str)
  410. else:
  411. theme = 'white'
  412. if self.defaults["global_cursor_color_enabled"]:
  413. self.cursor_color_3D = self.defaults["global_cursor_color"]
  414. else:
  415. if theme == 'white':
  416. self.cursor_color_3D = 'black'
  417. else:
  418. self.cursor_color_3D = 'gray'
  419. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  420. self.ui.final_save.connect(self.final_save)
  421. # restore the toolbar view
  422. self.restore_toolbar_view()
  423. # restore the GUI geometry
  424. self.restore_main_win_geom()
  425. # set FlatCAM units in the Status bar
  426. self.set_screen_units(self.defaults['units'])
  427. # ###########################################################################################################
  428. # ########################################### AUTOSAVE SETUP ################################################
  429. # ###########################################################################################################
  430. self.block_autosave = False
  431. self.autosave_timer = QtCore.QTimer(self)
  432. self.save_project_auto_update()
  433. self.autosave_timer.timeout.connect(self.save_project_auto)
  434. # ###########################################################################################################
  435. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  436. # ###########################################################################################################
  437. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  438. inform=self.inform, app=self)
  439. self.preferencesUiManager.defaults_write_form()
  440. # When the self.defaults dictionary changes will update the Preferences GUI forms
  441. self.defaults.set_change_callback(self.on_defaults_dict_change)
  442. # ###########################################################################################################
  443. # ##################################### FIRST RUN SECTION ###################################################
  444. # ################################ It's done only once after install #####################################
  445. # ###########################################################################################################
  446. if self.defaults["first_run"] is True:
  447. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  448. initial_lay = 'compact'
  449. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  450. # Set the combobox in Preferences to the current layout
  451. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  452. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  453. # after the first run, this object should be False
  454. self.defaults["first_run"] = False
  455. self.preferencesUiManager.save_defaults(silent=True)
  456. # ###########################################################################################################
  457. # ############################################ Data #########################################################
  458. # ###########################################################################################################
  459. self.recent = []
  460. self.recent_projects = []
  461. self.clipboard = QtWidgets.QApplication.clipboard()
  462. self.project_filename = None
  463. self.toggle_units_ignore = False
  464. # ###########################################################################################################
  465. # #################################### LOAD PREPROCESSORS ###################################################
  466. # ###########################################################################################################
  467. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  468. # the preprocessor file
  469. self.preprocessors = load_preprocessors(self)
  470. # make sure that always the 'default' preprocessor is the first item in the dictionary
  471. if 'default' in self.preprocessors.keys():
  472. new_ppp_dict = {}
  473. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  474. default_pp = self.preprocessors.pop('default')
  475. new_ppp_dict['default'] = default_pp
  476. # then add the rest of the keys
  477. for name, val_class in self.preprocessors.items():
  478. new_ppp_dict[name] = val_class
  479. # and now put back the ordered dict with 'default' key first
  480. self.preprocessors = new_ppp_dict
  481. for name in list(self.preprocessors.keys()):
  482. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  483. if name.partition('_')[0] == 'Paste':
  484. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  485. continue
  486. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  487. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  488. if name == 'hpgl':
  489. continue
  490. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  491. # ###########################################################################################################
  492. # ########################################## LOAD LANGUAGES ################################################
  493. # ###########################################################################################################
  494. self.languages = fcTranslate.load_languages()
  495. for name in sorted(self.languages.values()):
  496. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  497. # ###########################################################################################################
  498. # ####################################### APPLY APP LANGUAGE ################################################
  499. # ###########################################################################################################
  500. ret_val = fcTranslate.apply_language('strings')
  501. if ret_val == "no language":
  502. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  503. log.debug("Could not find the Language files. The App strings are missing.")
  504. else:
  505. # make the current language the current selection on the language combobox
  506. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  507. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  508. # ###########################################################################################################
  509. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  510. # ###########################################################################################################
  511. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  512. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  513. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  514. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  515. self.defaults.propagate_defaults()
  516. # ###########################################################################################################
  517. # ######################################## UPDATE THE OPTIONS ###############################################
  518. # ###########################################################################################################
  519. self.options = LoudDict()
  520. # -----------------------------------------------------------------------------------------------------------
  521. # Update the self.options from the self.defaults
  522. # The self.defaults holds the application defaults while the self.options holds the object defaults
  523. # -----------------------------------------------------------------------------------------------------------
  524. # Copy app defaults to project options
  525. for def_key, def_val in self.defaults.items():
  526. self.options[def_key] = deepcopy(def_val)
  527. self.preferencesUiManager.show_preferences_gui()
  528. # ### End of Data ####
  529. # ###########################################################################################################
  530. # #################################### SETUP OBJECT COLLECTION ##############################################
  531. # ###########################################################################################################
  532. self.collection = ObjectCollection(self)
  533. self.ui.project_tab_layout.addWidget(self.collection.view)
  534. # ### Adjust tabs width ## ##
  535. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  536. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  537. self.collection.view.setMinimumWidth(290)
  538. self.log.debug("Finished creating Object Collection.")
  539. # ###########################################################################################################
  540. # ######################################## SETUP Plot Area ##################################################
  541. # ###########################################################################################################
  542. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  543. if self.defaults["global_graphic_engine"] == '3D':
  544. self.is_legacy = False
  545. else:
  546. self.is_legacy = True
  547. # Event signals disconnect id holders
  548. self.mp = None
  549. self.mm = None
  550. self.mr = None
  551. self.mdc = None
  552. self.mp_zc = None
  553. self.kp = None
  554. # Matplotlib axis
  555. self.axes = None
  556. if show_splash:
  557. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  558. "Canvas initialization started."),
  559. alignment=Qt.AlignBottom | Qt.AlignLeft,
  560. color=QtGui.QColor("gray"))
  561. start_plot_time = time.time() # debug
  562. self.plotcanvas = None
  563. self.app_cursor = None
  564. self.hover_shapes = None
  565. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  566. # setup the PlotCanvas
  567. self.on_plotcanvas_setup()
  568. end_plot_time = time.time()
  569. self.used_time = end_plot_time - start_plot_time
  570. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  571. if show_splash:
  572. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  573. "Canvas initialization started.\n"
  574. "Canvas initialization finished in"), '%.2f' % self.used_time),
  575. alignment=Qt.AlignBottom | Qt.AlignLeft,
  576. color=QtGui.QColor("gray"))
  577. self.ui.splitter.setStretchFactor(1, 2)
  578. # ###########################################################################################################
  579. # ############################################### SYS TRAY ##################################################
  580. # ###########################################################################################################
  581. if self.defaults["global_systray_icon"]:
  582. self.parent_w = QtWidgets.QWidget()
  583. if self.cmd_line_headless == 1:
  584. self.trayIcon = FlatCAMSystemTray(app=self,
  585. icon=QtGui.QIcon(self.resource_location +
  586. '/flatcam_icon32_green.png'),
  587. headless=True,
  588. parent=self.parent_w)
  589. else:
  590. self.trayIcon = FlatCAMSystemTray(app=self,
  591. icon=QtGui.QIcon(self.resource_location +
  592. '/flatcam_icon32_green.png'),
  593. parent=self.parent_w)
  594. # ###########################################################################################################
  595. # ############################################### Worker SETUP ##############################################
  596. # ###########################################################################################################
  597. if self.defaults["global_worker_number"]:
  598. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  599. else:
  600. self.workers = WorkerStack(workers_number=2)
  601. self.worker_task.connect(self.workers.add_task)
  602. self.log.debug("Finished creating Workers crew.")
  603. # ###########################################################################################################
  604. # ############################################# Activity Monitor ###########################################
  605. # ###########################################################################################################
  606. self.activity_view = FlatCAMActivityView(app=self)
  607. self.ui.infobar.addWidget(self.activity_view)
  608. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  609. # ###########################################################################################################
  610. # ############################################# Signal handling #############################################
  611. # ###########################################################################################################
  612. # ########################################## Custom signals ################################################
  613. # signal for displaying messages in status bar
  614. self.inform.connect(self.info)
  615. # signal to be called when the app is quiting
  616. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  617. self.message.connect(self.message_dialog)
  618. # self.progress.connect(self.set_progress_bar)
  619. # signals that are emitted when object state changes
  620. self.object_created.connect(self.on_object_created)
  621. self.object_changed.connect(self.on_object_changed)
  622. self.object_plotted.connect(self.on_object_plotted)
  623. self.plots_updated.connect(self.on_plots_updated)
  624. # signals emitted when file state change
  625. self.file_opened.connect(self.register_recent)
  626. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  627. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  628. # ########################################## Standard signals ###############################################
  629. # ### Menu
  630. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  631. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  632. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  633. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  634. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  635. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  636. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  637. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  638. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  639. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  640. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  641. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  642. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  643. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  644. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  645. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  646. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  647. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  648. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  649. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  650. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  651. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  652. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  653. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  654. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  655. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  656. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  657. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  658. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  659. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  660. self.ui.menufile_exit.triggered.connect(self.final_save)
  661. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  662. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  663. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  664. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  665. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  666. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  667. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  668. self.ui.menueditdelete.triggered.connect(self.on_delete)
  669. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  670. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  671. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  672. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  673. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  674. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  675. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  676. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  677. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  678. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  679. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  680. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  681. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  682. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  683. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  684. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  685. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  686. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  687. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  688. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  689. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  690. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  691. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  692. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  693. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  694. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  695. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  696. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  697. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  698. self.ui.menuview_replot.triggered.connect(self.plot_all)
  699. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  700. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  701. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  702. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  703. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  704. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  705. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  706. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  707. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  708. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  709. self.ui.menuhelp_about.triggered.connect(self.on_about)
  710. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  711. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  712. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  713. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  714. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  715. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  716. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  717. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  718. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  719. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  720. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  721. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  722. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  723. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  724. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  725. # ToolBar signals
  726. self.connect_toolbar_signals()
  727. # Notebook and Plot Tab Area signals
  728. # make the right click on the notebook tab and plot tab area tab raise a menu
  729. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  730. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  731. self.on_tab_setup_context_menu()
  732. # activate initial state
  733. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  734. # Context Menu
  735. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  736. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  737. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  738. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  739. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  740. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  741. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  742. self.ui.clearplot.triggered.connect(self.clear_plots)
  743. self.ui.replot.triggered.connect(self.plot_all)
  744. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  745. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  746. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  747. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  748. self.ui.popmenu_move.triggered.connect(self.obj_move)
  749. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  750. # Project Context Menu -> Color Setting
  751. for act in self.ui.menuprojectcolor.actions():
  752. act.triggered.connect(self.on_set_color_action_triggered)
  753. # ###########################################################################################################
  754. # #################################### GUI PREFERENCES SIGNALS ##############################################
  755. # ###########################################################################################################
  756. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  757. lambda: self.on_toggle_units(no_pref=False))
  758. # ##################################### Workspace Setting Signals ###########################################
  759. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  760. self.on_workspace_modified)
  761. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  762. self.on_workspace_modified
  763. )
  764. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  765. # ###########################################################################################################
  766. # ######################################## GUI SETTINGS SIGNALS #############################################
  767. # ###########################################################################################################
  768. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  769. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  770. # ######################################## Tools related signals ############################################
  771. # Film Tool
  772. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  773. self.on_film_color_entry)
  774. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  775. self.on_film_color_button)
  776. # QRCode Tool
  777. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  778. self.on_qrcode_fill_color_entry)
  779. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  780. self.on_qrcode_fill_color_button)
  781. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  782. self.on_qrcode_back_color_entry)
  783. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  784. self.on_qrcode_back_color_button)
  785. # portability changed signal
  786. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  787. # Object list
  788. self.collection.view.activated.connect(self.on_row_activated)
  789. self.collection.item_selected.connect(self.on_row_selected)
  790. self.object_status_changed.connect(self.on_collection_updated)
  791. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  792. # Export Excellon parameters.
  793. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  794. self.on_update_exc_export
  795. )
  796. # call it once to make sure it is updated at startup
  797. self.on_update_exc_export(state=self.defaults["excellon_update"])
  798. # when there are arguments at application startup this get launched
  799. self.args_at_startup[list].connect(self.on_startup_args)
  800. # ###########################################################################################################
  801. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  802. # ###########################################################################################################
  803. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  804. lambda: self.restore_extensions(ext_type='excellon'))
  805. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  806. lambda: self.restore_extensions(ext_type='gcode'))
  807. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  808. lambda: self.restore_extensions(ext_type='gerber'))
  809. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  810. lambda: self.delete_all_extensions(ext_type='excellon'))
  811. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  812. lambda: self.delete_all_extensions(ext_type='gcode'))
  813. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  814. lambda: self.delete_all_extensions(ext_type='gerber'))
  815. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  816. lambda: self.add_extension(ext_type='excellon'))
  817. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  818. lambda: self.add_extension(ext_type='gcode'))
  819. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  820. lambda: self.add_extension(ext_type='gerber'))
  821. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  822. lambda: self.del_extension(ext_type='excellon'))
  823. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  824. lambda: self.del_extension(ext_type='gcode'))
  825. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  826. lambda: self.del_extension(ext_type='gerber'))
  827. # connect the 'Apply' buttons from the Preferences/File Associations
  828. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  829. lambda: self.on_register_files(obj_type='excellon'))
  830. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  831. lambda: self.on_register_files(obj_type='gcode'))
  832. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  833. lambda: self.on_register_files(obj_type='gerber'))
  834. # ###########################################################################################################
  835. # ########################################### KEYWORDS SIGNALS ##############################################
  836. # ###########################################################################################################
  837. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  838. lambda: self.restore_extensions(ext_type='keyword'))
  839. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  840. lambda: self.delete_all_extensions(ext_type='keyword'))
  841. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  842. lambda: self.add_extension(ext_type='keyword'))
  843. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  844. lambda: self.del_extension(ext_type='keyword'))
  845. # connect the abort_all_tasks related slots to the related signals
  846. self.proc_container.idle_flag.connect(self.app_is_idle)
  847. # signal emitted when a tab is closed in the Plot Area
  848. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  849. self.ui.grid_snap_btn.triggered.connect(self.on_grid_snap_triggered)
  850. self.ui.snap_infobar_label.clicked.connect(self.on_grid_icon_snap_clicked)
  851. # signal to close the application
  852. self.close_app_signal.connect(self.kill_app)
  853. # ################################# FINISHED CONNECTING SIGNALS #############################################
  854. # ###########################################################################################################
  855. # ###########################################################################################################
  856. # ###########################################################################################################
  857. self.log.debug("Finished connecting Signals.")
  858. # ###########################################################################################################
  859. # ########################################## Other setups ###################################################
  860. # ###########################################################################################################
  861. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  862. # depending on from where those tools are called different actions can be done
  863. self.call_source = 'app'
  864. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  865. self.tool_tab_locked = False
  866. # decide if to show or hide the Notebook side of the screen at startup
  867. if self.defaults["global_project_at_startup"] is True:
  868. self.ui.splitter.setSizes([1, 1])
  869. else:
  870. self.ui.splitter.setSizes([0, 1])
  871. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  872. self.setup_component_editor()
  873. # ###########################################################################################################
  874. # ####################################### Auto-complete KEYWORDS ############################################
  875. # ###########################################################################################################
  876. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  877. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  878. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  879. 'export_exc',
  880. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  881. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_sys', 'help', 'import_svg',
  882. 'interiors', 'isolate', 'join_excellon',
  883. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  884. 'mirror', 'ncc',
  885. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  886. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  887. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  888. 'save', 'save_project',
  889. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  890. 'skew', 'subtract_poly', 'subtract_rectangle',
  891. 'version', 'write_gcode'
  892. ]
  893. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  894. 'Paste_1',
  895. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  896. 'Toolchange_manual', 'True', 'Users',
  897. 'all', 'auto', 'axis',
  898. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  899. 'contour', 'default',
  900. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  901. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  902. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  903. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  904. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  905. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  906. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  907. 'spacing_columns',
  908. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  909. 'toolchange_xy', 'toolchangez', 'travelz',
  910. 'tooldia', 'use_threads', 'value',
  911. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  912. ]
  913. self.tcl_keywords = [
  914. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  915. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  916. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  917. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  918. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  919. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  920. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  921. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  922. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  923. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  924. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  925. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  926. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  927. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  928. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  929. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  930. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  931. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  932. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  933. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  934. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  935. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  936. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  937. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  938. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  939. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  940. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  941. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  942. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  943. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  944. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  945. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  946. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  947. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  948. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  949. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  950. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  951. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  952. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  953. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  954. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  955. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  956. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  957. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  958. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  959. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  960. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  961. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  962. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  963. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  964. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  965. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  966. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  967. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  968. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  969. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  970. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  971. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  972. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  973. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  974. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  975. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  976. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  977. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  978. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  979. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  980. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  981. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  982. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  983. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  984. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  985. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  986. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  987. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  988. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  989. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  990. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  991. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  992. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  993. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  994. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  995. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  996. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  997. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  998. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  999. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1000. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1001. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1002. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1003. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1004. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1005. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1006. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1007. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1008. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1009. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1010. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1011. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1012. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1013. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1014. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1015. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1016. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1017. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1018. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1019. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1020. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1021. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1022. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1023. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1024. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1025. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1026. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1027. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1028. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1029. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1030. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1031. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1032. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1033. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1034. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1035. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1036. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1037. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1038. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1039. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1040. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1041. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1042. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1043. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1044. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1045. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1046. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1047. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1048. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1049. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1050. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1051. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1052. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1053. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1054. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1055. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1056. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1057. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1058. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1059. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1060. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1061. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1062. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1063. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1064. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1065. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1066. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1067. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1068. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1069. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1070. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1071. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1072. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1073. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1074. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1075. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1076. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1077. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1078. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1079. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1080. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1081. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1082. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1083. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1084. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1085. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1086. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1087. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1088. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1089. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1090. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1091. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1092. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1093. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1094. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1095. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1096. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1097. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1098. ]
  1099. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1100. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1101. # ###########################################################################################################
  1102. # ############################################## Shell SETUP ################################################
  1103. # ###########################################################################################################
  1104. self.shell = FCShell(app=self, version=self.version)
  1105. self.ui.shell_dock.setWidget(self.shell)
  1106. self.log.debug("TCL Shell has been initialized.")
  1107. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1108. if self.defaults["global_shell_at_startup"]:
  1109. self.ui.shell_dock.show()
  1110. else:
  1111. self.ui.shell_dock.hide()
  1112. # ###########################################################################################################
  1113. # ########################################## Tools and Plugins ##############################################
  1114. # ###########################################################################################################
  1115. self.dblsidedtool = None
  1116. self.distance_tool = None
  1117. self.distance_min_tool = None
  1118. self.panelize_tool = None
  1119. self.film_tool = None
  1120. self.paste_tool = None
  1121. self.calculator_tool = None
  1122. self.rules_tool = None
  1123. self.sub_tool = None
  1124. self.move_tool = None
  1125. self.cutout_tool = None
  1126. self.ncclear_tool = None
  1127. self.optimal_tool = None
  1128. self.paint_tool = None
  1129. self.transform_tool = None
  1130. self.properties_tool = None
  1131. self.pdf_tool = None
  1132. self.image_tool = None
  1133. self.pcb_wizard_tool = None
  1134. self.cal_exc_tool = None
  1135. self.qrcode_tool = None
  1136. self.copper_thieving_tool = None
  1137. self.fiducial_tool = None
  1138. self.edrills_tool = None
  1139. self.align_objects_tool = None
  1140. self.punch_tool = None
  1141. self.invert_tool = None
  1142. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1143. try:
  1144. self.install_tools()
  1145. except AttributeError as e:
  1146. log.debug("App.__init__() install tools() --> %s" % str(e))
  1147. # ###########################################################################################################
  1148. # ############################################ SETUP RECENT ITEMS ###########################################
  1149. # ###########################################################################################################
  1150. self.setup_recent_items()
  1151. # ###########################################################################################################
  1152. # ######################################### BookMarks Manager ###############################################
  1153. # ###########################################################################################################
  1154. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1155. self.install_bookmarks()
  1156. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1157. # ###########################################################################################################
  1158. # ########################################### Tools Database ################################################
  1159. # ###########################################################################################################
  1160. self.tools_db_tab = None
  1161. # ### System Font Parsing ###
  1162. # self.f_parse = ParseFont(self)
  1163. # self.parse_system_fonts()
  1164. # ###########################################################################################################
  1165. # ######################################### Check for updates ###############################################
  1166. # ###########################################################################################################
  1167. # Separate thread (Not worker)
  1168. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1169. if (self.beta is False or self.beta is None) and \
  1170. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1171. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1172. self.thr2 = QtCore.QThread()
  1173. self.worker_task.emit({'fcn': self.version_check,
  1174. 'params': []})
  1175. self.thr2.start(QtCore.QThread.LowPriority)
  1176. # ###########################################################################################################
  1177. # ##################################### Register files with FlatCAM; #######################################
  1178. # ################################### It works only for Windows for now ####################################
  1179. # ###########################################################################################################
  1180. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1181. self.on_register_files()
  1182. # ###########################################################################################################
  1183. # ######################################## Variables for global usage #######################################
  1184. # ###########################################################################################################
  1185. # hold the App units
  1186. self.units = 'MM'
  1187. # coordinates for relative position display
  1188. self.rel_point1 = (0, 0)
  1189. self.rel_point2 = (0, 0)
  1190. # variable to store coordinates
  1191. self.pos = (0, 0)
  1192. self.pos_canvas = (0, 0)
  1193. self.pos_jump = (0, 0)
  1194. # variable to store mouse coordinates
  1195. self.mouse = [0, 0]
  1196. # variable to store the delta positions on cavnas
  1197. self.dx = 0
  1198. self.dy = 0
  1199. # decide if we have a double click or single click
  1200. self.doubleclick = False
  1201. # store here the is_dragging value
  1202. self.event_is_dragging = False
  1203. # variable to store if a command is active (then the var is not None) and which one it is
  1204. self.command_active = None
  1205. # variable to store the status of moving selection action
  1206. # None value means that it's not an selection action
  1207. # True value = a selection from left to right
  1208. # False value = a selection from right to left
  1209. self.selection_type = None
  1210. # List to store the objects that are currently loaded in FlatCAM
  1211. # This list is updated on each object creation or object delete
  1212. self.all_objects_list = []
  1213. self.objects_under_the_click_list = []
  1214. # List to store the objects that are selected
  1215. self.sel_objects_list = []
  1216. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1217. self.key_modifiers = None
  1218. # Variable to hold the status of the axis
  1219. self.toggle_axis = True
  1220. # Variable to hold the status of the grid lines
  1221. self.toggle_grid_lines = True
  1222. # Variable to store the status of the fullscreen event
  1223. self.toggle_fscreen = False
  1224. # Variable to store the status of the code editor
  1225. self.toggle_codeeditor = False
  1226. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1227. self.click_noproject = False
  1228. self.cursor = None
  1229. # Variable to store the GCODE that was edited
  1230. self.gcode_edited = ""
  1231. self.text_editor_tab = None
  1232. # reference for the self.ui.code_editor
  1233. self.reference_code_editor = None
  1234. self.script_code = ''
  1235. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1236. self.tools_db_changed_flag = False
  1237. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1238. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1239. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1240. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1241. 'tsm']
  1242. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1243. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1244. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1245. 'sbp', 'tap', 'xpi']
  1246. self.svg_list = ['svg']
  1247. self.dxf_list = ['dxf']
  1248. self.pdf_list = ['pdf']
  1249. self.prj_list = ['flatprj']
  1250. self.conf_list = ['flatconfig']
  1251. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1252. # flag for polygons not cleared
  1253. self.poly_not_cleared = False
  1254. # VisPy visuals
  1255. self.isHovering = False
  1256. self.notHovering = True
  1257. # Window geometry
  1258. self.x_pos = None
  1259. self.y_pos = None
  1260. self.width = None
  1261. self.height = None
  1262. # when True, the app has to return from any thread
  1263. self.abort_flag = False
  1264. # set the value used in the Windows Title
  1265. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1266. # this holds a widget that is installed in the Plot Area when View Source option is used
  1267. self.source_editor_tab = None
  1268. self.pagesize = {}
  1269. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1270. # VisPy visuals
  1271. if self.is_legacy is False:
  1272. try:
  1273. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1274. except AttributeError:
  1275. self.tool_shapes = None
  1276. else:
  1277. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1278. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1279. # used in the delayed shutdown self.start_delayed_quit() method
  1280. self.save_timer = None
  1281. # ###########################################################################################################
  1282. # ################################## ADDING FlatCAM EDITORS section #########################################
  1283. # ###########################################################################################################
  1284. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1285. # at the first launch of the App , the editors will not be functional.
  1286. try:
  1287. self.geo_editor = FlatCAMGeoEditor(self)
  1288. except AttributeError:
  1289. pass
  1290. try:
  1291. self.exc_editor = FlatCAMExcEditor(self)
  1292. except AttributeError:
  1293. pass
  1294. try:
  1295. self.grb_editor = FlatCAMGrbEditor(self)
  1296. except AttributeError:
  1297. pass
  1298. self.log.debug("Finished adding FlatCAM Editor's.")
  1299. self.set_ui_title(name=_("New Project - Not saved"))
  1300. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1301. current_platform = platform.architecture()[0]
  1302. if current_platform != '64bit':
  1303. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1304. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1305. # ###########################################################################################################
  1306. # ##################################### Finished the CONSTRUCTOR ############################################
  1307. # ###########################################################################################################
  1308. App.log.debug("END of constructor. Releasing control.")
  1309. # ###########################################################################################################
  1310. # ########################################## SHOW GUI #######################################################
  1311. # ###########################################################################################################
  1312. # if the app is not started as headless, show it
  1313. if self.cmd_line_headless != 1:
  1314. if show_splash:
  1315. # finish the splash
  1316. self.splash.finish(self.ui)
  1317. mgui_settings = QSettings("Open Source", "FlatCAM")
  1318. if mgui_settings.contains("maximized_gui"):
  1319. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1320. if maximized_ui is True:
  1321. self.ui.showMaximized()
  1322. else:
  1323. self.ui.show()
  1324. else:
  1325. self.ui.show()
  1326. if self.defaults["global_systray_icon"]:
  1327. self.trayIcon.show()
  1328. else:
  1329. log.warning("******************* RUNNING HEADLESS *******************")
  1330. # ###########################################################################################################
  1331. # ######################################## START-UP ARGUMENTS ###############################################
  1332. # ###########################################################################################################
  1333. # test if the program was started with a script as parameter
  1334. if self.cmd_line_shellvar:
  1335. try:
  1336. cnt = 0
  1337. command_tcl = 0
  1338. for i in self.cmd_line_shellvar.split(','):
  1339. if i is not None:
  1340. # noinspection PyBroadException
  1341. try:
  1342. command_tcl = eval(i)
  1343. except Exception:
  1344. command_tcl = i
  1345. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1346. cnt += 1
  1347. # if there are Windows paths then replace the path separator with a Unix like one
  1348. if sys.platform == 'win32':
  1349. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1350. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1351. except Exception as ext:
  1352. print("ERROR: ", ext)
  1353. sys.exit(2)
  1354. if self.cmd_line_shellfile:
  1355. if self.cmd_line_headless != 1:
  1356. if self.ui.shell_dock.isHidden():
  1357. self.ui.shell_dock.show()
  1358. try:
  1359. with open(self.cmd_line_shellfile, "r") as myfile:
  1360. # if show_splash:
  1361. # self.splash.showMessage('%s: %ssec\n%s' % (
  1362. # _("Canvas initialization started.\n"
  1363. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1364. # _("Executing Tcl Script ...")),
  1365. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1366. # color=QtGui.QColor("gray"))
  1367. cmd_line_shellfile_text = myfile.read()
  1368. if self.cmd_line_headless != 1:
  1369. self.shell.exec_command(cmd_line_shellfile_text)
  1370. else:
  1371. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1372. except Exception as ext:
  1373. print("ERROR: ", ext)
  1374. sys.exit(2)
  1375. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1376. # the path/file_name must be enclosed in quotes if it contain spaces
  1377. if App.args:
  1378. self.args_at_startup.emit(App.args)
  1379. if self.defaults.old_defaults_found is True:
  1380. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1381. "Please reboot the application to update."))
  1382. self.defaults.old_defaults_found = False
  1383. # ######################################### INIT FINISHED #######################################################
  1384. # #################################################################################################################
  1385. # #################################################################################################################
  1386. # #################################################################################################################
  1387. # #################################################################################################################
  1388. # #################################################################################################################
  1389. @staticmethod
  1390. def copy_and_overwrite(from_path, to_path):
  1391. """
  1392. From here:
  1393. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1394. :param from_path: source path
  1395. :param to_path: destination path
  1396. :return: None
  1397. """
  1398. if os.path.exists(to_path):
  1399. shutil.rmtree(to_path)
  1400. try:
  1401. shutil.copytree(from_path, to_path)
  1402. except FileNotFoundError:
  1403. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1404. shutil.copytree(from_new_path, to_path)
  1405. def on_startup_args(self, args, silent=False):
  1406. """
  1407. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1408. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1409. :param args: a list containing the application args at startup
  1410. :return: None
  1411. """
  1412. if args is not None:
  1413. args_to_process = args
  1414. else:
  1415. args_to_process = App.args
  1416. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1417. for argument in args_to_process:
  1418. if '.FlatPrj'.lower() in argument.lower():
  1419. try:
  1420. project_name = str(argument)
  1421. if project_name == "":
  1422. if silent is False:
  1423. self.inform.emit(_("Cancelled."))
  1424. else:
  1425. # self.open_project(project_name)
  1426. run_from_arg = True
  1427. # self.worker_task.emit({'fcn': self.open_project,
  1428. # 'params': [project_name, run_from_arg]})
  1429. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1430. except Exception as e:
  1431. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1432. elif '.FlatConfig'.lower() in argument.lower():
  1433. try:
  1434. file_name = str(argument)
  1435. if file_name == "":
  1436. if silent is False:
  1437. self.inform.emit(_("Open Config file failed."))
  1438. else:
  1439. run_from_arg = True
  1440. # self.worker_task.emit({'fcn': self.open_config_file,
  1441. # 'params': [file_name, run_from_arg]})
  1442. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1443. except Exception as e:
  1444. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1445. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1446. try:
  1447. file_name = str(argument)
  1448. if file_name == "":
  1449. if silent is False:
  1450. self.inform.emit(_("Open Script file failed."))
  1451. else:
  1452. if silent is False:
  1453. self.on_fileopenscript(name=file_name)
  1454. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1455. self.on_filerunscript(name=file_name)
  1456. except Exception as e:
  1457. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1458. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1459. log.debug("App.on_startup_args() --> Quit event.")
  1460. sys.exit()
  1461. elif 'save'.lower() in argument.lower():
  1462. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1463. self.preferencesUiManager.save_defaults()
  1464. else:
  1465. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1466. proc_arg = argument.lower()
  1467. for ext in exc_list:
  1468. proc_ext = ext.replace(' ', '')
  1469. proc_ext = '.%s' % proc_ext
  1470. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1471. file_name = str(argument)
  1472. if file_name == "":
  1473. if silent is False:
  1474. self.inform.emit(_("Open Excellon file failed."))
  1475. else:
  1476. self.on_fileopenexcellon(name=file_name)
  1477. return
  1478. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1479. for ext in gco_list:
  1480. proc_ext = ext.replace(' ', '')
  1481. proc_ext = '.%s' % proc_ext
  1482. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1483. file_name = str(argument)
  1484. if file_name == "":
  1485. if silent is False:
  1486. self.inform.emit(_("Open GCode file failed."))
  1487. else:
  1488. self.on_fileopengcode(name=file_name)
  1489. return
  1490. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1491. for ext in grb_list:
  1492. proc_ext = ext.replace(' ', '')
  1493. proc_ext = '.%s' % proc_ext
  1494. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1495. file_name = str(argument)
  1496. if file_name == "":
  1497. if silent is False:
  1498. self.inform.emit(_("Open Gerber file failed."))
  1499. else:
  1500. self.on_fileopengerber(name=file_name)
  1501. return
  1502. # if it reached here without already returning then the app was registered with a file that it does not
  1503. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1504. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1505. # for arg in args_to_process:
  1506. # if 'FlatCAM.exe' in arg:
  1507. # continue
  1508. # else:
  1509. # sys.exit(2)
  1510. def set_ui_title(self, name):
  1511. """
  1512. Sets the title of the main window.
  1513. :param name: String that store the project path and project name
  1514. :return: None
  1515. """
  1516. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1517. (self.version,
  1518. ('BETA' if self.beta else ''),
  1519. platform.architecture()[0],
  1520. self.engine,
  1521. name)
  1522. )
  1523. def on_app_restart(self):
  1524. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1525. # be left in the SySTray
  1526. try:
  1527. self.trayIcon.hide()
  1528. except Exception:
  1529. pass
  1530. fcTranslate.restart_program(app=self)
  1531. def clear_pool(self):
  1532. """
  1533. Clear the multiprocessing pool and calls garbage collector.
  1534. :return: None
  1535. """
  1536. self.pool.close()
  1537. self.pool = Pool()
  1538. self.pool_recreated.emit(self.pool)
  1539. gc.collect()
  1540. def install_tools(self):
  1541. """
  1542. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1543. Instantiation of the Tools classes.
  1544. The order that the tools are installed is important as they can depend on each other install position.
  1545. :return: None
  1546. """
  1547. self.distance_tool = Distance(self)
  1548. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1549. before=self.ui.menueditorigin,
  1550. separator=False)
  1551. self.distance_min_tool = DistanceMin(self)
  1552. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1553. pos=self.ui.menuedit,
  1554. before=self.ui.menueditorigin,
  1555. separator=True)
  1556. self.dblsidedtool = DblSidedTool(self)
  1557. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1558. self.cal_exc_tool = ToolCalibration(self)
  1559. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1560. before=self.dblsidedtool.menuAction,
  1561. separator=False)
  1562. self.align_objects_tool = AlignObjects(self)
  1563. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1564. self.edrills_tool = ToolExtractDrills(self)
  1565. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1566. self.panelize_tool = Panelize(self)
  1567. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1568. self.film_tool = Film(self)
  1569. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1570. self.paste_tool = SolderPaste(self)
  1571. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1572. self.calculator_tool = ToolCalculator(self)
  1573. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1574. self.sub_tool = ToolSub(self)
  1575. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1576. pos=self.ui.menutool, separator=True)
  1577. self.rules_tool = RulesCheck(self)
  1578. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1579. pos=self.ui.menutool, separator=False)
  1580. self.optimal_tool = ToolOptimal(self)
  1581. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1582. pos=self.ui.menutool, separator=True)
  1583. self.move_tool = ToolMove(self)
  1584. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1585. before=self.ui.menueditorigin, separator=True)
  1586. self.cutout_tool = CutOut(self)
  1587. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1588. before=self.sub_tool.menuAction)
  1589. self.ncclear_tool = NonCopperClear(self)
  1590. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1591. before=self.sub_tool.menuAction, separator=True)
  1592. self.paint_tool = ToolPaint(self)
  1593. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1594. before=self.sub_tool.menuAction, separator=True)
  1595. self.copper_thieving_tool = ToolCopperThieving(self)
  1596. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1597. pos=self.ui.menutool)
  1598. self.fiducial_tool = ToolFiducials(self)
  1599. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1600. pos=self.ui.menutool)
  1601. self.qrcode_tool = QRCode(self)
  1602. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1603. pos=self.ui.menutool)
  1604. self.punch_tool = ToolPunchGerber(self)
  1605. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1606. self.invert_tool = ToolInvertGerber(self)
  1607. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1608. self.transform_tool = ToolTransform(self)
  1609. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1610. pos=self.ui.menuoptions, separator=True)
  1611. self.properties_tool = Properties(self)
  1612. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1613. pos=self.ui.menuoptions)
  1614. self.pdf_tool = ToolPDF(self)
  1615. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1616. pos=self.ui.menufileimport,
  1617. separator=True)
  1618. self.image_tool = ToolImage(self)
  1619. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1620. pos=self.ui.menufileimport,
  1621. separator=True)
  1622. self.pcb_wizard_tool = PcbWizard(self)
  1623. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1624. pos=self.ui.menufileimport)
  1625. self.log.debug("Tools are installed.")
  1626. def remove_tools(self):
  1627. """
  1628. Will remove all the actions in the Tool menu.
  1629. :return: None
  1630. """
  1631. for act in self.ui.menutool.actions():
  1632. self.ui.menutool.removeAction(act)
  1633. def init_tools(self):
  1634. """
  1635. Initialize the Tool tab in the notebook side of the central widget.
  1636. Remove the actions in the Tools menu.
  1637. Instantiate again the FlatCAM tools (plugins).
  1638. All this is required when changing the layout: standard, compact etc.
  1639. :return: None
  1640. """
  1641. log.debug("init_tools()")
  1642. # delete the data currently in the Tools Tab and the Tab itself
  1643. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1644. if widget is not None:
  1645. widget.deleteLater()
  1646. self.ui.notebook.removeTab(2)
  1647. # rebuild the Tools Tab
  1648. self.ui.tool_tab = QtWidgets.QWidget()
  1649. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1650. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1651. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1652. self.ui.tool_scroll_area = VerticalScrollArea()
  1653. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1654. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1655. # first remove all of them
  1656. self.remove_tools()
  1657. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1658. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1659. '&Command Line\tS')
  1660. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1661. # third install all of them
  1662. try:
  1663. self.install_tools()
  1664. except AttributeError:
  1665. pass
  1666. self.log.debug("Tools are initialized.")
  1667. # def parse_system_fonts(self):
  1668. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1669. # 'params': []})
  1670. def connect_toolbar_signals(self):
  1671. """
  1672. Reconnect the signals to the actions in the toolbar.
  1673. This has to be done each time after the FlatCAM tools are removed/installed.
  1674. :return: None
  1675. """
  1676. # Toolbar
  1677. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1678. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1679. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1680. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1681. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1682. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1683. self.ui.replot_btn.triggered.connect(self.plot_all)
  1684. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1685. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1686. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1687. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1688. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1689. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1690. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1691. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1692. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1693. self.ui.delete_btn.triggered.connect(self.on_delete)
  1694. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1695. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1696. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1697. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1698. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1699. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1700. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1701. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1702. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1703. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1704. # Tools Toolbar Signals
  1705. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1706. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1707. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1708. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1709. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1710. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1711. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1712. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1713. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1714. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1715. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1716. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1717. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1718. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1719. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1720. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1721. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1722. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1723. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1724. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1725. def object2editor(self):
  1726. """
  1727. Send the current Geometry or Excellon object (if any) into the it's editor.
  1728. :return: None
  1729. """
  1730. self.defaults.report_usage("object2editor()")
  1731. # disable the objects menu as it may interfere with the Editors
  1732. self.ui.menuobjects.setDisabled(True)
  1733. edited_object = self.collection.get_active()
  1734. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1735. isinstance(edited_object, ExcellonObject):
  1736. pass
  1737. else:
  1738. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1739. return
  1740. if isinstance(edited_object, GeometryObject):
  1741. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1742. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1743. # we set the notebook to hidden
  1744. # self.ui.splitter.setSizes([0, 1])
  1745. if edited_object.multigeo is True:
  1746. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1747. if len(sel_rows) > 1:
  1748. self.inform.emit('[WARNING_NOTCL] %s' %
  1749. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1750. "is not possible.\n"
  1751. "Edit only one geometry at a time."))
  1752. # determine the tool dia of the selected tool
  1753. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1754. # now find the key in the edited_object.tools that has this tooldia
  1755. multi_tool = 1
  1756. for tool in edited_object.tools:
  1757. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1758. multi_tool = tool
  1759. break
  1760. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1761. else:
  1762. self.geo_editor.edit_fcgeometry(edited_object)
  1763. # set call source to the Editor we go into
  1764. self.call_source = 'geo_editor'
  1765. elif isinstance(edited_object, ExcellonObject):
  1766. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1767. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1768. if self.ui.splitter.sizes()[0] == 0:
  1769. self.ui.splitter.setSizes([1, 1])
  1770. self.exc_editor.edit_fcexcellon(edited_object)
  1771. # set call source to the Editor we go into
  1772. self.call_source = 'exc_editor'
  1773. elif isinstance(edited_object, GerberObject):
  1774. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1775. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1776. if self.ui.splitter.sizes()[0] == 0:
  1777. self.ui.splitter.setSizes([1, 1])
  1778. self.grb_editor.edit_fcgerber(edited_object)
  1779. # set call source to the Editor we go into
  1780. self.call_source = 'grb_editor'
  1781. # reset the following variables so the UI is built again after edit
  1782. edited_object.ui_build = False
  1783. edited_object.build_aperture_storage = False
  1784. # make sure that we can't select another object while in Editor Mode:
  1785. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1786. self.ui.project_frame.setDisabled(True)
  1787. # delete any selection shape that might be active as they are not relevant in Editor
  1788. self.delete_selection_shape()
  1789. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1790. self.ui.plot_tab_area.protectTab(0)
  1791. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1792. self.should_we_save = True
  1793. def editor2object(self, cleanup=None):
  1794. """
  1795. Transfers the Geometry or Excellon from it's editor to the current object.
  1796. :return: None
  1797. """
  1798. self.defaults.report_usage("editor2object()")
  1799. # re-enable the objects menu that was disabled on entry in Editor mode
  1800. self.ui.menuobjects.setDisabled(False)
  1801. # do not update a geometry or excellon object unless it comes out of an editor
  1802. if self.call_source != 'app':
  1803. edited_obj = self.collection.get_active()
  1804. if cleanup is None:
  1805. msgbox = QtWidgets.QMessageBox()
  1806. msgbox.setText(_("Do you want to save the edited object?"))
  1807. msgbox.setWindowTitle(_("Close Editor"))
  1808. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1809. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1810. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1811. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1812. msgbox.setDefaultButton(bt_yes)
  1813. msgbox.exec_()
  1814. response = msgbox.clickedButton()
  1815. if response == bt_yes:
  1816. # clean the Tools Tab
  1817. self.ui.tool_scroll_area.takeWidget()
  1818. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1819. self.ui.notebook.setTabText(2, "Tool")
  1820. if isinstance(edited_obj, GeometryObject):
  1821. obj_type = "Geometry"
  1822. if cleanup is None:
  1823. self.geo_editor.update_fcgeometry(edited_obj)
  1824. # self.geo_editor.update_options(edited_obj)
  1825. self.geo_editor.deactivate()
  1826. # restore GUI to the Selected TAB
  1827. # Remove anything else in the GUI
  1828. self.ui.tool_scroll_area.takeWidget()
  1829. # update the geo object options so it is including the bounding box values
  1830. try:
  1831. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1832. edited_obj.options['xmin'] = xmin
  1833. edited_obj.options['ymin'] = ymin
  1834. edited_obj.options['xmax'] = xmax
  1835. edited_obj.options['ymax'] = ymax
  1836. except AttributeError as e:
  1837. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1838. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1839. edited_obj.build_ui()
  1840. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1841. elif isinstance(edited_obj, GerberObject):
  1842. obj_type = "Gerber"
  1843. if cleanup is None:
  1844. self.grb_editor.update_fcgerber()
  1845. self.grb_editor.update_options(edited_obj)
  1846. self.grb_editor.deactivate_grb_editor()
  1847. # delete the old object (the source object) if it was an empty one
  1848. try:
  1849. if len(edited_obj.solid_geometry) == 0:
  1850. old_name = edited_obj.options['name']
  1851. self.collection.set_active(old_name)
  1852. self.collection.delete_active()
  1853. except TypeError:
  1854. # if the solid_geometry is a single Polygon the len() will not work
  1855. # in any case, falling here means that we have something in the solid_geometry, even if only
  1856. # a single Polygon, therefore we pass this
  1857. pass
  1858. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1859. # restore GUI to the Selected TAB
  1860. # Remove anything else in the GUI
  1861. self.ui.selected_scroll_area.takeWidget()
  1862. elif isinstance(edited_obj, ExcellonObject):
  1863. obj_type = "Excellon"
  1864. if cleanup is None:
  1865. self.exc_editor.update_fcexcellon(edited_obj)
  1866. # self.exc_editor.update_options(edited_obj)
  1867. self.exc_editor.deactivate()
  1868. # restore GUI to the Selected TAB
  1869. # Remove anything else in the GUI
  1870. self.ui.tool_scroll_area.takeWidget()
  1871. # delete the old object (the source object) if it was an empty one
  1872. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1873. old_name = edited_obj.options['name']
  1874. self.collection.delete_by_name(name=old_name)
  1875. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1876. else:
  1877. self.inform.emit('[WARNING_NOTCL] %s' %
  1878. _("Select a Gerber, Geometry or Excellon Object to update."))
  1879. return
  1880. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1881. elif response == bt_no:
  1882. # clean the Tools Tab
  1883. self.ui.tool_scroll_area.takeWidget()
  1884. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1885. self.ui.notebook.setTabText(2, "Tool")
  1886. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1887. if isinstance(edited_obj, GeometryObject):
  1888. self.geo_editor.deactivate()
  1889. edited_obj.build_ui()
  1890. elif isinstance(edited_obj, GerberObject):
  1891. self.grb_editor.deactivate_grb_editor()
  1892. edited_obj.build_ui()
  1893. elif isinstance(edited_obj, ExcellonObject):
  1894. self.exc_editor.deactivate()
  1895. edited_obj.build_ui()
  1896. else:
  1897. self.inform.emit('[WARNING_NOTCL] %s' %
  1898. _("Select a Gerber, Geometry or Excellon Object to update."))
  1899. return
  1900. elif response == bt_cancel:
  1901. return
  1902. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1903. # edited_obj.build_ui()
  1904. # Switch notebook to Selected page
  1905. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1906. else:
  1907. if isinstance(edited_obj, GeometryObject):
  1908. self.geo_editor.deactivate()
  1909. elif isinstance(edited_obj, GerberObject):
  1910. self.grb_editor.deactivate_grb_editor()
  1911. elif isinstance(edited_obj, ExcellonObject):
  1912. self.exc_editor.deactivate()
  1913. else:
  1914. self.inform.emit('[WARNING_NOTCL] %s' %
  1915. _("Select a Gerber, Geometry or Excellon Object to update."))
  1916. return
  1917. # if notebook is hidden we show it
  1918. if self.ui.splitter.sizes()[0] == 0:
  1919. self.ui.splitter.setSizes([1, 1])
  1920. # restore the call_source to app
  1921. self.call_source = 'app'
  1922. edited_obj.plot()
  1923. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1924. self.ui.plot_tab_area.protectTab(0)
  1925. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1926. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1927. self.ui.project_frame.setDisabled(False)
  1928. def get_last_folder(self):
  1929. """
  1930. Get the folder path from where the last file was opened.
  1931. :return: String, last opened folder path
  1932. """
  1933. return self.defaults["global_last_folder"]
  1934. def get_last_save_folder(self):
  1935. """
  1936. Get the folder path from where the last file was saved.
  1937. :return: String, last saved folder path
  1938. """
  1939. loc = self.defaults["global_last_save_folder"]
  1940. if loc is None:
  1941. loc = self.defaults["global_last_folder"]
  1942. if loc is None:
  1943. loc = os.path.dirname(__file__)
  1944. return loc
  1945. def info(self, msg):
  1946. """
  1947. Informs the user. Normally on the status bar, optionally
  1948. also on the shell.
  1949. :param msg: Text to write.
  1950. :return: None
  1951. """
  1952. # Type of message in brackets at the beginning of the message.
  1953. match = re.search(r"\[(.*)\](.*)", msg)
  1954. if match:
  1955. level = match.group(1)
  1956. msg_ = match.group(2)
  1957. self.ui.fcinfo.set_status(str(msg_), level=level)
  1958. if level.lower() == "error":
  1959. self.shell_message(msg, error=True, show=True)
  1960. elif level.lower() == "warning":
  1961. self.shell_message(msg, warning=True, show=True)
  1962. elif level.lower() == "error_notcl":
  1963. self.shell_message(msg, error=True, show=False)
  1964. elif level.lower() == "warning_notcl":
  1965. self.shell_message(msg, warning=True, show=False)
  1966. elif level.lower() == "success":
  1967. self.shell_message(msg, success=True, show=False)
  1968. elif level.lower() == "selected":
  1969. self.shell_message(msg, selected=True, show=False)
  1970. else:
  1971. self.shell_message(msg, show=False)
  1972. else:
  1973. self.ui.fcinfo.set_status(str(msg), level="info")
  1974. # make sure that if the message is to clear the infobar with a space
  1975. # is not printed over and over on the shell
  1976. if msg != '':
  1977. self.shell_message(msg)
  1978. def restore_toolbar_view(self):
  1979. """
  1980. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1981. was saved in the defaults dictionary.
  1982. :return: None
  1983. """
  1984. tb = self.defaults["global_toolbar_view"]
  1985. if tb & 1:
  1986. self.ui.toolbarfile.setVisible(True)
  1987. else:
  1988. self.ui.toolbarfile.setVisible(False)
  1989. if tb & 2:
  1990. self.ui.toolbargeo.setVisible(True)
  1991. else:
  1992. self.ui.toolbargeo.setVisible(False)
  1993. if tb & 4:
  1994. self.ui.toolbarview.setVisible(True)
  1995. else:
  1996. self.ui.toolbarview.setVisible(False)
  1997. if tb & 8:
  1998. self.ui.toolbartools.setVisible(True)
  1999. else:
  2000. self.ui.toolbartools.setVisible(False)
  2001. if tb & 16:
  2002. self.ui.exc_edit_toolbar.setVisible(True)
  2003. else:
  2004. self.ui.exc_edit_toolbar.setVisible(False)
  2005. if tb & 32:
  2006. self.ui.geo_edit_toolbar.setVisible(True)
  2007. else:
  2008. self.ui.geo_edit_toolbar.setVisible(False)
  2009. if tb & 64:
  2010. self.ui.grb_edit_toolbar.setVisible(True)
  2011. else:
  2012. self.ui.grb_edit_toolbar.setVisible(False)
  2013. if tb & 128:
  2014. self.ui.snap_toolbar.setVisible(True)
  2015. else:
  2016. self.ui.snap_toolbar.setVisible(False)
  2017. if tb & 256:
  2018. self.ui.toolbarshell.setVisible(True)
  2019. else:
  2020. self.ui.toolbarshell.setVisible(False)
  2021. def on_import_preferences(self):
  2022. """
  2023. Loads the application default settings from a saved file into
  2024. ``self.defaults`` dictionary.
  2025. :return: None
  2026. """
  2027. self.defaults.report_usage("on_import_preferences")
  2028. App.log.debug("App.on_import_preferences()")
  2029. # Show file chooser
  2030. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2031. try:
  2032. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2033. directory=self.data_path,
  2034. filter=filter_)
  2035. except TypeError:
  2036. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2037. filter=filter_)
  2038. filename = str(filename)
  2039. if filename == "":
  2040. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2041. return
  2042. # Load in the defaults from the chosen file
  2043. self.defaults.load(filename=filename)
  2044. self.preferencesUiManager.on_preferences_edited()
  2045. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2046. def on_export_preferences(self):
  2047. """
  2048. Save the defaults dictionary to a file.
  2049. :return: None
  2050. """
  2051. self.defaults.report_usage("on_export_preferences")
  2052. App.log.debug("on_export_preferences()")
  2053. defaults_file_content = None
  2054. # Show file chooser
  2055. date = str(datetime.today()).rpartition('.')[0]
  2056. date = ''.join(c for c in date if c not in ':-')
  2057. date = date.replace(' ', '_')
  2058. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2059. try:
  2060. filename, _f = FCFileSaveDialog.get_saved_filename(
  2061. caption=_("Export FlatCAM Preferences"),
  2062. directory=self.data_path + '/preferences_' + date,
  2063. filter=filter__
  2064. )
  2065. except TypeError:
  2066. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2067. filename = str(filename)
  2068. if filename == "":
  2069. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2070. return
  2071. # Update options
  2072. self.preferencesUiManager.defaults_read_form()
  2073. self.defaults.propagate_defaults()
  2074. # Save update options
  2075. try:
  2076. self.defaults.write(filename=filename)
  2077. except Exception:
  2078. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2079. return
  2080. if self.defaults["global_open_style"] is False:
  2081. self.file_opened.emit("preferences", filename)
  2082. self.file_saved.emit("preferences", filename)
  2083. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2084. def save_to_file(self, content_to_save, txt_content):
  2085. """
  2086. Save something to a file.
  2087. :return: None
  2088. """
  2089. self.defaults.report_usage("save_to_file")
  2090. App.log.debug("save_to_file()")
  2091. self.date = str(datetime.today()).rpartition('.')[0]
  2092. self.date = ''.join(c for c in self.date if c not in ':-')
  2093. self.date = self.date.replace(' ', '_')
  2094. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2095. path_to_save = self.defaults["global_last_save_folder"] if\
  2096. self.defaults["global_last_save_folder"] is not None else self.data_path
  2097. try:
  2098. filename, _f = FCFileSaveDialog.get_saved_filename(
  2099. caption=_("Save to file"),
  2100. directory=path_to_save + '/file_' + self.date,
  2101. filter=filter__
  2102. )
  2103. except TypeError:
  2104. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2105. filename = str(filename)
  2106. if filename == "":
  2107. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2108. return
  2109. else:
  2110. try:
  2111. with open(filename, 'w') as f:
  2112. ___ = f.read()
  2113. except PermissionError:
  2114. self.inform.emit('[WARNING] %s' %
  2115. _("Permission denied, saving not possible.\n"
  2116. "Most likely another app is holding the file open and not accessible."))
  2117. return
  2118. except IOError:
  2119. App.log.debug('Creating a new file ...')
  2120. f = open(filename, 'w')
  2121. f.close()
  2122. except Exception:
  2123. e = sys.exc_info()[0]
  2124. App.log.error("Could not load the file.")
  2125. App.log.error(str(e))
  2126. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2127. return
  2128. # Save content
  2129. if filename.rpartition('.')[2].lower() == 'html':
  2130. file_content = content_to_save
  2131. else:
  2132. file_content = txt_content
  2133. try:
  2134. with open(filename, "w") as f:
  2135. f.write(file_content)
  2136. except Exception:
  2137. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2138. return
  2139. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2140. def save_geometry(self, x, y, width, height, notebook_width):
  2141. """
  2142. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2143. launch of the application.
  2144. :param x: X position of the main window
  2145. :param y: Y position of the main window
  2146. :param width: width of the main window
  2147. :param height: height of the main window
  2148. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2149. :return: None
  2150. """
  2151. self.defaults["global_def_win_x"] = x
  2152. self.defaults["global_def_win_y"] = y
  2153. self.defaults["global_def_win_w"] = width
  2154. self.defaults["global_def_win_h"] = height
  2155. self.defaults["global_def_notebook_width"] = notebook_width
  2156. self.preferencesUiManager.save_defaults()
  2157. def restore_main_win_geom(self):
  2158. try:
  2159. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2160. self.defaults["global_def_win_y"],
  2161. self.defaults["global_def_win_w"],
  2162. self.defaults["global_def_win_h"])
  2163. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2164. except KeyError as e:
  2165. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2166. def message_dialog(self, title, message, kind="info"):
  2167. """
  2168. Builds and show a custom QMessageBox to be used in FlatCAM.
  2169. :param title: title of the QMessageBox
  2170. :param message: message to be displayed
  2171. :param kind: type of QMessageBox; will display a specific icon.
  2172. :return:
  2173. """
  2174. icon = {"info": QtWidgets.QMessageBox.Information,
  2175. "warning": QtWidgets.QMessageBox.Warning,
  2176. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2177. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2178. dlg.setText(message)
  2179. dlg.exec_()
  2180. def register_recent(self, kind, filename):
  2181. """
  2182. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2183. dictionary.
  2184. :param kind: type of file that was opened
  2185. :param filename: the path and file name for the file that was opened
  2186. :return:
  2187. """
  2188. self.log.debug("register_recent()")
  2189. self.log.debug(" %s" % kind)
  2190. self.log.debug(" %s" % filename)
  2191. record = {'kind': str(kind), 'filename': str(filename)}
  2192. if record in self.recent:
  2193. return
  2194. if record in self.recent_projects:
  2195. return
  2196. if record['kind'] == 'project':
  2197. self.recent_projects.insert(0, record)
  2198. else:
  2199. self.recent.insert(0, record)
  2200. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2201. self.recent.pop()
  2202. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2203. self.recent_projects.pop()
  2204. try:
  2205. f = open(self.data_path + '/recent.json', 'w')
  2206. except IOError:
  2207. App.log.error("Failed to open recent items file for writing.")
  2208. self.inform.emit('[ERROR_NOTCL] %s' %
  2209. _('Failed to open recent files file for writing.'))
  2210. return
  2211. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2212. f.close()
  2213. try:
  2214. fp = open(self.data_path + '/recent_projects.json', 'w')
  2215. except IOError:
  2216. App.log.error("Failed to open recent items file for writing.")
  2217. self.inform.emit('[ERROR_NOTCL] %s' %
  2218. _('Failed to open recent projects file for writing.'))
  2219. return
  2220. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2221. fp.close()
  2222. # Re-build the recent items menu
  2223. self.setup_recent_items()
  2224. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2225. """
  2226. Creates a new specialized FlatCAMObj and attaches it to the application,
  2227. this is, updates the GUI accordingly, any other records and plots it.
  2228. This method is thread-safe.
  2229. Notes:
  2230. * If the name is in use, the self.collection will modify it
  2231. when appending it to the collection. There is no need to handle
  2232. name conflicts here.
  2233. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2234. :type kind: str
  2235. :param name: Name for the object.
  2236. :type name: str
  2237. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2238. The function is called with 2 parameters: the new object and the App instance.
  2239. :type initialize: function
  2240. :param active:
  2241. :param fit:
  2242. :param plot: If to plot the resulting object
  2243. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2244. self.collection
  2245. :return: None
  2246. :rtype: None
  2247. """
  2248. App.log.debug("new_object()")
  2249. obj_plot = plot
  2250. obj_autoselected = autoselected
  2251. t0 = time.time() # Debug
  2252. # ## Create object
  2253. classdict = {
  2254. "gerber": GerberObject,
  2255. "excellon": ExcellonObject,
  2256. "cncjob": CNCJobObject,
  2257. "geometry": GeometryObject,
  2258. "script": ScriptObject,
  2259. "document": DocumentObject
  2260. }
  2261. App.log.debug("Calling object constructor...")
  2262. # Object creation/instantiation
  2263. obj = classdict[kind](name)
  2264. obj.units = self.options["units"]
  2265. # IMPORTANT
  2266. # The key names in defaults and options dictionary's are not random:
  2267. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2268. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2269. # copied to self.options. After that, below, depending on the type of
  2270. # object that is created, it will strip the name of the object and the underline (if the original key was
  2271. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2272. # "toolchange"
  2273. for option in self.options:
  2274. if option.find(kind + "_") == 0:
  2275. oname = option[len(kind) + 1:]
  2276. obj.options[oname] = self.options[option]
  2277. obj.isHovering = False
  2278. obj.notHovering = True
  2279. # Initialize as per user request
  2280. # User must take care to implement initialize
  2281. # in a thread-safe way as is is likely that we
  2282. # have been invoked in a separate thread.
  2283. t1 = time.time()
  2284. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2285. try:
  2286. return_value = initialize(obj, self)
  2287. except Exception as e:
  2288. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2289. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2290. msg += traceback.format_exc()
  2291. self.inform.emit(msg)
  2292. return "fail"
  2293. t2 = time.time()
  2294. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2295. if return_value == 'fail':
  2296. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2297. return "fail"
  2298. # Check units and convert if necessary
  2299. # This condition CAN be true because initialize() can change obj.units
  2300. if self.options["units"].upper() != obj.units.upper():
  2301. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2302. obj.convert_units(self.options["units"])
  2303. t3 = time.time()
  2304. self.log.debug("%f seconds converting units." % (t3 - t2))
  2305. # Create the bounding box for the object and then add the results to the obj.options
  2306. # But not for Scripts or for Documents
  2307. if kind != 'document' and kind != 'script':
  2308. try:
  2309. xmin, ymin, xmax, ymax = obj.bounds()
  2310. obj.options['xmin'] = xmin
  2311. obj.options['ymin'] = ymin
  2312. obj.options['xmax'] = xmax
  2313. obj.options['ymax'] = ymax
  2314. except Exception as e:
  2315. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2316. return "fail"
  2317. try:
  2318. if kind == 'excellon':
  2319. obj.fill_color = self.defaults["excellon_plot_fill"]
  2320. obj.outline_color = self.defaults["excellon_plot_line"]
  2321. if kind == 'gerber':
  2322. obj.fill_color = self.defaults["gerber_plot_fill"]
  2323. obj.outline_color = self.defaults["gerber_plot_line"]
  2324. except Exception as e:
  2325. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2326. # update the KeyWords list with the name of the file
  2327. self.myKeywords.append(obj.options['name'])
  2328. log.debug("Moving new object back to main thread.")
  2329. # Move the object to the main thread and let the app know that it is available.
  2330. obj.moveToThread(self.main_thread)
  2331. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2332. return obj
  2333. def new_excellon_object(self):
  2334. """
  2335. Creates a new, blank Excellon object.
  2336. :return: None
  2337. """
  2338. self.defaults.report_usage("new_excellon_object()")
  2339. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2340. def new_geometry_object(self):
  2341. """
  2342. Creates a new, blank and single-tool Geometry object.
  2343. :return: None
  2344. """
  2345. self.defaults.report_usage("new_geometry_object()")
  2346. def initialize(obj, app):
  2347. obj.multitool = False
  2348. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2349. def new_gerber_object(self):
  2350. """
  2351. Creates a new, blank Gerber object.
  2352. :return: None
  2353. """
  2354. self.defaults.report_usage("new_gerber_object()")
  2355. def initialize(grb_obj, app):
  2356. grb_obj.multitool = False
  2357. grb_obj.source_file = []
  2358. grb_obj.multigeo = False
  2359. grb_obj.follow = False
  2360. grb_obj.apertures = {}
  2361. grb_obj.solid_geometry = []
  2362. try:
  2363. grb_obj.options['xmin'] = 0
  2364. grb_obj.options['ymin'] = 0
  2365. grb_obj.options['xmax'] = 0
  2366. grb_obj.options['ymax'] = 0
  2367. except KeyError:
  2368. pass
  2369. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2370. def new_script_object(self, name=None, text=None):
  2371. """
  2372. Creates a new, blank TCL Script object.
  2373. :param name: a name for the new object
  2374. :param text: pass a source file to the newly created script to be loaded in it
  2375. :return: None
  2376. """
  2377. self.defaults.report_usage("new_script_object()")
  2378. if text is not None:
  2379. new_source_file = text
  2380. else:
  2381. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2382. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2383. "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2384. "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2385. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2386. "ListSys, MillDrills,\n" \
  2387. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2388. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2389. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2390. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2391. "# SubtractRectangle, Version, WriteGCode\n"
  2392. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2393. '# %s:\n' % _('TCL Tutorial is here') + \
  2394. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2395. '# %s:\n' % _("FlatCAM commands list")
  2396. new_source_file += commands_list + '\n'
  2397. def initialize(obj, app):
  2398. obj.source_file = deepcopy(new_source_file)
  2399. if name is None:
  2400. outname = 'new_script'
  2401. else:
  2402. outname = name
  2403. self.new_object('script', outname, initialize, plot=False)
  2404. def new_document_object(self):
  2405. """
  2406. Creates a new, blank Document object.
  2407. :return: None
  2408. """
  2409. self.defaults.report_usage("new_document_object()")
  2410. def initialize(obj, app):
  2411. obj.source_file = ""
  2412. self.new_object('document', 'new_document', initialize, plot=False)
  2413. def on_object_created(self, obj, plot, auto_select):
  2414. """
  2415. Event callback for object creation.
  2416. It will add the new object to the collection. After that it will plot the object in a threaded way
  2417. :param obj: The newly created FlatCAM object.
  2418. :param plot: if the newly create object t obe plotted
  2419. :param auto_select: if the newly created object to be autoselected after creation
  2420. :return: None
  2421. """
  2422. t0 = time.time() # DEBUG
  2423. self.log.debug("on_object_created()")
  2424. # The Collection might change the name if there is a collision
  2425. self.collection.append(obj)
  2426. # after adding the object to the collection always update the list of objects that are in the collection
  2427. self.all_objects_list = self.collection.get_list()
  2428. # self.inform.emit('[selected] %s created & selected: %s' %
  2429. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2430. if obj.kind == 'gerber':
  2431. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2432. kind=obj.kind.capitalize(),
  2433. color='green',
  2434. name=str(obj.options['name']), tx=_("created/selected"))
  2435. )
  2436. elif obj.kind == 'excellon':
  2437. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2438. kind=obj.kind.capitalize(),
  2439. color='brown',
  2440. name=str(obj.options['name']), tx=_("created/selected"))
  2441. )
  2442. elif obj.kind == 'cncjob':
  2443. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2444. kind=obj.kind.capitalize(),
  2445. color='blue',
  2446. name=str(obj.options['name']), tx=_("created/selected"))
  2447. )
  2448. elif obj.kind == 'geometry':
  2449. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2450. kind=obj.kind.capitalize(),
  2451. color='red',
  2452. name=str(obj.options['name']), tx=_("created/selected"))
  2453. )
  2454. elif obj.kind == 'script':
  2455. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2456. kind=obj.kind.capitalize(),
  2457. color='orange',
  2458. name=str(obj.options['name']), tx=_("created/selected"))
  2459. )
  2460. elif obj.kind == 'document':
  2461. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2462. kind=obj.kind.capitalize(),
  2463. color='darkCyan',
  2464. name=str(obj.options['name']), tx=_("created/selected"))
  2465. )
  2466. # update the SHELL auto-completer model with the name of the new object
  2467. self.shell._edit.set_model_data(self.myKeywords)
  2468. if auto_select:
  2469. # select the just opened object but deselect the previous ones
  2470. self.collection.set_all_inactive()
  2471. self.collection.set_active(obj.options["name"])
  2472. else:
  2473. self.collection.set_all_inactive()
  2474. # here it is done the object plotting
  2475. def worker_task(t_obj):
  2476. with self.proc_container.new(_("Plotting")):
  2477. if isinstance(t_obj, CNCJobObject):
  2478. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2479. else:
  2480. t_obj.plot()
  2481. t1 = time.time() # DEBUG
  2482. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2483. self.object_plotted.emit(t_obj)
  2484. # Send to worker
  2485. # self.worker.add_task(worker_task, [self])
  2486. if plot is True:
  2487. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2488. def on_object_changed(self, obj):
  2489. """
  2490. Called whenever the geometry of the object was changed in some way.
  2491. This require the update of it's bounding values so it can be the selected on canvas.
  2492. Update the bounding box data from obj.options
  2493. :param obj: the object that was changed
  2494. :return: None
  2495. """
  2496. xmin, ymin, xmax, ymax = obj.bounds()
  2497. obj.options['xmin'] = xmin
  2498. obj.options['ymin'] = ymin
  2499. obj.options['xmax'] = xmax
  2500. obj.options['ymax'] = ymax
  2501. log.debug("Object changed, updating the bounding box data on self.options")
  2502. # delete the old selection shape
  2503. self.delete_selection_shape()
  2504. self.should_we_save = True
  2505. def on_object_plotted(self):
  2506. """
  2507. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2508. :return: None
  2509. """
  2510. self.on_zoom_fit(None)
  2511. def on_about(self):
  2512. """
  2513. Displays the "about" dialog found in the Menu --> Help.
  2514. :return: None
  2515. """
  2516. self.defaults.report_usage("on_about")
  2517. version = self.version
  2518. version_date = self.version_date
  2519. beta = self.beta
  2520. class AboutDialog(QtWidgets.QDialog):
  2521. def __init__(self, app, parent=None):
  2522. QtWidgets.QDialog.__init__(self, parent)
  2523. self.app = app
  2524. # Icon and title
  2525. self.setWindowIcon(parent.app_icon)
  2526. self.setWindowTitle(_("About FlatCAM"))
  2527. self.resize(600, 200)
  2528. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2529. # self.setStyleSheet(
  2530. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2531. # "background-attachment: fixed"
  2532. # )
  2533. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2534. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2535. # palette = QtGui.QPalette()
  2536. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2537. # self.setPalette(palette)
  2538. logo = QtWidgets.QLabel()
  2539. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2540. title = QtWidgets.QLabel(
  2541. "<font size=8><B>FlatCAM</B></font><BR>"
  2542. "{title}<BR>"
  2543. "<BR>"
  2544. "<BR>"
  2545. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2546. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2547. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2548. "<B>{issue}</B></a><BR>".format(
  2549. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2550. devel=_("Development"),
  2551. down=_("DOWNLOAD"),
  2552. issue=_("Issue tracker"))
  2553. )
  2554. title.setOpenExternalLinks(True)
  2555. closebtn = QtWidgets.QPushButton(_("Close"))
  2556. tab_widget = QtWidgets.QTabWidget()
  2557. description_label = QtWidgets.QLabel(
  2558. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2559. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2560. version=version,
  2561. beta=('BETA' if beta else ''),
  2562. date=version_date,
  2563. arch=platform.architecture()[0])
  2564. )
  2565. description_label.setOpenExternalLinks(True)
  2566. lic_lbl_header = QtWidgets.QLabel(
  2567. '%s:<br>%s<br>' % (
  2568. _('Licensed under the MIT license'),
  2569. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2570. "http://www.opensource.org/licenses/mit-license.php</a>"
  2571. )
  2572. )
  2573. lic_lbl_header.setOpenExternalLinks(True)
  2574. lic_lbl_body = QtWidgets.QLabel(
  2575. _(
  2576. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2577. 'of this software and associated documentation files (the "Software"), to deal\n'
  2578. 'in the Software without restriction, including without limitation the rights\n'
  2579. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2580. 'copies of the Software, and to permit persons to whom the Software is\n'
  2581. 'furnished to do so, subject to the following conditions:\n\n'
  2582. 'The above copyright notice and this permission notice shall be included in\n'
  2583. 'all copies or substantial portions of the Software.\n\n'
  2584. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2585. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2586. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2587. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2588. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2589. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2590. 'THE SOFTWARE.'
  2591. )
  2592. )
  2593. attributions_label = QtWidgets.QLabel(
  2594. _(
  2595. 'Some of the icons used are from the following sources:<br>'
  2596. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2597. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2598. 'title="Flaticon">www.flaticon.com</a></div>'
  2599. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2600. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2601. )
  2602. )
  2603. attributions_label.setOpenExternalLinks(True)
  2604. # layouts
  2605. layout1 = QtWidgets.QVBoxLayout()
  2606. layout1_1 = QtWidgets.QHBoxLayout()
  2607. layout1_2 = QtWidgets.QHBoxLayout()
  2608. layout2 = QtWidgets.QHBoxLayout()
  2609. layout3 = QtWidgets.QHBoxLayout()
  2610. self.setLayout(layout1)
  2611. layout1.addLayout(layout1_1)
  2612. layout1.addLayout(layout1_2)
  2613. layout1.addLayout(layout2)
  2614. layout1.addLayout(layout3)
  2615. layout1_1.addStretch()
  2616. layout1_1.addWidget(description_label)
  2617. layout1_2.addWidget(tab_widget)
  2618. self.splash_tab = QtWidgets.QWidget()
  2619. self.splash_tab.setObjectName("splash_about")
  2620. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2621. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2622. tab_widget.addTab(self.splash_tab, _("Splash"))
  2623. self.programmmers_tab = QtWidgets.QWidget()
  2624. self.programmmers_tab.setObjectName("programmers_about")
  2625. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2626. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2627. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2628. self.translators_tab = QtWidgets.QWidget()
  2629. self.translators_tab.setObjectName("translators_about")
  2630. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2631. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2632. tab_widget.addTab(self.translators_tab, _("Translators"))
  2633. self.license_tab = QtWidgets.QWidget()
  2634. self.license_tab.setObjectName("license_about")
  2635. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2636. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2637. tab_widget.addTab(self.license_tab, _("License"))
  2638. self.attributions_tab = QtWidgets.QWidget()
  2639. self.attributions_tab.setObjectName("attributions_about")
  2640. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2641. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2642. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2643. self.splash_tab_layout.addWidget(logo, stretch=0)
  2644. self.splash_tab_layout.addWidget(title, stretch=1)
  2645. pal = QtGui.QPalette()
  2646. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2647. self.prog_grid_lay = QtWidgets.QGridLayout()
  2648. self.prog_grid_lay.setHorizontalSpacing(20)
  2649. self.prog_grid_lay.setColumnStretch(0, 0)
  2650. self.prog_grid_lay.setColumnStretch(2, 1)
  2651. prog_widget = QtWidgets.QWidget()
  2652. prog_widget.setLayout(self.prog_grid_lay)
  2653. prog_scroll = QtWidgets.QScrollArea()
  2654. prog_scroll.setWidget(prog_widget)
  2655. prog_scroll.setWidgetResizable(True)
  2656. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2657. prog_scroll.setPalette(pal)
  2658. self.programmmers_tab_layout.addWidget(prog_scroll)
  2659. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2660. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2661. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2662. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2663. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  2664. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2665. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2666. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 28, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 29, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 30, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 31, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 34, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2704. self.translator_grid_lay = QtWidgets.QGridLayout()
  2705. self.translator_grid_lay.setColumnStretch(0, 0)
  2706. self.translator_grid_lay.setColumnStretch(1, 0)
  2707. self.translator_grid_lay.setColumnStretch(2, 1)
  2708. self.translator_grid_lay.setColumnStretch(3, 0)
  2709. # trans_widget = QtWidgets.QWidget()
  2710. # trans_widget.setLayout(self.translator_grid_lay)
  2711. # self.translators_tab_layout.addWidget(trans_widget)
  2712. # self.translators_tab_layout.addStretch()
  2713. trans_widget = QtWidgets.QWidget()
  2714. trans_widget.setLayout(self.translator_grid_lay)
  2715. trans_scroll = QtWidgets.QScrollArea()
  2716. trans_scroll.setWidget(trans_widget)
  2717. trans_scroll.setWidgetResizable(True)
  2718. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2719. trans_scroll.setPalette(pal)
  2720. self.translators_tab_layout.addWidget(trans_scroll)
  2721. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2722. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2723. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2724. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2725. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2726. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2727. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2728. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2729. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 3, 2)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  2746. self.translator_grid_lay.setColumnStretch(0, 0)
  2747. self.translators_tab_layout.addStretch()
  2748. self.license_tab_layout.addWidget(lic_lbl_header)
  2749. self.license_tab_layout.addWidget(lic_lbl_body)
  2750. self.license_tab_layout.addStretch()
  2751. self.attributions_tab_layout.addWidget(attributions_label)
  2752. self.attributions_tab_layout.addStretch()
  2753. layout3.addStretch()
  2754. layout3.addWidget(closebtn)
  2755. closebtn.clicked.connect(self.accept)
  2756. AboutDialog(app=self, parent=self.ui).exec_()
  2757. def install_bookmarks(self, book_dict=None):
  2758. """
  2759. Install the bookmarks actions in the Help menu -> Bookmarks
  2760. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2761. :return: None
  2762. """
  2763. if book_dict is None:
  2764. self.defaults["global_bookmarks"].update(
  2765. {
  2766. '1': ['FlatCAM', "http://flatcam.org"],
  2767. '2': ['Backup Site', ""]
  2768. }
  2769. )
  2770. else:
  2771. self.defaults["global_bookmarks"].clear()
  2772. self.defaults["global_bookmarks"].update(book_dict)
  2773. # first try to disconnect if somehow they get connected from elsewhere
  2774. for act in self.ui.menuhelp_bookmarks.actions():
  2775. try:
  2776. act.triggered.disconnect()
  2777. except TypeError:
  2778. pass
  2779. # clear all actions except the last one who is the Bookmark manager
  2780. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2781. pass
  2782. else:
  2783. self.ui.menuhelp_bookmarks.removeAction(act)
  2784. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2785. if self.defaults["global_bookmarks"]:
  2786. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2787. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2788. # the JSON is first making the keys as strings (therefore I have to use strings too
  2789. # or do the conversion :(
  2790. # )
  2791. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2792. # the '10' entry jsut after '1' therefore ordering as strings
  2793. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2794. key=lambda x: int(x[0]))
  2795. for entry, bookmark in sorted_bookmarks:
  2796. title = bookmark[0]
  2797. weblink = bookmark[1]
  2798. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2799. act.setText(title)
  2800. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2801. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2802. if title == 'Backup Site' and weblink == "":
  2803. act.triggered.connect(self.on_backup_site)
  2804. else:
  2805. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2806. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2807. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2808. def on_bookmarks_manager(self):
  2809. """
  2810. Adds the bookmark manager in a Tab in Plot Area
  2811. :return:
  2812. """
  2813. for idx in range(self.ui.plot_tab_area.count()):
  2814. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2815. # there can be only one instance of Bookmark Manager at one time
  2816. return
  2817. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2818. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2819. # add the tab if it was closed
  2820. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2821. # delete the absolute and relative position and messages in the infobar
  2822. self.ui.position_label.setText("")
  2823. self.ui.rel_position_label.setText("")
  2824. # Switch plot_area to preferences page
  2825. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2826. def on_backup_site(self):
  2827. msgbox = QtWidgets.QMessageBox()
  2828. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2829. "1. FlatCAM.org website is down\n"
  2830. "2. Someone forked FlatCAM project and wants to point\n"
  2831. "to his own website\n\n"
  2832. "If you can't get any informations about FlatCAM beta\n"
  2833. "use the YouTube channel link from the Help menu."))
  2834. msgbox.setWindowTitle(_("Alternative website"))
  2835. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2836. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2837. msgbox.setDefaultButton(bt_yes)
  2838. msgbox.exec_()
  2839. # response = msgbox.clickedButton()
  2840. def on_file_savedefaults(self):
  2841. """
  2842. Callback for menu item File->Save Defaults. Saves application default options
  2843. ``self.defaults`` to current_defaults.FlatConfig.
  2844. :return: None
  2845. """
  2846. self.preferencesUiManager.save_defaults()
  2847. def final_save(self):
  2848. """
  2849. Callback for doing a preferences save to file whenever the application is about to quit.
  2850. If the project has changes, it will ask the user to save the project.
  2851. :return: None
  2852. """
  2853. if self.save_in_progress:
  2854. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2855. return
  2856. if self.should_we_save and self.collection.get_list():
  2857. msgbox = QtWidgets.QMessageBox()
  2858. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2859. "\n"
  2860. "Do you want to Save the project?"))
  2861. msgbox.setWindowTitle(_("Save changes"))
  2862. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2863. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2864. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2865. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2866. msgbox.setDefaultButton(bt_yes)
  2867. msgbox.exec_()
  2868. response = msgbox.clickedButton()
  2869. if response == bt_yes:
  2870. try:
  2871. self.trayIcon.hide()
  2872. except Exception:
  2873. pass
  2874. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2875. elif response == bt_no:
  2876. try:
  2877. self.trayIcon.hide()
  2878. except Exception:
  2879. pass
  2880. self.quit_application()
  2881. elif response == bt_cancel:
  2882. return
  2883. else:
  2884. try:
  2885. self.trayIcon.hide()
  2886. except Exception:
  2887. pass
  2888. self.quit_application()
  2889. def quit_application(self):
  2890. """
  2891. Called (as a pyslot or not) when the application is quit.
  2892. :return: None
  2893. """
  2894. self.preferencesUiManager.save_defaults(silent=True)
  2895. log.debug("App.quit_application() --> App Defaults saved.")
  2896. if self.cmd_line_headless != 1:
  2897. # save app state to file
  2898. stgs = QSettings("Open Source", "FlatCAM")
  2899. stgs.setValue('saved_gui_state', self.ui.saveState())
  2900. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2901. stgs.setValue(
  2902. 'language',
  2903. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2904. )
  2905. stgs.setValue(
  2906. 'notebook_font_size',
  2907. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2908. )
  2909. stgs.setValue(
  2910. 'axis_font_size',
  2911. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2912. )
  2913. stgs.setValue(
  2914. 'textbox_font_size',
  2915. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2916. )
  2917. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2918. stgs.setValue(
  2919. 'machinist',
  2920. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2921. )
  2922. # This will write the setting to the platform specific storage.
  2923. del stgs
  2924. log.debug("App.quit_application() --> App UI state saved.")
  2925. # try to quit the QThread that run ArgsThread class
  2926. try:
  2927. self.th.quit()
  2928. except Exception as e:
  2929. log.debug("App.quit_application() --> %s" % str(e))
  2930. # try to quit the Socket opened by ArgsThread class
  2931. try:
  2932. self.new_launch.listener.close()
  2933. except Exception as err:
  2934. log.debug("App.quit_application() --> %s" % str(err))
  2935. # quit app by signalling for self.kill_app() method
  2936. # self.close_app_signal.emit()
  2937. QtWidgets.qApp.quit()
  2938. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2939. # we use the following command
  2940. # sys.exit(0)
  2941. os._exit(0) # fix to work with Python 3.8
  2942. @staticmethod
  2943. def kill_app():
  2944. # QtCore.QCoreApplication.quit()
  2945. QtWidgets.qApp.quit()
  2946. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2947. # we use the following command
  2948. sys.exit(0)
  2949. def on_portable_checked(self, state):
  2950. """
  2951. Callback called when the checkbox in Preferences GUI is checked.
  2952. It will set the application as portable by creating the preferences and recent files in the
  2953. 'config' folder found in the FlatCAM installation folder.
  2954. :param state: boolean, the state of the checkbox when clicked/checked
  2955. :return:
  2956. """
  2957. line_no = 0
  2958. data = None
  2959. if sys.platform != 'win32':
  2960. # this won't work in Linux or MacOS
  2961. return
  2962. # test if the app was frozen and choose the path for the configuration file
  2963. if getattr(sys, "frozen", False) is True:
  2964. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2965. else:
  2966. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2967. config_file = current_data_path + '\\configuration.txt'
  2968. try:
  2969. with open(config_file, 'r') as f:
  2970. try:
  2971. data = f.readlines()
  2972. except Exception as e:
  2973. log.debug('App.__init__() -->%s' % str(e))
  2974. return
  2975. except FileNotFoundError:
  2976. pass
  2977. for line in data:
  2978. line = line.strip('\n')
  2979. param = str(line).rpartition('=')
  2980. if param[0] == 'portable':
  2981. break
  2982. line_no += 1
  2983. if state:
  2984. data[line_no] = 'portable=True\n'
  2985. # create the new defauults files
  2986. # create current_defaults.FlatConfig file if there is none
  2987. try:
  2988. f = open(current_data_path + '/current_defaults.FlatConfig')
  2989. f.close()
  2990. except IOError:
  2991. App.log.debug('Creating empty current_defaults.FlatConfig')
  2992. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2993. json.dump({}, f)
  2994. f.close()
  2995. # create factory_defaults.FlatConfig file if there is none
  2996. try:
  2997. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2998. f.close()
  2999. except IOError:
  3000. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3001. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3002. json.dump({}, f)
  3003. f.close()
  3004. try:
  3005. f = open(current_data_path + '/recent.json')
  3006. f.close()
  3007. except IOError:
  3008. App.log.debug('Creating empty recent.json')
  3009. f = open(current_data_path + '/recent.json', 'w')
  3010. json.dump([], f)
  3011. f.close()
  3012. try:
  3013. fp = open(current_data_path + '/recent_projects.json')
  3014. fp.close()
  3015. except IOError:
  3016. App.log.debug('Creating empty recent_projects.json')
  3017. fp = open(current_data_path + '/recent_projects.json', 'w')
  3018. json.dump([], fp)
  3019. fp.close()
  3020. # save the current defaults to the new defaults file
  3021. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3022. else:
  3023. data[line_no] = 'portable=False\n'
  3024. with open(config_file, 'w') as f:
  3025. f.writelines(data)
  3026. def on_register_files(self, obj_type=None):
  3027. """
  3028. Called whenever there is a need to register file extensions with FlatCAM.
  3029. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3030. :param obj_type: the type of object to be register for.
  3031. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3032. :return: None
  3033. """
  3034. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3035. new_reg_path = 'Software\\Classes\\'
  3036. # find if the current user is admin
  3037. try:
  3038. is_admin = os.getuid() == 0
  3039. except AttributeError:
  3040. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3041. if is_admin is True:
  3042. root_path = winreg.HKEY_LOCAL_MACHINE
  3043. else:
  3044. root_path = winreg.HKEY_CURRENT_USER
  3045. # create the keys
  3046. def set_reg(name, root_path, new_reg_path, value):
  3047. try:
  3048. winreg.CreateKey(root_path, new_reg_path)
  3049. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3050. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3051. return True
  3052. except WindowsError:
  3053. return False
  3054. # delete key in registry
  3055. def delete_reg(root_path, reg_path, key_to_del):
  3056. key_to_del_path = reg_path + key_to_del
  3057. try:
  3058. winreg.DeleteKey(root_path, key_to_del_path)
  3059. return True
  3060. except WindowsError:
  3061. return False
  3062. if obj_type is None or obj_type == 'excellon':
  3063. exc_list = \
  3064. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3065. exc_list = [x for x in exc_list if x != '']
  3066. # register all keys in the Preferences window
  3067. for ext in exc_list:
  3068. new_k = new_reg_path + '.%s' % ext
  3069. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3070. # and unregister those that are no longer in the Preferences windows but are in the file
  3071. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3072. if ext not in exc_list:
  3073. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3074. # now write the updated extensions to the self.defaults
  3075. # new_ext = ''
  3076. # for ext in exc_list:
  3077. # new_ext = new_ext + ext + ', '
  3078. # self.defaults["fa_excellon"] = new_ext
  3079. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3080. if obj_type is None or obj_type == 'gcode':
  3081. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3082. gco_list = [x for x in gco_list if x != '']
  3083. # register all keys in the Preferences window
  3084. for ext in gco_list:
  3085. new_k = new_reg_path + '.%s' % ext
  3086. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3087. # and unregister those that are no longer in the Preferences windows but are in the file
  3088. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3089. if ext not in gco_list:
  3090. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3091. # now write the updated extensions to the self.defaults
  3092. # new_ext = ''
  3093. # for ext in gco_list:
  3094. # new_ext = new_ext + ext + ', '
  3095. # self.defaults["fa_gcode"] = new_ext
  3096. self.inform.emit('[success] %s' %
  3097. _("Selected GCode file extensions registered with FlatCAM."))
  3098. if obj_type is None or obj_type == 'gerber':
  3099. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3100. grb_list = [x for x in grb_list if x != '']
  3101. # register all keys in the Preferences window
  3102. for ext in grb_list:
  3103. new_k = new_reg_path + '.%s' % ext
  3104. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3105. # and unregister those that are no longer in the Preferences windows but are in the file
  3106. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3107. if ext not in grb_list:
  3108. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3109. # now write the updated extensions to the self.defaults
  3110. # new_ext = ''
  3111. # for ext in grb_list:
  3112. # new_ext = new_ext + ext + ', '
  3113. # self.defaults["fa_gerber"] = new_ext
  3114. self.inform.emit('[success] %s' %
  3115. _("Selected Gerber file extensions registered with FlatCAM."))
  3116. def add_extension(self, ext_type):
  3117. """
  3118. Add a file extension to the list for a specific object
  3119. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3120. :return:
  3121. """
  3122. if ext_type == 'excellon':
  3123. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3124. if new_ext == '':
  3125. return
  3126. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3127. if new_ext in old_val:
  3128. return
  3129. old_val.append(new_ext)
  3130. old_val.sort()
  3131. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3132. if ext_type == 'gcode':
  3133. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3134. if new_ext == '':
  3135. return
  3136. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3137. if new_ext in old_val:
  3138. return
  3139. old_val.append(new_ext)
  3140. old_val.sort()
  3141. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3142. if ext_type == 'gerber':
  3143. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3144. if new_ext == '':
  3145. return
  3146. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3147. if new_ext in old_val:
  3148. return
  3149. old_val.append(new_ext)
  3150. old_val.sort()
  3151. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3152. if ext_type == 'keyword':
  3153. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3154. if new_kw == '':
  3155. return
  3156. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3157. if new_kw in old_val:
  3158. return
  3159. old_val.append(new_kw)
  3160. old_val.sort()
  3161. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3162. # update the self.myKeywords so the model is updated
  3163. self.autocomplete_kw_list = \
  3164. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3165. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3166. self.shell._edit.set_model_data(self.myKeywords)
  3167. def del_extension(self, ext_type):
  3168. """
  3169. Remove a file extension from the list for a specific object
  3170. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3171. :return:
  3172. """
  3173. if ext_type == 'excellon':
  3174. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3175. if new_ext == '':
  3176. return
  3177. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3178. if new_ext not in old_val:
  3179. return
  3180. old_val.remove(new_ext)
  3181. old_val.sort()
  3182. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3183. if ext_type == 'gcode':
  3184. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3185. if new_ext == '':
  3186. return
  3187. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3188. if new_ext not in old_val:
  3189. return
  3190. old_val.remove(new_ext)
  3191. old_val.sort()
  3192. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3193. if ext_type == 'gerber':
  3194. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3195. if new_ext == '':
  3196. return
  3197. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3198. if new_ext not in old_val:
  3199. return
  3200. old_val.remove(new_ext)
  3201. old_val.sort()
  3202. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3203. if ext_type == 'keyword':
  3204. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3205. if new_kw == '':
  3206. return
  3207. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3208. if new_kw not in old_val:
  3209. return
  3210. old_val.remove(new_kw)
  3211. old_val.sort()
  3212. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3213. # update the self.myKeywords so the model is updated
  3214. self.autocomplete_kw_list = \
  3215. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3216. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3217. self.shell._edit.set_model_data(self.myKeywords)
  3218. def restore_extensions(self, ext_type):
  3219. """
  3220. Restore all file extensions associations with FlatCAM, for a specific object
  3221. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3222. :return:
  3223. """
  3224. if ext_type == 'excellon':
  3225. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3226. # for the ability to open Excellon files with .txt extension
  3227. new_exc_list = deepcopy(self.exc_list)
  3228. try:
  3229. new_exc_list.remove('txt')
  3230. except ValueError:
  3231. pass
  3232. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3233. if ext_type == 'gcode':
  3234. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3235. if ext_type == 'gerber':
  3236. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3237. if ext_type == 'keyword':
  3238. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3239. # update the self.myKeywords so the model is updated
  3240. self.autocomplete_kw_list = self.default_keywords
  3241. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3242. self.shell._edit.set_model_data(self.myKeywords)
  3243. def delete_all_extensions(self, ext_type):
  3244. """
  3245. Delete all file extensions associations with FlatCAM, for a specific object
  3246. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3247. :return:
  3248. """
  3249. if ext_type == 'excellon':
  3250. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3251. if ext_type == 'gcode':
  3252. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3253. if ext_type == 'gerber':
  3254. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3255. if ext_type == 'keyword':
  3256. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3257. # update the self.myKeywords so the model is updated
  3258. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3259. self.shell._edit.set_model_data(self.myKeywords)
  3260. def on_edit_join(self, name=None):
  3261. """
  3262. Callback for Edit->Join. Joins the selected geometry objects into
  3263. a new one.
  3264. :return: None
  3265. """
  3266. self.defaults.report_usage("on_edit_join()")
  3267. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3268. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3269. geo_type_set = set()
  3270. objs = self.collection.get_selected()
  3271. if len(objs) < 2:
  3272. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3273. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3274. return 'fail'
  3275. for obj in objs:
  3276. geo_type_set.add(obj.multigeo)
  3277. # if len(geo_type_list) == 1 means that all list elements are the same
  3278. if len(geo_type_set) != 1:
  3279. self.inform.emit('[ERROR] %s' %
  3280. _("Failed join. The Geometry objects are of different types.\n"
  3281. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3282. "convert from one to another and retry joining \n"
  3283. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3284. "the result may not be what was expected. \n"
  3285. "Check the generated GCODE."))
  3286. return
  3287. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3288. if True in geo_type_set:
  3289. def initialize(geo_obj, app):
  3290. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  3291. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3292. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3293. for v in geo_obj.tools.values():
  3294. v['data']['name'] = obj_name_multi
  3295. self.new_object("geometry", obj_name_multi, initialize)
  3296. else:
  3297. def initialize(geo_obj, app):
  3298. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  3299. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3300. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3301. for v in geo_obj.tools.values():
  3302. v['data']['name'] = obj_name_single
  3303. self.new_object("geometry", obj_name_single, initialize)
  3304. self.should_we_save = True
  3305. def on_edit_join_exc(self):
  3306. """
  3307. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3308. a new Excellon.
  3309. :return: None
  3310. """
  3311. self.defaults.report_usage("on_edit_join_exc()")
  3312. objs = self.collection.get_selected()
  3313. for obj in objs:
  3314. if not isinstance(obj, ExcellonObject):
  3315. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3316. return
  3317. if len(objs) < 2:
  3318. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3319. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3320. return 'fail'
  3321. def initialize(exc_obj, app):
  3322. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj)
  3323. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3324. self.new_object("excellon", 'Combo_Excellon', initialize)
  3325. self.should_we_save = True
  3326. def on_edit_join_grb(self):
  3327. """
  3328. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3329. a new Gerber object.
  3330. :return: None
  3331. """
  3332. self.defaults.report_usage("on_edit_join_grb()")
  3333. objs = self.collection.get_selected()
  3334. for obj in objs:
  3335. if not isinstance(obj, GerberObject):
  3336. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3337. return
  3338. if len(objs) < 2:
  3339. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3340. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3341. return 'fail'
  3342. def initialize(grb_obj, app):
  3343. GerberObject.merge(self, grb_list=objs, grb_final=grb_obj)
  3344. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3345. self.new_object("gerber", 'Combo_Gerber', initialize)
  3346. self.should_we_save = True
  3347. def on_convert_singlegeo_to_multigeo(self):
  3348. """
  3349. Called for converting a Geometry object from single-geo to multi-geo.
  3350. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3351. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3352. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3353. the solid-geometry of that tool.
  3354. :return: None
  3355. """
  3356. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3357. obj = self.collection.get_active()
  3358. if obj is None:
  3359. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3360. return
  3361. if not isinstance(obj, GeometryObject):
  3362. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3363. return
  3364. obj.multigeo = True
  3365. for tooluid, dict_value in obj.tools.items():
  3366. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3367. if not isinstance(obj.solid_geometry, list):
  3368. obj.solid_geometry = [obj.solid_geometry]
  3369. obj.solid_geometry[:] = []
  3370. obj.plot()
  3371. self.should_we_save = True
  3372. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3373. def on_convert_multigeo_to_singlegeo(self):
  3374. """
  3375. Called for converting a Geometry object from multi-geo to single-geo.
  3376. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3377. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3378. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3379. the solid-geometry of that tool.
  3380. :return: None
  3381. """
  3382. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3383. obj = self.collection.get_active()
  3384. if obj is None:
  3385. self.inform.emit('[ERROR_NOTCL] %s' %
  3386. _("Failed. Select a Geometry Object and try again."))
  3387. return
  3388. if not isinstance(obj, GeometryObject):
  3389. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3390. (_("Expected a GeometryObject, got"), type(obj)))
  3391. return
  3392. obj.multigeo = False
  3393. total_solid_geometry = []
  3394. for tooluid, dict_value in obj.tools.items():
  3395. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3396. # clear the original geometry
  3397. dict_value['solid_geometry'][:] = []
  3398. obj.solid_geometry = deepcopy(total_solid_geometry)
  3399. obj.plot()
  3400. self.should_we_save = True
  3401. self.inform.emit('[success] %s' %
  3402. _("A Geometry object was converted to SingleGeo type."))
  3403. def on_defaults_dict_change(self, field):
  3404. """
  3405. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3406. Edit -> Preferences tab window.
  3407. :param field: the key of the self.defaults dictionary that was changed.
  3408. :return: None
  3409. """
  3410. self.preferencesUiManager.defaults_write_form_field(field=field)
  3411. if field == "units":
  3412. self.set_screen_units(self.defaults['units'])
  3413. def set_screen_units(self, units):
  3414. """
  3415. Set the FlatCAM units on the status bar.
  3416. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3417. :return: None
  3418. """
  3419. self.ui.units_label.setText("[" + units.lower() + "]")
  3420. def on_toggle_units_click(self):
  3421. try:
  3422. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3423. except (TypeError, AttributeError):
  3424. pass
  3425. if self.defaults["units"] == 'MM':
  3426. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3427. else:
  3428. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3429. self.on_toggle_units(no_pref=True)
  3430. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3431. lambda: self.on_toggle_units(no_pref=False))
  3432. def on_toggle_units(self, no_pref=False):
  3433. """
  3434. Callback for the Units radio-button change in the Preferences tab.
  3435. Changes the application's default units adn for the project too.
  3436. If changing the project's units, the change propagates to all of
  3437. the objects in the project.
  3438. :return: None
  3439. """
  3440. self.defaults.report_usage("on_toggle_units")
  3441. if self.toggle_units_ignore:
  3442. return
  3443. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3444. # If option is the same, then ignore
  3445. if new_units == self.defaults["units"].upper():
  3446. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3447. return
  3448. # Options to scale
  3449. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  3450. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3451. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3452. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3453. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3454. "excellon_feedrate_probe",
  3455. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3456. "excellon_editor_slot_lin_pitch",
  3457. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3458. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3459. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3460. "geometry_z_pdepth",
  3461. "geometry_feedrate_probe", "geometry_startz",
  3462. 'cncjob_tooldia',
  3463. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3464. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3465. "tools_nccnewdia",
  3466. "tools_2sided_drilldia", "tools_film_boundary",
  3467. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3468. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3469. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3470. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3471. "tools_transform_offset_y",
  3472. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3473. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3474. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3475. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3476. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3477. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3478. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  3479. "tools_fiducials_line_thickness",
  3480. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3481. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3482. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3483. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3484. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3485. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3486. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3487. def scale_defaults(sfactor):
  3488. for dim in dimensions:
  3489. if dim == 'excellon_toolchangexy':
  3490. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3491. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3492. coords_xy[0] *= sfactor
  3493. coords_xy[1] *= sfactor
  3494. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3495. self.decimals, coords_xy[1])
  3496. elif dim == 'geometry_toolchangexy':
  3497. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3498. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3499. coords_xy[0] *= sfactor
  3500. coords_xy[1] *= sfactor
  3501. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3502. self.decimals, coords_xy[1])
  3503. elif dim == 'excellon_endxy':
  3504. coordinates = self.defaults["excellon_endxy"].split(",")
  3505. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3506. end_coords_xy[0] *= sfactor
  3507. end_coords_xy[1] *= sfactor
  3508. self.defaults['excellon_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3509. self.decimals, end_coords_xy[1])
  3510. elif dim == 'geometry_endxy':
  3511. coordinates = self.defaults["geometry_endxy"].split(",")
  3512. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3513. end_coords_xy[0] *= sfactor
  3514. end_coords_xy[1] *= sfactor
  3515. self.defaults['geometry_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3516. self.decimals, end_coords_xy[1])
  3517. elif dim == 'geometry_cnctooldia':
  3518. if type(self.defaults["geometry_cnctooldia"]) == float:
  3519. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  3520. else:
  3521. try:
  3522. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3523. tools_diameters = [eval(a) for a in tools_string if a != '']
  3524. except Exception as e:
  3525. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3526. continue
  3527. self.defaults['geometry_cnctooldia'] = ''
  3528. for t in range(len(tools_diameters)):
  3529. tools_diameters[t] *= sfactor
  3530. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  3531. elif dim == 'tools_ncctools':
  3532. if type(self.defaults["tools_ncctools"]) == float:
  3533. ncctools = [self.defaults["tools_ncctools"]]
  3534. else:
  3535. try:
  3536. tools_string = self.defaults["tools_ncctools"].split(",")
  3537. ncctools = [eval(a) for a in tools_string if a != '']
  3538. except Exception as e:
  3539. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3540. continue
  3541. self.defaults['tools_ncctools'] = ''
  3542. for t in range(len(ncctools)):
  3543. ncctools[t] *= sfactor
  3544. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  3545. elif dim == 'tools_solderpaste_tools':
  3546. if type(self.defaults["tools_solderpaste_tools"]) == float:
  3547. sptools = [self.defaults["tools_solderpaste_tools"]]
  3548. else:
  3549. try:
  3550. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3551. sptools = [eval(a) for a in tools_string if a != '']
  3552. except Exception as e:
  3553. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3554. continue
  3555. self.defaults['tools_solderpaste_tools'] = ""
  3556. for t in range(len(sptools)):
  3557. sptools[t] *= sfactor
  3558. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  3559. elif dim == 'tools_solderpaste_xy_toolchange':
  3560. try:
  3561. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3562. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3563. sp_coords[0] *= sfactor
  3564. sp_coords[1] *= sfactor
  3565. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  3566. self.decimals, sp_coords[1])
  3567. except Exception as e:
  3568. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3569. continue
  3570. elif dim == 'global_gridx' or dim == 'global_gridy':
  3571. if new_units == 'IN':
  3572. try:
  3573. val = float(self.defaults[dim]) * sfactor
  3574. except Exception as e:
  3575. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3576. continue
  3577. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3578. else:
  3579. try:
  3580. val = float(self.defaults[dim]) * sfactor
  3581. except Exception as e:
  3582. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3583. continue
  3584. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3585. else:
  3586. if self.defaults[dim]:
  3587. try:
  3588. val = float(self.defaults[dim]) * sfactor
  3589. except Exception as e:
  3590. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3591. continue
  3592. self.defaults[dim] = val
  3593. # The scaling factor depending on choice of units.
  3594. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3595. # Changing project units. Warn user.
  3596. msgbox = QtWidgets.QMessageBox()
  3597. msgbox.setWindowTitle(_("Toggle Units"))
  3598. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3599. msgbox.setText(_("Changing the units of the project\n"
  3600. "will scale all objects.\n\n"
  3601. "Do you want to continue?"))
  3602. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3603. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3604. msgbox.setDefaultButton(bt_ok)
  3605. msgbox.exec_()
  3606. response = msgbox.clickedButton()
  3607. if response == bt_ok:
  3608. if no_pref is False:
  3609. self.preferencesUiManager.defaults_read_form()
  3610. scale_defaults(factor)
  3611. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3612. self.defaults["units"] = new_units
  3613. # update the defaults from form, some may assume that the conversion is enough and it's not
  3614. self.on_options_app2project()
  3615. # update the objects
  3616. for obj in self.collection.get_list():
  3617. obj.convert_units(new_units)
  3618. # make that the properties stored in the object are also updated
  3619. self.object_changed.emit(obj)
  3620. # rebuild the object UI
  3621. obj.build_ui()
  3622. # change this only if the workspace is active
  3623. if self.defaults['global_workspace'] is True:
  3624. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3625. # adjust the grid values on the main toolbar
  3626. val_x = float(self.defaults['global_gridx']) * factor
  3627. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3628. current = self.collection.get_active()
  3629. if current is not None:
  3630. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3631. if not isinstance(current, GeometryObject):
  3632. current.to_form()
  3633. # replot all objects
  3634. self.plot_all()
  3635. # set the status labels to reflect the current FlatCAM units
  3636. self.set_screen_units(new_units)
  3637. # signal to the app that we changed the object properties and it shoud save the project
  3638. self.should_we_save = True
  3639. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3640. else:
  3641. # Undo toggling
  3642. self.toggle_units_ignore = True
  3643. if self.defaults['units'].upper() == 'MM':
  3644. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3645. else:
  3646. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3647. self.toggle_units_ignore = False
  3648. # store the grid values so they are not changed in the next step
  3649. val_x = float(self.defaults['global_gridx'])
  3650. val_y = float(self.defaults['global_gridy'])
  3651. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3652. self.preferencesUiManager.defaults_read_form()
  3653. # the self.preferencesUiManager.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  3654. # I don't want it for the grid values, so I update them here
  3655. self.defaults['global_gridx'] = val_x
  3656. self.defaults['global_gridy'] = val_y
  3657. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3658. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3659. def on_fullscreen(self, disable=False):
  3660. self.defaults.report_usage("on_fullscreen()")
  3661. flags = self.ui.windowFlags()
  3662. if self.toggle_fscreen is False and disable is False:
  3663. # self.ui.showFullScreen()
  3664. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3665. a = self.ui.geometry()
  3666. self.x_pos = a.x()
  3667. self.y_pos = a.y()
  3668. self.width = a.width()
  3669. self.height = a.height()
  3670. # set new geometry to full desktop rect
  3671. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3672. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3673. # everything else will not work without this hack. This happen in Windows.
  3674. # https://bugreports.qt.io/browse/QTBUG-41309
  3675. desktop = QtWidgets.QApplication.desktop()
  3676. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3677. rec = desktop.screenGeometry(screen)
  3678. x = rec.x() - 1
  3679. y = rec.y() - 1
  3680. h = rec.height() + 2
  3681. w = rec.width() + 2
  3682. self.ui.setGeometry(x, y, w, h)
  3683. self.ui.show()
  3684. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3685. tb.setVisible(False)
  3686. self.ui.splitter_left.setVisible(False)
  3687. self.toggle_fscreen = True
  3688. elif self.toggle_fscreen is True or disable is True:
  3689. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3690. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3691. self.ui.showNormal()
  3692. self.restore_toolbar_view()
  3693. self.ui.splitter_left.setVisible(True)
  3694. self.toggle_fscreen = False
  3695. def on_toggle_plotarea(self):
  3696. self.defaults.report_usage("on_toggle_plotarea()")
  3697. try:
  3698. name = self.ui.plot_tab_area.widget(0).objectName()
  3699. except AttributeError:
  3700. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3701. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3702. self.ui.plot_tab_area.protectTab(0)
  3703. return
  3704. if name != 'plotarea':
  3705. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3706. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3707. self.ui.plot_tab_area.protectTab(0)
  3708. else:
  3709. self.ui.plot_tab_area.closeTab(0)
  3710. def on_toggle_notebook(self):
  3711. if self.ui.splitter.sizes()[0] == 0:
  3712. self.ui.splitter.setSizes([1, 1])
  3713. self.ui.menu_toggle_nb.setChecked(True)
  3714. else:
  3715. self.ui.splitter.setSizes([0, 1])
  3716. self.ui.menu_toggle_nb.setChecked(False)
  3717. def on_toggle_axis(self):
  3718. self.defaults.report_usage("on_toggle_axis()")
  3719. if self.toggle_axis is False:
  3720. if self.is_legacy is False:
  3721. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3722. parent=self.plotcanvas.view.scene)
  3723. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3724. parent=self.plotcanvas.view.scene)
  3725. else:
  3726. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3727. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3728. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3729. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3730. self.plotcanvas.canvas.draw()
  3731. self.toggle_axis = True
  3732. else:
  3733. if self.is_legacy is False:
  3734. self.plotcanvas.v_line.parent = None
  3735. self.plotcanvas.h_line.parent = None
  3736. else:
  3737. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3738. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3739. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3740. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3741. self.plotcanvas.canvas.draw()
  3742. self.toggle_axis = False
  3743. def on_toggle_grid(self):
  3744. self.defaults.report_usage("on_toggle_grid()")
  3745. self.ui.grid_snap_btn.trigger()
  3746. self.on_grid_snap_triggered(state=True)
  3747. def on_toggle_grid_lines(self):
  3748. self.defaults.report_usage("on_toggle_grd_lines()")
  3749. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3750. if tt_settings.contains("theme"):
  3751. theme = tt_settings.value('theme', type=str)
  3752. else:
  3753. theme = 'white'
  3754. if self.toggle_grid_lines is False:
  3755. if self.is_legacy is False:
  3756. if theme == 'white':
  3757. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3758. else:
  3759. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3760. else:
  3761. self.plotcanvas.axes.grid(True)
  3762. try:
  3763. self.plotcanvas.canvas.draw()
  3764. except IndexError:
  3765. pass
  3766. pass
  3767. self.toggle_grid_lines = True
  3768. else:
  3769. if self.is_legacy is False:
  3770. if theme == 'white':
  3771. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3772. else:
  3773. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3774. else:
  3775. self.plotcanvas.axes.grid(False)
  3776. try:
  3777. self.plotcanvas.canvas.draw()
  3778. except IndexError:
  3779. pass
  3780. self.toggle_grid_lines = False
  3781. if self.is_legacy is False:
  3782. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3783. # - perhaps is a bug in VisPy implementation
  3784. if self.grid_status() is True:
  3785. self.app_cursor.enabled = False
  3786. self.app_cursor.enabled = True
  3787. else:
  3788. self.app_cursor.enabled = True
  3789. self.app_cursor.enabled = False
  3790. def on_update_exc_export(self, state):
  3791. """
  3792. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3793. if the update_excellon_cb checkbox is checked
  3794. :param state: state of the checkbox whose signals is tied to his slot
  3795. :return:
  3796. """
  3797. if state:
  3798. # first try to disconnect
  3799. try:
  3800. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3801. disconnect(self.on_excellon_format_changed)
  3802. except TypeError:
  3803. pass
  3804. try:
  3805. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3806. disconnect(self.on_excellon_format_changed)
  3807. except TypeError:
  3808. pass
  3809. try:
  3810. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3811. disconnect(self.on_excellon_format_changed)
  3812. except TypeError:
  3813. pass
  3814. try:
  3815. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3816. disconnect(self.on_excellon_format_changed)
  3817. except TypeError:
  3818. pass
  3819. try:
  3820. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3821. disconnect(self.on_excellon_zeros_changed)
  3822. except TypeError:
  3823. pass
  3824. try:
  3825. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3826. disconnect(self.on_excellon_zeros_changed)
  3827. except TypeError:
  3828. pass
  3829. # the connect them
  3830. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3831. self.on_excellon_format_changed)
  3832. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3833. self.on_excellon_format_changed)
  3834. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3835. self.on_excellon_format_changed)
  3836. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3837. self.on_excellon_format_changed)
  3838. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3839. self.on_excellon_zeros_changed)
  3840. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3841. self.on_excellon_units_changed)
  3842. else:
  3843. # disconnect the signals
  3844. try:
  3845. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3846. disconnect(self.on_excellon_format_changed)
  3847. except TypeError:
  3848. pass
  3849. try:
  3850. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3851. disconnect(self.on_excellon_format_changed)
  3852. except TypeError:
  3853. pass
  3854. try:
  3855. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3856. disconnect(self.on_excellon_format_changed)
  3857. except TypeError:
  3858. pass
  3859. try:
  3860. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3861. disconnect(self.on_excellon_format_changed)
  3862. except TypeError:
  3863. pass
  3864. try:
  3865. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3866. disconnect(self.on_excellon_zeros_changed)
  3867. except TypeError:
  3868. pass
  3869. try:
  3870. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3871. disconnect(self.on_excellon_zeros_changed)
  3872. except TypeError:
  3873. pass
  3874. def on_excellon_format_changed(self):
  3875. """
  3876. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3877. :return: None
  3878. """
  3879. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3880. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3881. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3882. )
  3883. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3884. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3885. )
  3886. else:
  3887. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3888. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3889. )
  3890. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3891. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3892. )
  3893. def on_excellon_zeros_changed(self):
  3894. """
  3895. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3896. :return: None
  3897. """
  3898. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3899. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3900. )
  3901. def on_excellon_units_changed(self):
  3902. """
  3903. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3904. :return: None
  3905. """
  3906. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3907. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3908. )
  3909. self.on_excellon_format_changed()
  3910. def on_film_color_entry(self):
  3911. self.defaults['tools_film_color'] = \
  3912. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3913. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3914. "background-color:%s;"
  3915. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3916. )
  3917. def on_film_color_button(self):
  3918. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3919. c_dialog = QtWidgets.QColorDialog()
  3920. film_color = c_dialog.getColor(initial=current_color)
  3921. if film_color.isValid() is False:
  3922. return
  3923. # if new color is different then mark that the Preferences are changed
  3924. if film_color != current_color:
  3925. self.preferencesUiManager.on_preferences_edited()
  3926. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3927. "background-color:%s;"
  3928. "border-color: dimgray" % str(film_color.name())
  3929. )
  3930. new_val_sel = str(film_color.name())
  3931. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3932. self.defaults['tools_film_color'] = new_val_sel
  3933. def on_qrcode_fill_color_entry(self):
  3934. self.defaults['tools_qrcode_fill_color'] = \
  3935. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3936. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3937. "background-color:%s;"
  3938. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3939. )
  3940. def on_qrcode_fill_color_button(self):
  3941. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3942. c_dialog = QtWidgets.QColorDialog()
  3943. fill_color = c_dialog.getColor(initial=current_color)
  3944. if fill_color.isValid() is False:
  3945. return
  3946. # if new color is different then mark that the Preferences are changed
  3947. if fill_color != current_color:
  3948. self.preferencesUiManager.on_preferences_edited()
  3949. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3950. "background-color:%s;"
  3951. "border-color: dimgray" % str(fill_color.name())
  3952. )
  3953. new_val_sel = str(fill_color.name())
  3954. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3955. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3956. def on_qrcode_back_color_entry(self):
  3957. self.defaults['tools_qrcode_back_color'] = \
  3958. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3959. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3960. "background-color:%s;"
  3961. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3962. )
  3963. def on_qrcode_back_color_button(self):
  3964. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3965. c_dialog = QtWidgets.QColorDialog()
  3966. back_color = c_dialog.getColor(initial=current_color)
  3967. if back_color.isValid() is False:
  3968. return
  3969. # if new color is different then mark that the Preferences are changed
  3970. if back_color != current_color:
  3971. self.preferencesUiManager.on_preferences_edited()
  3972. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3973. "background-color:%s;"
  3974. "border-color: dimgray" % str(back_color.name())
  3975. )
  3976. new_val_sel = str(back_color.name())
  3977. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3978. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3979. def on_tab_rmb_click(self, checked):
  3980. self.ui.notebook.set_detachable(val=checked)
  3981. self.defaults["global_tabs_detachable"] = checked
  3982. self.ui.plot_tab_area.set_detachable(val=checked)
  3983. self.defaults["global_tabs_detachable"] = checked
  3984. def on_tab_setup_context_menu(self):
  3985. initial_checked = self.defaults["global_tabs_detachable"]
  3986. action_name = str(_("Detachable Tabs"))
  3987. action = QtWidgets.QAction(self)
  3988. action.setCheckable(True)
  3989. action.setText(action_name)
  3990. action.setChecked(initial_checked)
  3991. self.ui.notebook.tabBar.addAction(action)
  3992. self.ui.plot_tab_area.tabBar.addAction(action)
  3993. try:
  3994. action.triggered.disconnect()
  3995. except TypeError:
  3996. pass
  3997. action.triggered.connect(self.on_tab_rmb_click)
  3998. def on_deselect_all(self):
  3999. self.collection.set_all_inactive()
  4000. self.delete_selection_shape()
  4001. def on_workspace_modified(self):
  4002. # self.save_defaults(silent=True)
  4003. if self.is_legacy is True:
  4004. self.plotcanvas.delete_workspace()
  4005. self.preferencesUiManager.defaults_read_form()
  4006. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4007. def on_workspace(self):
  4008. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4009. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4010. else:
  4011. self.plotcanvas.delete_workspace()
  4012. self.preferencesUiManager.defaults_read_form()
  4013. # self.save_defaults(silent=True)
  4014. def on_workspace_toggle(self):
  4015. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4016. try:
  4017. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4018. except TypeError:
  4019. pass
  4020. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4021. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4022. self.on_workspace()
  4023. def on_cursor_type(self, val):
  4024. """
  4025. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4026. :return: None
  4027. """
  4028. self.app_cursor.enabled = False
  4029. if val == 'small':
  4030. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4031. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4032. self.app_cursor = self.plotcanvas.new_cursor()
  4033. else:
  4034. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4035. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4036. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4037. if self.ui.grid_snap_btn.isChecked():
  4038. self.app_cursor.enabled = True
  4039. else:
  4040. self.app_cursor.enabled = False
  4041. def on_tool_add_keypress(self):
  4042. # ## Current application units in Upper Case
  4043. self.units = self.defaults['units'].upper()
  4044. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4045. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4046. if notebook_widget_name == 'selected_tab':
  4047. if self.collection.get_active().kind == 'geometry':
  4048. # Tool add works for Geometry only if Advanced is True in Preferences
  4049. if self.defaults["global_app_level"] == 'a':
  4050. tool_add_popup = FCInputDialog(title="New Tool ...",
  4051. text='Enter a Tool Diameter:',
  4052. min=0.0000, max=99.9999, decimals=4)
  4053. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4054. val, ok = tool_add_popup.get_value()
  4055. if ok:
  4056. if float(val) == 0:
  4057. self.inform.emit('[WARNING_NOTCL] %s' %
  4058. _("Please enter a tool diameter with non-zero value, in Float format."))
  4059. return
  4060. self.collection.get_active().on_tool_add(dia=float(val))
  4061. else:
  4062. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4063. else:
  4064. msgbox = QtWidgets.QMessageBox()
  4065. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4066. "Go to Preferences -> General - Show Advanced Options."))
  4067. msgbox.setWindowTitle("Tool adding ...")
  4068. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4069. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4070. msgbox.setDefaultButton(bt_ok)
  4071. msgbox.exec_()
  4072. # work only if the notebook tab on focus is the Tools_Tab
  4073. if notebook_widget_name == 'tool_tab':
  4074. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4075. # and only if the tool is NCC Tool
  4076. if tool_widget == self.ncclear_tool.toolName:
  4077. self.ncclear_tool.on_add_tool_by_key()
  4078. # and only if the tool is Paint Area Tool
  4079. elif tool_widget == self.paint_tool.toolName:
  4080. self.paint_tool.on_add_tool_by_key()
  4081. # and only if the tool is Solder Paste Dispensing Tool
  4082. elif tool_widget == self.paste_tool.toolName:
  4083. self.paste_tool.on_add_tool_by_key()
  4084. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4085. # See description bellow.
  4086. def on_delete_keypress(self):
  4087. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4088. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4089. if notebook_widget_name == 'selected_tab':
  4090. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4091. self.collection.get_active().on_tool_delete()
  4092. # work only if the notebook tab on focus is the Tools_Tab
  4093. elif notebook_widget_name == 'tool_tab':
  4094. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4095. # and only if the tool is NCC Tool
  4096. if tool_widget == self.ncclear_tool.toolName:
  4097. self.ncclear_tool.on_tool_delete()
  4098. # and only if the tool is Paint Tool
  4099. elif tool_widget == self.paint_tool.toolName:
  4100. self.paint_tool.on_tool_delete()
  4101. # and only if the tool is Solder Paste Dispensing Tool
  4102. elif tool_widget == self.paste_tool.toolName:
  4103. self.paste_tool.on_tool_delete()
  4104. else:
  4105. self.on_delete()
  4106. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4107. # some screens you have to be careful where you hover with your mouse.
  4108. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4109. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4110. # Complicated, I know :)
  4111. def on_delete(self, force_deletion=False):
  4112. """
  4113. Delete the currently selected FlatCAMObjs.
  4114. :param force_deletion: used by Tcl command
  4115. :return: None
  4116. """
  4117. self.defaults.report_usage("on_delete()")
  4118. response = None
  4119. bt_ok = None
  4120. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4121. # a geometry object before we update it.
  4122. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4123. and self.grb_editor.editor_active is False:
  4124. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4125. msgbox = QtWidgets.QMessageBox()
  4126. msgbox.setWindowTitle(_("Delete objects"))
  4127. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4128. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4129. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4130. "the selected objects?"))
  4131. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4132. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4133. msgbox.setDefaultButton(bt_ok)
  4134. msgbox.exec_()
  4135. response = msgbox.clickedButton()
  4136. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4137. response = bt_ok
  4138. if response == bt_ok:
  4139. if self.collection.get_active():
  4140. self.log.debug("App.on_delete()")
  4141. for obj_active in self.collection.get_selected():
  4142. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4143. if isinstance(obj_active, GerberObject):
  4144. for el in obj_active.mark_shapes:
  4145. obj_active.mark_shapes[el].clear(update=True)
  4146. obj_active.mark_shapes[el].enabled = False
  4147. # obj_active.mark_shapes[el] = None
  4148. del el
  4149. elif isinstance(obj_active, CNCJobObject):
  4150. try:
  4151. obj_active.text_col.enabled = False
  4152. del obj_active.text_col
  4153. obj_active.annotation.clear(update=True)
  4154. del obj_active.annotation
  4155. except AttributeError as e:
  4156. log.debug(
  4157. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4158. )
  4159. while self.collection.get_selected():
  4160. self.delete_first_selected()
  4161. self.inform.emit('%s...' % _("Object(s) deleted"))
  4162. # make sure that the selection shape is deleted, too
  4163. self.delete_selection_shape()
  4164. else:
  4165. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4166. else:
  4167. self.inform.emit(_("Save the work in Editor and try again ..."))
  4168. def delete_first_selected(self):
  4169. # Keep this for later
  4170. try:
  4171. sel_obj = self.collection.get_active()
  4172. name = sel_obj.options["name"]
  4173. isPlotted = sel_obj.options["plot"]
  4174. except AttributeError:
  4175. self.log.debug("Nothing selected for deletion")
  4176. return
  4177. if self.is_legacy is True:
  4178. # Remove plot only if the object was plotted otherwise delaxes will fail
  4179. if isPlotted:
  4180. try:
  4181. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4182. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4183. except Exception as e:
  4184. log.debug("App.delete_first_selected() --> %s" % str(e))
  4185. self.plotcanvas.auto_adjust_axes()
  4186. # Remove from dictionary
  4187. self.collection.delete_active()
  4188. # Clear form
  4189. self.setup_component_editor()
  4190. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4191. def on_set_origin(self):
  4192. """
  4193. Set the origin to the left mouse click position
  4194. :return: None
  4195. """
  4196. # display the message for the user
  4197. # and ask him to click on the desired position
  4198. self.defaults.report_usage("on_set_origin()")
  4199. def origin_replot():
  4200. def worker_task():
  4201. with self.proc_container.new('%s...' % _("Plotting")):
  4202. for obj in self.collection.get_list():
  4203. obj.plot()
  4204. self.plotcanvas.fit_view()
  4205. if self.is_legacy:
  4206. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4207. else:
  4208. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4209. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4210. self.inform.emit(_('Click to set the origin ...'))
  4211. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4212. # first disconnect it as it may have been used by something else
  4213. try:
  4214. self.replot_signal.disconnect()
  4215. except TypeError:
  4216. pass
  4217. self.replot_signal[list].connect(origin_replot)
  4218. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4219. """
  4220. :param event:
  4221. :param location:
  4222. :param noplot:
  4223. :param use_thread:
  4224. :return:
  4225. """
  4226. noplot_sig = noplot
  4227. def worker_task():
  4228. with self.proc_container.new(_("Setting Origin...")):
  4229. obj_list = self.collection.get_list()
  4230. for obj in obj_list:
  4231. obj.offset((x, y))
  4232. self.object_changed.emit(obj)
  4233. # Update the object bounding box options
  4234. a, b, c, d = obj.bounds()
  4235. obj.options['xmin'] = a
  4236. obj.options['ymin'] = b
  4237. obj.options['xmax'] = c
  4238. obj.options['ymax'] = d
  4239. self.inform.emit('[success] %s...' % _('Origin set'))
  4240. for obj in obj_list:
  4241. out_name = obj.options["name"]
  4242. if obj.kind == 'gerber':
  4243. obj.source_file = self.export_gerber(
  4244. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4245. elif obj.kind == 'excellon':
  4246. obj.source_file = self.export_excellon(
  4247. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4248. if noplot_sig is False:
  4249. self.replot_signal.emit([])
  4250. if location is not None:
  4251. if len(location) != 2:
  4252. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4253. return 'fail'
  4254. x, y = location
  4255. if use_thread is True:
  4256. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4257. else:
  4258. worker_task()
  4259. self.should_we_save = True
  4260. return
  4261. if event.button == 1:
  4262. if self.is_legacy is False:
  4263. event_pos = event.pos
  4264. else:
  4265. event_pos = (event.xdata, event.ydata)
  4266. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4267. if self.grid_status():
  4268. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4269. else:
  4270. pos = pos_canvas
  4271. x = 0 - pos[0]
  4272. y = 0 - pos[1]
  4273. if use_thread is True:
  4274. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4275. else:
  4276. worker_task()
  4277. self.should_we_save = True
  4278. def on_move2origin(self, use_thread=True):
  4279. """
  4280. Move selected objects to origin.
  4281. :param use_thread: Control if to use threaded operation. Boolean.
  4282. :return:
  4283. """
  4284. def worker_task():
  4285. with self.proc_container.new(_("Moving to Origin...")):
  4286. obj_list = self.collection.get_selected()
  4287. if not obj_list:
  4288. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4289. return
  4290. xminlist = []
  4291. yminlist = []
  4292. # first get a bounding box to fit all
  4293. for obj in obj_list:
  4294. xmin, ymin, xmax, ymax = obj.bounds()
  4295. xminlist.append(xmin)
  4296. yminlist.append(ymin)
  4297. # get the minimum x,y for all objects selected
  4298. x = min(xminlist)
  4299. y = min(yminlist)
  4300. for obj in obj_list:
  4301. obj.offset((-x, -y))
  4302. self.object_changed.emit(obj)
  4303. # Update the object bounding box options
  4304. a, b, c, d = obj.bounds()
  4305. obj.options['xmin'] = a
  4306. obj.options['ymin'] = b
  4307. obj.options['xmax'] = c
  4308. obj.options['ymax'] = d
  4309. for obj in obj_list:
  4310. obj.plot()
  4311. for obj in obj_list:
  4312. out_name = obj.options["name"]
  4313. if obj.kind == 'gerber':
  4314. obj.source_file = self.export_gerber(
  4315. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4316. elif obj.kind == 'excellon':
  4317. obj.source_file = self.export_excellon(
  4318. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4319. self.inform.emit('[success] %s...' % _('Origin set'))
  4320. if use_thread is True:
  4321. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4322. else:
  4323. worker_task()
  4324. self.should_we_save = True
  4325. def on_jump_to(self, custom_location=None, fit_center=True):
  4326. """
  4327. Jump to a location by setting the mouse cursor location.
  4328. :param custom_location: Jump to a specified point. (x, y) tuple.
  4329. :param fit_center: If to fit view. Boolean.
  4330. :return:
  4331. """
  4332. self.defaults.report_usage("on_jump_to()")
  4333. if not custom_location:
  4334. dia_box_location = None
  4335. try:
  4336. dia_box_location = eval(self.clipboard.text())
  4337. except Exception:
  4338. pass
  4339. if type(dia_box_location) == tuple:
  4340. dia_box_location = str(dia_box_location)
  4341. else:
  4342. dia_box_location = None
  4343. # dia_box = Dialog_box(title=_("Jump to ..."),
  4344. # label=_("Enter the coordinates in format X,Y:"),
  4345. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4346. # initial_text=dia_box_location)
  4347. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4348. label=_("Enter the coordinates in format X,Y:"),
  4349. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4350. initial_text=dia_box_location,
  4351. reference=self.defaults['global_jump_ref'])
  4352. if dia_box.ok is True:
  4353. try:
  4354. location = eval(dia_box.location)
  4355. if not isinstance(location, tuple):
  4356. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4357. return
  4358. if dia_box.reference == 'rel':
  4359. rel_x = self.mouse[0] + location[0]
  4360. rel_y = self.mouse[1] + location[1]
  4361. location = (rel_x, rel_y)
  4362. self.defaults['global_jump_ref'] = dia_box.reference
  4363. except Exception:
  4364. return
  4365. else:
  4366. return
  4367. else:
  4368. location = custom_location
  4369. self.jump_signal.emit(location)
  4370. if fit_center:
  4371. self.plotcanvas.fit_center(loc=location)
  4372. cursor = QtGui.QCursor()
  4373. if self.is_legacy is False:
  4374. # I don't know where those differences come from but they are constant for the current
  4375. # execution of the application and they are multiples of a value around 0.0263mm.
  4376. # In a random way sometimes they are more sometimes they are less
  4377. # if units == 'MM':
  4378. # cal_factor = 0.0263
  4379. # else:
  4380. # cal_factor = 0.0263 / 25.4
  4381. cal_location = (location[0], location[1])
  4382. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4383. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4384. j_pos = (
  4385. int(canvas_origin.x() + round(jump_loc[0])),
  4386. int(canvas_origin.y() + round(jump_loc[1]))
  4387. )
  4388. cursor.setPos(j_pos[0], j_pos[1])
  4389. else:
  4390. # find the canvas origin which is in the top left corner
  4391. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4392. # determine the coordinates for the lowest left point of the canvas
  4393. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4394. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4395. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4396. # canvas) and the point (width, height) is in the top-right location
  4397. loc = self.plotcanvas.axes.transData.transform_point(location)
  4398. j_pos = (
  4399. int(x0 + loc[0]),
  4400. int(y0 - loc[1])
  4401. )
  4402. cursor.setPos(j_pos[0], j_pos[1])
  4403. self.plotcanvas.mouse = [location[0], location[1]]
  4404. if self.defaults["global_cursor_color_enabled"] is True:
  4405. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4406. else:
  4407. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4408. if self.grid_status():
  4409. # Update cursor
  4410. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4411. symbol='++', edge_color=self.cursor_color_3D,
  4412. edge_width=self.defaults["global_cursor_width"],
  4413. size=self.defaults["global_cursor_size"])
  4414. # Set the position label
  4415. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4416. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4417. # Set the relative position label
  4418. dx = location[0] - float(self.rel_point1[0])
  4419. dy = location[1] - float(self.rel_point1[1])
  4420. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4421. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4422. self.inform.emit('[success] %s' % _("Done."))
  4423. return location
  4424. def on_locate(self, obj, fit_center=True):
  4425. """
  4426. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4427. :param obj: The object on which to locate certain points
  4428. :param fit_center: If to fit view. Boolean.
  4429. :return: A point location. (x, y) tuple.
  4430. """
  4431. self.defaults.report_usage("on_locate()")
  4432. if obj is None:
  4433. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4434. return 'fail'
  4435. class DialogBoxChoice(QtWidgets.QDialog):
  4436. def __init__(self, title=None, icon=None, choice='bl'):
  4437. """
  4438. :param title: string with the window title
  4439. """
  4440. super(DialogBoxChoice, self).__init__()
  4441. self.ok = False
  4442. self.setWindowIcon(icon)
  4443. self.setWindowTitle(str(title))
  4444. self.form = QtWidgets.QFormLayout(self)
  4445. self.ref_radio = RadioSet([
  4446. {"label": _("Bottom-Left"), "value": "bl"},
  4447. {"label": _("Top-Left"), "value": "tl"},
  4448. {"label": _("Bottom-Right"), "value": "br"},
  4449. {"label": _("Top-Right"), "value": "tr"},
  4450. {"label": _("Center"), "value": "c"}
  4451. ], orientation='vertical', stretch=False)
  4452. self.ref_radio.set_value(choice)
  4453. self.form.addRow(self.ref_radio)
  4454. self.button_box = QtWidgets.QDialogButtonBox(
  4455. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4456. Qt.Horizontal, parent=self)
  4457. self.form.addRow(self.button_box)
  4458. self.button_box.accepted.connect(self.accept)
  4459. self.button_box.rejected.connect(self.reject)
  4460. if self.exec_() == QtWidgets.QDialog.Accepted:
  4461. self.ok = True
  4462. self.location_point = self.ref_radio.get_value()
  4463. else:
  4464. self.ok = False
  4465. self.location_point = None
  4466. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4467. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4468. choice=self.defaults['global_locate_pt'])
  4469. if dia_box.ok is True:
  4470. try:
  4471. location_point = dia_box.location_point
  4472. self.defaults['global_locate_pt'] = dia_box.location_point
  4473. except Exception:
  4474. return
  4475. else:
  4476. return
  4477. loc_b = obj.bounds()
  4478. if location_point == 'bl':
  4479. location = (loc_b[0], loc_b[1])
  4480. elif location_point == 'tl':
  4481. location = (loc_b[0], loc_b[3])
  4482. elif location_point == 'br':
  4483. location = (loc_b[2], loc_b[1])
  4484. elif location_point == 'tr':
  4485. location = (loc_b[2], loc_b[3])
  4486. else:
  4487. # center
  4488. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4489. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4490. location = (cx, cy)
  4491. self.locate_signal.emit(location, location_point)
  4492. if fit_center:
  4493. self.plotcanvas.fit_center(loc=location)
  4494. cursor = QtGui.QCursor()
  4495. if self.is_legacy is False:
  4496. # I don't know where those differences come from but they are constant for the current
  4497. # execution of the application and they are multiples of a value around 0.0263mm.
  4498. # In a random way sometimes they are more sometimes they are less
  4499. # if units == 'MM':
  4500. # cal_factor = 0.0263
  4501. # else:
  4502. # cal_factor = 0.0263 / 25.4
  4503. cal_location = (location[0], location[1])
  4504. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4505. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4506. j_pos = (
  4507. int(canvas_origin.x() + round(jump_loc[0])),
  4508. int(canvas_origin.y() + round(jump_loc[1]))
  4509. )
  4510. cursor.setPos(j_pos[0], j_pos[1])
  4511. else:
  4512. # find the canvas origin which is in the top left corner
  4513. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4514. # determine the coordinates for the lowest left point of the canvas
  4515. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4516. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4517. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4518. # canvas) and the point (width, height) is in the top-right location
  4519. loc = self.plotcanvas.axes.transData.transform_point(location)
  4520. j_pos = (
  4521. int(x0 + loc[0]),
  4522. int(y0 - loc[1])
  4523. )
  4524. cursor.setPos(j_pos[0], j_pos[1])
  4525. self.plotcanvas.mouse = [location[0], location[1]]
  4526. if self.defaults["global_cursor_color_enabled"] is True:
  4527. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4528. else:
  4529. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4530. if self.grid_status():
  4531. # Update cursor
  4532. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4533. symbol='++', edge_color=self.cursor_color_3D,
  4534. edge_width=self.defaults["global_cursor_width"],
  4535. size=self.defaults["global_cursor_size"])
  4536. # Set the position label
  4537. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4538. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4539. # Set the relative position label
  4540. self.dx = location[0] - float(self.rel_point1[0])
  4541. self.dy = location[1] - float(self.rel_point1[1])
  4542. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4543. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4544. self.inform.emit('[success] %s' % _("Done."))
  4545. return location
  4546. def on_copy_command(self):
  4547. """
  4548. Will copy a selection of objects, creating new objects.
  4549. :return:
  4550. """
  4551. self.defaults.report_usage("on_copy_command()")
  4552. def initialize(obj_init, app):
  4553. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4554. try:
  4555. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4556. except AttributeError:
  4557. pass
  4558. try:
  4559. obj_init.apertures = deepcopy(obj.apertures)
  4560. except AttributeError:
  4561. pass
  4562. try:
  4563. if obj.tools:
  4564. obj_init.tools = deepcopy(obj.tools)
  4565. except Exception as err:
  4566. log.debug("App.on_copy_command() --> %s" % str(err))
  4567. try:
  4568. obj_init.source_file = deepcopy(obj.source_file)
  4569. except (AttributeError, TypeError):
  4570. pass
  4571. def initialize_excellon(obj_init, app):
  4572. obj_init.source_file = deepcopy(obj.source_file)
  4573. obj_init.tools = deepcopy(obj.tools)
  4574. # drills are offset, so they need to be deep copied
  4575. obj_init.drills = deepcopy(obj.drills)
  4576. # slots are offset, so they need to be deep copied
  4577. obj_init.slots = deepcopy(obj.slots)
  4578. obj_init.create_geometry()
  4579. def initialize_script(obj_init, app_obj):
  4580. obj_init.source_file = deepcopy(obj.source_file)
  4581. def initialize_document(obj_init, app_obj):
  4582. obj_init.source_file = deepcopy(obj.source_file)
  4583. for obj in self.collection.get_selected():
  4584. obj_name = obj.options["name"]
  4585. try:
  4586. if isinstance(obj, ExcellonObject):
  4587. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4588. elif isinstance(obj, GerberObject):
  4589. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4590. elif isinstance(obj, GeometryObject):
  4591. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4592. elif isinstance(obj, ScriptObject):
  4593. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4594. elif isinstance(obj, DocumentObject):
  4595. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4596. except Exception as e:
  4597. return "Operation failed: %s" % str(e)
  4598. def on_copy_object2(self, custom_name):
  4599. def initialize_geometry(obj_init, app):
  4600. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4601. try:
  4602. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4603. except AttributeError:
  4604. pass
  4605. try:
  4606. obj_init.apertures = deepcopy(obj.apertures)
  4607. except AttributeError:
  4608. pass
  4609. try:
  4610. if obj.tools:
  4611. obj_init.tools = deepcopy(obj.tools)
  4612. except Exception as ee:
  4613. log.debug("on_copy_object2() --> %s" % str(ee))
  4614. def initialize_gerber(obj_init, app):
  4615. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4616. obj_init.apertures = deepcopy(obj.apertures)
  4617. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4618. def initialize_excellon(obj_init, app):
  4619. obj_init.tools = deepcopy(obj.tools)
  4620. # drills are offset, so they need to be deep copied
  4621. obj_init.drills = deepcopy(obj.drills)
  4622. # slots are offset, so they need to be deep copied
  4623. obj_init.slots = deepcopy(obj.slots)
  4624. obj_init.create_geometry()
  4625. for obj in self.collection.get_selected():
  4626. obj_name = obj.options["name"]
  4627. try:
  4628. if isinstance(obj, ExcellonObject):
  4629. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4630. elif isinstance(obj, GerberObject):
  4631. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4632. elif isinstance(obj, GeometryObject):
  4633. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4634. except Exception as er:
  4635. return "Operation failed: %s" % str(er)
  4636. def on_rename_object(self, text):
  4637. """
  4638. Will rename an object.
  4639. :param text: New name for the object.
  4640. :return:
  4641. """
  4642. self.defaults.report_usage("on_rename_object()")
  4643. named_obj = self.collection.get_active()
  4644. for obj in named_obj:
  4645. if obj is list:
  4646. self.on_rename_object(text)
  4647. else:
  4648. try:
  4649. obj.options['name'] = text
  4650. except Exception as e:
  4651. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4652. def convert_any2geo(self):
  4653. """
  4654. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4655. :return:
  4656. """
  4657. self.defaults.report_usage("convert_any2geo()")
  4658. def initialize(obj_init, app):
  4659. obj_init.solid_geometry = obj.solid_geometry
  4660. try:
  4661. obj_init.follow_geometry = obj.follow_geometry
  4662. except AttributeError:
  4663. pass
  4664. try:
  4665. obj_init.apertures = obj.apertures
  4666. except AttributeError:
  4667. pass
  4668. try:
  4669. if obj.tools:
  4670. obj_init.tools = obj.tools
  4671. except AttributeError:
  4672. pass
  4673. def initialize_excellon(obj_init, app):
  4674. # objs = self.collection.get_selected()
  4675. # GeometryObject.merge(objs, obj)
  4676. solid_geo = []
  4677. for tool in obj.tools:
  4678. for geo in obj.tools[tool]['solid_geometry']:
  4679. solid_geo.append(geo)
  4680. obj_init.solid_geometry = deepcopy(solid_geo)
  4681. if not self.collection.get_selected():
  4682. log.warning("App.convert_any2geo --> No object selected")
  4683. self.inform.emit('[WARNING_NOTCL] %s' %
  4684. _("No object is selected. Select an object and try again."))
  4685. return
  4686. for obj in self.collection.get_selected():
  4687. obj_name = obj.options["name"]
  4688. try:
  4689. if isinstance(obj, ExcellonObject):
  4690. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4691. else:
  4692. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4693. except Exception as e:
  4694. return "Operation failed: %s" % str(e)
  4695. def convert_any2gerber(self):
  4696. """
  4697. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4698. :return:
  4699. """
  4700. self.defaults.report_usage("convert_any2gerber()")
  4701. def initialize_geometry(obj_init, app):
  4702. apertures = {}
  4703. apid = 0
  4704. apertures[str(apid)] = {}
  4705. apertures[str(apid)]['geometry'] = []
  4706. for obj_orig in obj.solid_geometry:
  4707. new_elem = {}
  4708. new_elem['solid'] = obj_orig
  4709. try:
  4710. new_elem['follow'] = obj_orig.exterior
  4711. except AttributeError:
  4712. pass
  4713. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4714. apertures[str(apid)]['size'] = 0.0
  4715. apertures[str(apid)]['type'] = 'C'
  4716. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4717. obj_init.apertures = deepcopy(apertures)
  4718. def initialize_excellon(obj_init, app):
  4719. apertures = {}
  4720. apid = 10
  4721. for tool in obj.tools:
  4722. apertures[str(apid)] = {}
  4723. apertures[str(apid)]['geometry'] = []
  4724. for geo in obj.tools[tool]['solid_geometry']:
  4725. new_el = {}
  4726. new_el['solid'] = geo
  4727. new_el['follow'] = geo.exterior
  4728. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4729. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4730. apertures[str(apid)]['type'] = 'C'
  4731. apid += 1
  4732. # create solid_geometry
  4733. solid_geometry = []
  4734. for apid in apertures:
  4735. for geo_el in apertures[apid]['geometry']:
  4736. solid_geometry.append(geo_el['solid'])
  4737. solid_geometry = MultiPolygon(solid_geometry)
  4738. solid_geometry = solid_geometry.buffer(0.0000001)
  4739. obj_init.solid_geometry = deepcopy(solid_geometry)
  4740. obj_init.apertures = deepcopy(apertures)
  4741. # clear the working objects (perhaps not necessary due of Python GC)
  4742. apertures.clear()
  4743. if not self.collection.get_selected():
  4744. log.warning("App.convert_any2gerber --> No object selected")
  4745. self.inform.emit('[WARNING_NOTCL] %s' %
  4746. _("No object is selected. Select an object and try again."))
  4747. return
  4748. for obj in self.collection.get_selected():
  4749. obj_name = obj.options["name"]
  4750. try:
  4751. if isinstance(obj, ExcellonObject):
  4752. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4753. elif isinstance(obj, GeometryObject):
  4754. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4755. else:
  4756. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4757. except Exception as e:
  4758. return "Operation failed: %s" % str(e)
  4759. def abort_all_tasks(self):
  4760. """
  4761. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4762. on the first possible occasion.
  4763. :return:
  4764. """
  4765. if self.abort_flag is False:
  4766. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4767. self.abort_flag = True
  4768. self.cleanup.emit()
  4769. def app_is_idle(self):
  4770. if self.abort_flag:
  4771. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4772. self.abort_flag = False
  4773. def on_selectall(self):
  4774. """
  4775. Will draw a selection box shape around the selected objects.
  4776. :return:
  4777. """
  4778. self.defaults.report_usage("on_selectall()")
  4779. # delete the possible selection box around a possible selected object
  4780. self.delete_selection_shape()
  4781. for name in self.collection.get_names():
  4782. self.collection.set_active(name)
  4783. curr_sel_obj = self.collection.get_by_name(name)
  4784. # create the selection box around the selected object
  4785. if self.defaults['global_selection_shape'] is True:
  4786. self.draw_selection_shape(curr_sel_obj)
  4787. def on_preferences(self):
  4788. """
  4789. Adds the Preferences in a Tab in Plot Area
  4790. :return:
  4791. """
  4792. # add the tab if it was closed
  4793. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4794. # delete the absolute and relative position and messages in the infobar
  4795. self.ui.position_label.setText("")
  4796. self.ui.rel_position_label.setText("")
  4797. # Switch plot_area to preferences page
  4798. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4799. # self.ui.show()
  4800. # detect changes in the preferences
  4801. for idx in range(self.ui.pref_tab_area.count()):
  4802. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4803. try:
  4804. try:
  4805. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4806. except (TypeError, AttributeError):
  4807. pass
  4808. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4809. except AttributeError:
  4810. pass
  4811. try:
  4812. try:
  4813. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4814. except (TypeError, AttributeError):
  4815. pass
  4816. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4817. except AttributeError:
  4818. pass
  4819. try:
  4820. try:
  4821. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4822. except (TypeError, AttributeError):
  4823. pass
  4824. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4825. except AttributeError:
  4826. pass
  4827. try:
  4828. try:
  4829. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4830. except (TypeError, AttributeError):
  4831. pass
  4832. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4833. except AttributeError:
  4834. pass
  4835. try:
  4836. try:
  4837. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4838. except (TypeError, AttributeError):
  4839. pass
  4840. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4841. except AttributeError:
  4842. pass
  4843. def on_tools_database(self, source='app'):
  4844. """
  4845. Adds the Tools Database in a Tab in Plot Area.
  4846. :return:
  4847. """
  4848. for idx in range(self.ui.plot_tab_area.count()):
  4849. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4850. # there can be only one instance of Tools Database at one time
  4851. return
  4852. if source == 'app':
  4853. self.tools_db_tab = ToolsDB2(
  4854. app=self,
  4855. parent=self.ui,
  4856. callback_on_edited=self.on_tools_db_edited,
  4857. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4858. )
  4859. elif source == 'ncc':
  4860. self.tools_db_tab = ToolsDB2(
  4861. app=self,
  4862. parent=self.ui,
  4863. callback_on_edited=self.on_tools_db_edited,
  4864. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4865. )
  4866. elif source == 'paint':
  4867. self.tools_db_tab = ToolsDB2(
  4868. app=self,
  4869. parent=self.ui,
  4870. callback_on_edited=self.on_tools_db_edited,
  4871. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4872. )
  4873. # add the tab if it was closed
  4874. try:
  4875. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4876. self.tools_db_tab.setObjectName("database_tab")
  4877. except Exception as e:
  4878. log.debug("App.on_tools_database() --> %s" % str(e))
  4879. return
  4880. # delete the absolute and relative position and messages in the infobar
  4881. self.ui.position_label.setText("")
  4882. self.ui.rel_position_label.setText("")
  4883. # Switch plot_area to preferences page
  4884. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4885. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4886. self.tools_db_tab.ui_connect()
  4887. def on_tools_db_edited(self):
  4888. """
  4889. Executed whenever a tool is edited in Tools Database.
  4890. Will color the text of the Tools Database tab to Red color.
  4891. :return:
  4892. """
  4893. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4894. for idx in range(self.ui.plot_tab_area.count()):
  4895. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4896. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4897. self.tools_db_changed_flag = True
  4898. def on_geometry_tool_add_from_db_executed(self, tool):
  4899. """
  4900. Here add the tool from DB in the selected geometry object.
  4901. :return:
  4902. """
  4903. tool_from_db = deepcopy(tool)
  4904. obj = self.collection.get_active()
  4905. if isinstance(obj, GeometryObject):
  4906. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4907. # close the tab and delete it
  4908. for idx in range(self.ui.plot_tab_area.count()):
  4909. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4910. wdg = self.ui.plot_tab_area.widget(idx)
  4911. wdg.deleteLater()
  4912. self.ui.plot_tab_area.removeTab(idx)
  4913. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4914. else:
  4915. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4916. def on_plot_area_tab_closed(self, title):
  4917. """
  4918. Executed whenever a tab is closed in the Plot Area.
  4919. :param title: The name of the tab that was closed.
  4920. :return:
  4921. """
  4922. # FIXME: doing this based on translated title doesn't seem very robust.
  4923. if title == _("Preferences"):
  4924. self.uiPreferencesManager.on_close_preferences_tab()
  4925. if title == _("Tools Database"):
  4926. # disconnect the signals from the table widget in tab
  4927. self.tools_db_tab.ui_disconnect()
  4928. if self.tools_db_changed_flag is True:
  4929. msgbox = QtWidgets.QMessageBox()
  4930. msgbox.setText(_("One or more Tools are edited.\n"
  4931. "Do you want to update the Tools Database?"))
  4932. msgbox.setWindowTitle(_("Save Tools Database"))
  4933. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4934. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4935. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4936. msgbox.setDefaultButton(bt_yes)
  4937. msgbox.exec_()
  4938. response = msgbox.clickedButton()
  4939. if response == bt_yes:
  4940. self.tools_db_tab.on_save_tools_db()
  4941. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4942. else:
  4943. self.tools_db_changed_flag = False
  4944. self.inform.emit('')
  4945. return
  4946. self.tools_db_tab.deleteLater()
  4947. if title == _("Code Editor"):
  4948. self.toggle_codeeditor = False
  4949. if title == _("Bookmarks Manager"):
  4950. self.book_dialog_tab.rebuild_actions()
  4951. self.book_dialog_tab.deleteLater()
  4952. def on_flipy(self):
  4953. """
  4954. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4955. :return:
  4956. """
  4957. self.defaults.report_usage("on_flipy()")
  4958. obj_list = self.collection.get_selected()
  4959. xminlist = []
  4960. yminlist = []
  4961. xmaxlist = []
  4962. ymaxlist = []
  4963. if not obj_list:
  4964. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4965. else:
  4966. try:
  4967. # first get a bounding box to fit all
  4968. for obj in obj_list:
  4969. xmin, ymin, xmax, ymax = obj.bounds()
  4970. xminlist.append(xmin)
  4971. yminlist.append(ymin)
  4972. xmaxlist.append(xmax)
  4973. ymaxlist.append(ymax)
  4974. # get the minimum x,y and maximum x,y for all objects selected
  4975. xminimal = min(xminlist)
  4976. yminimal = min(yminlist)
  4977. xmaximal = max(xmaxlist)
  4978. ymaximal = max(ymaxlist)
  4979. px = 0.5 * (xminimal + xmaximal)
  4980. py = 0.5 * (yminimal + ymaximal)
  4981. # execute mirroring
  4982. for obj in obj_list:
  4983. obj.mirror('X', [px, py])
  4984. obj.plot()
  4985. self.object_changed.emit(obj)
  4986. self.inform.emit('[success] %s' %
  4987. _("Flip on Y axis done."))
  4988. except Exception as e:
  4989. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4990. return
  4991. def on_flipx(self):
  4992. """
  4993. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4994. :return:
  4995. """
  4996. self.defaults.report_usage("on_flipx()")
  4997. obj_list = self.collection.get_selected()
  4998. xminlist = []
  4999. yminlist = []
  5000. xmaxlist = []
  5001. ymaxlist = []
  5002. if not obj_list:
  5003. self.inform.emit('[WARNING_NOTCL] %s' %
  5004. _("No object selected to Flip on X axis."))
  5005. else:
  5006. try:
  5007. # first get a bounding box to fit all
  5008. for obj in obj_list:
  5009. xmin, ymin, xmax, ymax = obj.bounds()
  5010. xminlist.append(xmin)
  5011. yminlist.append(ymin)
  5012. xmaxlist.append(xmax)
  5013. ymaxlist.append(ymax)
  5014. # get the minimum x,y and maximum x,y for all objects selected
  5015. xminimal = min(xminlist)
  5016. yminimal = min(yminlist)
  5017. xmaximal = max(xmaxlist)
  5018. ymaximal = max(ymaxlist)
  5019. px = 0.5 * (xminimal + xmaximal)
  5020. py = 0.5 * (yminimal + ymaximal)
  5021. # execute mirroring
  5022. for obj in obj_list:
  5023. obj.mirror('Y', [px, py])
  5024. obj.plot()
  5025. self.object_changed.emit(obj)
  5026. self.inform.emit('[success] %s' %
  5027. _("Flip on X axis done."))
  5028. except Exception as e:
  5029. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5030. return
  5031. def on_rotate(self, silent=False, preset=None):
  5032. """
  5033. Executed when Options -> Rotate Selection menu entry is clicked.
  5034. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5035. :param preset: A value to be used as predefined angle for rotation.
  5036. :return:
  5037. """
  5038. self.defaults.report_usage("on_rotate()")
  5039. obj_list = self.collection.get_selected()
  5040. xminlist = []
  5041. yminlist = []
  5042. xmaxlist = []
  5043. ymaxlist = []
  5044. if not obj_list:
  5045. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5046. else:
  5047. if silent is False:
  5048. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5049. min=-360, max=360, decimals=4,
  5050. init_val=float(self.defaults['tools_transform_rotate']))
  5051. num, ok = rotatebox.get_value()
  5052. else:
  5053. num = preset
  5054. ok = True
  5055. if ok:
  5056. try:
  5057. # first get a bounding box to fit all
  5058. for obj in obj_list:
  5059. xmin, ymin, xmax, ymax = obj.bounds()
  5060. xminlist.append(xmin)
  5061. yminlist.append(ymin)
  5062. xmaxlist.append(xmax)
  5063. ymaxlist.append(ymax)
  5064. # get the minimum x,y and maximum x,y for all objects selected
  5065. xminimal = min(xminlist)
  5066. yminimal = min(yminlist)
  5067. xmaximal = max(xmaxlist)
  5068. ymaximal = max(ymaxlist)
  5069. px = 0.5 * (xminimal + xmaximal)
  5070. py = 0.5 * (yminimal + ymaximal)
  5071. for sel_obj in obj_list:
  5072. sel_obj.rotate(-float(num), point=(px, py))
  5073. sel_obj.plot()
  5074. self.object_changed.emit(sel_obj)
  5075. self.inform.emit('[success] %s' %
  5076. _("Rotation done."))
  5077. except Exception as e:
  5078. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5079. return
  5080. def on_skewx(self):
  5081. """
  5082. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5083. :return:
  5084. """
  5085. self.defaults.report_usage("on_skewx()")
  5086. obj_list = self.collection.get_selected()
  5087. xminlist = []
  5088. yminlist = []
  5089. if not obj_list:
  5090. self.inform.emit('[WARNING_NOTCL] %s' %
  5091. _("No object selected to Skew/Shear on X axis."))
  5092. else:
  5093. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5094. min=-360, max=360, decimals=4,
  5095. init_val=float(self.defaults['tools_transform_skew_x']))
  5096. num, ok = skewxbox.get_value()
  5097. if ok:
  5098. # first get a bounding box to fit all
  5099. for obj in obj_list:
  5100. xmin, ymin, xmax, ymax = obj.bounds()
  5101. xminlist.append(xmin)
  5102. yminlist.append(ymin)
  5103. # get the minimum x,y and maximum x,y for all objects selected
  5104. xminimal = min(xminlist)
  5105. yminimal = min(yminlist)
  5106. for obj in obj_list:
  5107. obj.skew(num, 0, point=(xminimal, yminimal))
  5108. obj.plot()
  5109. self.object_changed.emit(obj)
  5110. self.inform.emit('[success] %s' %
  5111. _("Skew on X axis done."))
  5112. def on_skewy(self):
  5113. """
  5114. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5115. :return:
  5116. """
  5117. self.defaults.report_usage("on_skewy()")
  5118. obj_list = self.collection.get_selected()
  5119. xminlist = []
  5120. yminlist = []
  5121. if not obj_list:
  5122. self.inform.emit('[WARNING_NOTCL] %s' %
  5123. _("No object selected to Skew/Shear on Y axis."))
  5124. else:
  5125. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5126. min=-360, max=360, decimals=4,
  5127. init_val=float(self.defaults['tools_transform_skew_y']))
  5128. num, ok = skewybox.get_value()
  5129. if ok:
  5130. # first get a bounding box to fit all
  5131. for obj in obj_list:
  5132. xmin, ymin, xmax, ymax = obj.bounds()
  5133. xminlist.append(xmin)
  5134. yminlist.append(ymin)
  5135. # get the minimum x,y and maximum x,y for all objects selected
  5136. xminimal = min(xminlist)
  5137. yminimal = min(yminlist)
  5138. for obj in obj_list:
  5139. obj.skew(0, num, point=(xminimal, yminimal))
  5140. obj.plot()
  5141. self.object_changed.emit(obj)
  5142. self.inform.emit('[success] %s' %
  5143. _("Skew on Y axis done."))
  5144. def on_plots_updated(self):
  5145. """
  5146. Callback used to report when the plots have changed.
  5147. Adjust axes and zooms to fit.
  5148. :return: None
  5149. """
  5150. if self.is_legacy is False:
  5151. self.plotcanvas.update()
  5152. else:
  5153. self.plotcanvas.auto_adjust_axes()
  5154. self.on_zoom_fit(None)
  5155. self.collection.update_view()
  5156. # self.inform.emit(_("Plots updated ..."))
  5157. def on_toolbar_replot(self):
  5158. """
  5159. Callback for toolbar button. Re-plots all objects.
  5160. :return: None
  5161. """
  5162. self.defaults.report_usage("on_toolbar_replot")
  5163. self.log.debug("on_toolbar_replot()")
  5164. try:
  5165. self.collection.get_active().read_form()
  5166. except AttributeError:
  5167. self.log.debug("on_toolbar_replot(): AttributeError")
  5168. pass
  5169. self.plot_all()
  5170. def on_row_activated(self, index):
  5171. if index.isValid():
  5172. if index.internalPointer().parent_item != self.collection.root_item:
  5173. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5174. self.collection.on_item_activated(index)
  5175. def on_row_selected(self, obj_name):
  5176. """
  5177. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5178. It mean we clicked outside of the items and deselected all
  5179. :param obj_name:
  5180. :return:
  5181. """
  5182. if obj_name == 'none':
  5183. for act in self.ui.menuobjects.actions():
  5184. act.setChecked(False)
  5185. return
  5186. # get the name of the selected objects and add them to a list
  5187. name_list = []
  5188. for obj in self.collection.get_selected():
  5189. name_list.append(obj.options['name'])
  5190. # set all actions as unchecked but the ones selected make them checked
  5191. for act in self.ui.menuobjects.actions():
  5192. act.setChecked(False)
  5193. if act.text() in name_list:
  5194. act.setChecked(True)
  5195. def on_collection_updated(self, obj, state, old_name):
  5196. """
  5197. Create a menu from the object loaded in the collection.
  5198. :param obj: object that was changed (added, deleted, renamed)
  5199. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5200. :param old_name: the old name of the object before the action that triggered this slot happened
  5201. :return: None
  5202. """
  5203. icon_files = {
  5204. "gerber": self.resource_location + "/flatcam_icon16.png",
  5205. "excellon": self.resource_location + "/drill16.png",
  5206. "cncjob": self.resource_location + "/cnc16.png",
  5207. "geometry": self.resource_location + "/geometry16.png",
  5208. "script": self.resource_location + "/script_new16.png",
  5209. "document": self.resource_location + "/notes16_1.png"
  5210. }
  5211. if state == 'append':
  5212. for act in self.ui.menuobjects.actions():
  5213. try:
  5214. act.triggered.disconnect()
  5215. except TypeError:
  5216. pass
  5217. self.ui.menuobjects.clear()
  5218. gerber_list = []
  5219. exc_list = []
  5220. cncjob_list = []
  5221. geo_list = []
  5222. script_list = []
  5223. doc_list = []
  5224. for name in self.collection.get_names():
  5225. obj_named = self.collection.get_by_name(name)
  5226. if obj_named.kind == 'gerber':
  5227. gerber_list.append(name)
  5228. elif obj_named.kind == 'excellon':
  5229. exc_list.append(name)
  5230. elif obj_named.kind == 'cncjob':
  5231. cncjob_list.append(name)
  5232. elif obj_named.kind == 'geometry':
  5233. geo_list.append(name)
  5234. elif obj_named.kind == 'script':
  5235. script_list.append(name)
  5236. elif obj_named.kind == 'document':
  5237. doc_list.append(name)
  5238. def add_act(o_name):
  5239. obj_for_icon = self.collection.get_by_name(o_name)
  5240. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5241. add_action.setCheckable(True)
  5242. add_action.setText(o_name)
  5243. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5244. add_action.triggered.connect(
  5245. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5246. self.collection.set_inactive(o_name))
  5247. self.ui.menuobjects.addAction(add_action)
  5248. for name in gerber_list:
  5249. add_act(name)
  5250. self.ui.menuobjects.addSeparator()
  5251. for name in exc_list:
  5252. add_act(name)
  5253. self.ui.menuobjects.addSeparator()
  5254. for name in cncjob_list:
  5255. add_act(name)
  5256. self.ui.menuobjects.addSeparator()
  5257. for name in geo_list:
  5258. add_act(name)
  5259. self.ui.menuobjects.addSeparator()
  5260. for name in script_list:
  5261. add_act(name)
  5262. self.ui.menuobjects.addSeparator()
  5263. for name in doc_list:
  5264. add_act(name)
  5265. self.ui.menuobjects.addSeparator()
  5266. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5267. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5268. _('Select All')
  5269. )
  5270. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5271. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5272. _('Deselect All')
  5273. )
  5274. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5275. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5276. elif state == 'delete':
  5277. for act in self.ui.menuobjects.actions():
  5278. if act.text() == obj.options['name']:
  5279. try:
  5280. act.triggered.disconnect()
  5281. except TypeError:
  5282. pass
  5283. self.ui.menuobjects.removeAction(act)
  5284. break
  5285. elif state == 'rename':
  5286. for act in self.ui.menuobjects.actions():
  5287. if act.text() == old_name:
  5288. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5289. add_action.setText(obj.options['name'])
  5290. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5291. add_action.triggered.connect(
  5292. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5293. self.collection.set_inactive(obj.options['name']))
  5294. self.ui.menuobjects.insertAction(act, add_action)
  5295. try:
  5296. act.triggered.disconnect()
  5297. except TypeError:
  5298. pass
  5299. self.ui.menuobjects.removeAction(act)
  5300. break
  5301. elif state == 'delete_all':
  5302. for act in self.ui.menuobjects.actions():
  5303. try:
  5304. act.triggered.disconnect()
  5305. except TypeError:
  5306. pass
  5307. self.ui.menuobjects.clear()
  5308. self.ui.menuobjects.addSeparator()
  5309. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5310. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5311. _('Select All')
  5312. )
  5313. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5314. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5315. _('Deselect All')
  5316. )
  5317. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5318. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5319. def on_objects_selection(self, on_off):
  5320. obj_list = self.collection.get_names()
  5321. if on_off is True:
  5322. self.collection.set_all_active()
  5323. for act in self.ui.menuobjects.actions():
  5324. try:
  5325. act.setChecked(True)
  5326. except Exception:
  5327. pass
  5328. if obj_list:
  5329. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5330. else:
  5331. self.collection.set_all_inactive()
  5332. for act in self.ui.menuobjects.actions():
  5333. try:
  5334. act.setChecked(False)
  5335. except Exception:
  5336. pass
  5337. if obj_list:
  5338. self.inform.emit('%s' % _("Objects selection is cleared."))
  5339. else:
  5340. self.inform.emit('')
  5341. def grid_status(self):
  5342. if self.ui.grid_snap_btn.isChecked():
  5343. return True
  5344. else:
  5345. return False
  5346. def populate_cmenu_grids(self):
  5347. units = self.defaults['units'].lower()
  5348. # for act in self.ui.cmenu_gridmenu.actions():
  5349. # act.triggered.disconnect()
  5350. self.ui.cmenu_gridmenu.clear()
  5351. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5352. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5353. _("Grid On/Off"))
  5354. grid_toggle.setCheckable(True)
  5355. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5356. self.ui.cmenu_gridmenu.addSeparator()
  5357. for grid in sorted_list:
  5358. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5359. "%s" % str(grid))
  5360. action.triggered.connect(self.set_grid)
  5361. self.ui.cmenu_gridmenu.addSeparator()
  5362. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5363. _("Add"))
  5364. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5365. _("Delete"))
  5366. grid_add.triggered.connect(self.on_grid_add)
  5367. grid_delete.triggered.connect(self.on_grid_delete)
  5368. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5369. def set_grid(self):
  5370. menu_action = self.sender()
  5371. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5372. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5373. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5374. def on_grid_add(self):
  5375. # ## Current application units in lower Case
  5376. units = self.defaults['units'].lower()
  5377. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5378. text=_('Enter a Grid Value:'),
  5379. min=0.0000, max=99.9999, decimals=4)
  5380. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5381. val, ok = grid_add_popup.get_value()
  5382. if ok:
  5383. if float(val) == 0:
  5384. self.inform.emit('[WARNING_NOTCL] %s' %
  5385. _("Please enter a grid value with non-zero value, in Float format."))
  5386. return
  5387. else:
  5388. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5389. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5390. self.inform.emit('[success] %s...' %
  5391. _("New Grid added"))
  5392. else:
  5393. self.inform.emit('[WARNING_NOTCL] %s...' %
  5394. _("Grid already exists"))
  5395. else:
  5396. self.inform.emit('[WARNING_NOTCL] %s...' %
  5397. _("Adding New Grid cancelled"))
  5398. def on_grid_delete(self):
  5399. # ## Current application units in lower Case
  5400. units = self.defaults['units'].lower()
  5401. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5402. text='Enter a Grid Value:',
  5403. min=0.0000, max=99.9999, decimals=4)
  5404. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5405. val, ok = grid_del_popup.get_value()
  5406. if ok:
  5407. if float(val) == 0:
  5408. self.inform.emit('[WARNING_NOTCL] %s' %
  5409. _("Please enter a grid value with non-zero value, in Float format."))
  5410. return
  5411. else:
  5412. try:
  5413. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5414. except ValueError:
  5415. self.inform.emit('[ERROR_NOTCL]%s...' %
  5416. _(" Grid Value does not exist"))
  5417. return
  5418. self.inform.emit('[success] %s...' %
  5419. _("Grid Value deleted"))
  5420. else:
  5421. self.inform.emit('[WARNING_NOTCL] %s...' %
  5422. _("Delete Grid value cancelled"))
  5423. def on_shortcut_list(self):
  5424. self.defaults.report_usage("on_shortcut_list()")
  5425. # add the tab if it was closed
  5426. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5427. # delete the absolute and relative position and messages in the infobar
  5428. self.ui.position_label.setText("")
  5429. self.ui.rel_position_label.setText("")
  5430. # Switch plot_area to preferences page
  5431. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5432. # self.ui.show()
  5433. def on_select_tab(self, name):
  5434. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5435. if self.ui.splitter.sizes()[0] == 0:
  5436. self.ui.splitter.setSizes([1, 1])
  5437. else:
  5438. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5439. self.ui.splitter.setSizes([0, 1])
  5440. if name == 'project':
  5441. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5442. elif name == 'selected':
  5443. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5444. elif name == 'tool':
  5445. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5446. def on_copy_name(self):
  5447. self.defaults.report_usage("on_copy_name()")
  5448. obj = self.collection.get_active()
  5449. try:
  5450. name = obj.options["name"]
  5451. except AttributeError:
  5452. log.debug("on_copy_name() --> No object selected to copy it's name")
  5453. self.inform.emit('[WARNING_NOTCL]%s' %
  5454. _(" No object selected to copy it's name"))
  5455. return
  5456. self.clipboard.setText(name)
  5457. self.inform.emit(_("Name copied on clipboard ..."))
  5458. def on_mouse_click_over_plot(self, event):
  5459. """
  5460. Default actions are:
  5461. :param event: Contains information about the event, like which button
  5462. was clicked, the pixel coordinates and the axes coordinates.
  5463. :return: None
  5464. """
  5465. self.pos = []
  5466. if self.is_legacy is False:
  5467. event_pos = event.pos
  5468. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5469. # # Set the mouse button for panning
  5470. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5471. else:
  5472. event_pos = (event.xdata, event.ydata)
  5473. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5474. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5475. # So it can receive key presses
  5476. self.plotcanvas.native.setFocus()
  5477. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5478. if self.grid_status():
  5479. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5480. else:
  5481. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5482. try:
  5483. if event.button == 1:
  5484. # Reset here the relative coordinates so there is a new reference on the click position
  5485. if self.rel_point1 is None:
  5486. self.rel_point1 = self.pos
  5487. else:
  5488. self.rel_point2 = copy(self.rel_point1)
  5489. self.rel_point1 = self.pos
  5490. self.on_mouse_move_over_plot(event, origin_click=True)
  5491. except Exception as e:
  5492. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5493. def on_mouse_double_click_over_plot(self, event):
  5494. if event.button == 1:
  5495. self.doubleclick = True
  5496. def on_mouse_move_over_plot(self, event, origin_click=None):
  5497. """
  5498. Callback for the mouse motion event over the plot.
  5499. :param event: Contains information about the event.
  5500. :param origin_click
  5501. :return: None
  5502. """
  5503. if self.is_legacy is False:
  5504. event_pos = event.pos
  5505. if self.defaults["global_pan_button"] == '2':
  5506. pan_button = 2
  5507. else:
  5508. pan_button = 3
  5509. self.event_is_dragging = event.is_dragging
  5510. else:
  5511. event_pos = (event.xdata, event.ydata)
  5512. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5513. if self.defaults["global_pan_button"] == '2':
  5514. pan_button = 3
  5515. else:
  5516. pan_button = 2
  5517. self.event_is_dragging = self.plotcanvas.is_dragging
  5518. # So it can receive key presses but not when the Tcl Shell is active
  5519. if not self.ui.shell_dock.isVisible():
  5520. if not self.plotcanvas.native.hasFocus():
  5521. self.plotcanvas.native.setFocus()
  5522. self.pos_jump = event_pos
  5523. self.ui.popMenu.mouse_is_panning = False
  5524. if origin_click is None:
  5525. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5526. if event.button == pan_button and self.event_is_dragging == 1:
  5527. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5528. if self.ui.popMenu.popup_active:
  5529. self.ui.popMenu.popup_active = False
  5530. return
  5531. self.ui.popMenu.mouse_is_panning = True
  5532. return
  5533. if self.rel_point1 is not None:
  5534. try: # May fail in case mouse not within axes
  5535. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5536. if self.grid_status():
  5537. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5538. # Update cursor
  5539. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5540. symbol='++', edge_color=self.cursor_color_3D,
  5541. edge_width=self.defaults["global_cursor_width"],
  5542. size=self.defaults["global_cursor_size"])
  5543. else:
  5544. pos = (pos_canvas[0], pos_canvas[1])
  5545. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5546. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5547. self.dx = pos[0] - float(self.rel_point1[0])
  5548. self.dy = pos[1] - float(self.rel_point1[1])
  5549. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5550. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5551. self.mouse = [pos[0], pos[1]]
  5552. # if the mouse is moved and the LMB is clicked then the action is a selection
  5553. if self.event_is_dragging == 1 and event.button == 1:
  5554. self.delete_selection_shape()
  5555. if self.dx < 0:
  5556. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5557. face_color=self.defaults['global_alt_sel_fill'])
  5558. self.selection_type = False
  5559. elif self.dx >= 0:
  5560. self.draw_moving_selection_shape(self.pos, pos)
  5561. self.selection_type = True
  5562. else:
  5563. self.selection_type = None
  5564. else:
  5565. self.selection_type = None
  5566. # hover effect - enabled in Preferences -> General -> GUI Settings
  5567. if self.defaults['global_hover']:
  5568. for obj in self.collection.get_list():
  5569. try:
  5570. # select the object(s) only if it is enabled (plotted)
  5571. if obj.options['plot']:
  5572. if obj not in self.collection.get_selected():
  5573. poly_obj = Polygon(
  5574. [(obj.options['xmin'], obj.options['ymin']),
  5575. (obj.options['xmax'], obj.options['ymin']),
  5576. (obj.options['xmax'], obj.options['ymax']),
  5577. (obj.options['xmin'], obj.options['ymax'])]
  5578. )
  5579. if Point(pos).within(poly_obj):
  5580. if obj.isHovering is False:
  5581. obj.isHovering = True
  5582. obj.notHovering = True
  5583. # create the selection box around the selected object
  5584. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5585. else:
  5586. if obj.notHovering is True:
  5587. obj.notHovering = False
  5588. obj.isHovering = False
  5589. self.delete_hover_shape()
  5590. except Exception:
  5591. # the Exception here will happen if we try to select on screen and we have an
  5592. # newly (and empty) just created Geometry or Excellon object that do not have the
  5593. # xmin, xmax, ymin, ymax options.
  5594. # In this case poly_obj creation (see above) will fail
  5595. pass
  5596. except Exception:
  5597. self.ui.position_label.setText("")
  5598. self.ui.rel_position_label.setText("")
  5599. self.mouse = None
  5600. def on_mouse_click_release_over_plot(self, event):
  5601. """
  5602. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5603. and has been registered in ''self.__init__()''.
  5604. :param event: contains information about the event.
  5605. :return:
  5606. """
  5607. if self.is_legacy is False:
  5608. event_pos = event.pos
  5609. right_button = 2
  5610. else:
  5611. event_pos = (event.xdata, event.ydata)
  5612. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5613. right_button = 3
  5614. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5615. if self.grid_status():
  5616. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5617. else:
  5618. pos = (pos_canvas[0], pos_canvas[1])
  5619. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5620. # canvas menu
  5621. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5622. self.ui.popMenu.mouse_is_panning = False
  5623. self.cursor = QtGui.QCursor()
  5624. self.populate_cmenu_grids()
  5625. self.ui.popMenu.popup(self.cursor.pos())
  5626. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5627. # selection and then select a type of selection ("enclosing" or "touching")
  5628. if event.button == 1: # left click
  5629. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5630. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5631. if modifiers == QtCore.Qt.ShiftModifier:
  5632. # do not auto open the Project Tab
  5633. self.click_noproject = True
  5634. self.clipboard.setText(
  5635. self.defaults["global_point_clipboard_format"] %
  5636. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5637. )
  5638. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5639. return
  5640. if self.doubleclick is True:
  5641. self.doubleclick = False
  5642. if self.collection.get_selected():
  5643. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5644. if self.ui.splitter.sizes()[0] == 0:
  5645. self.ui.splitter.setSizes([1, 1])
  5646. try:
  5647. # delete the selection shape(S) as it may be in the way
  5648. self.delete_selection_shape()
  5649. self.delete_hover_shape()
  5650. except Exception as e:
  5651. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5652. return
  5653. else:
  5654. # WORKAROUND for LEGACY MODE
  5655. if self.is_legacy is True:
  5656. # if there is no move on canvas then we have no dragging selection
  5657. if self.dx == 0 or self.dy == 0:
  5658. self.selection_type = None
  5659. if self.selection_type is not None:
  5660. try:
  5661. self.selection_area_handler(self.pos, pos, self.selection_type)
  5662. self.selection_type = None
  5663. except Exception as e:
  5664. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5665. return
  5666. else:
  5667. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5668. if key_modifier == QtCore.Qt.ShiftModifier:
  5669. mod_key = 'Shift'
  5670. elif key_modifier == QtCore.Qt.ControlModifier:
  5671. mod_key = 'Control'
  5672. else:
  5673. mod_key = None
  5674. try:
  5675. if mod_key == self.defaults["global_mselect_key"]:
  5676. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5677. # deselect, and if it's not selected then it will be selected
  5678. # If there is no active command (self.command_active is None) then we check if we clicked
  5679. # on a object by checking the bounding limits against mouse click position
  5680. if self.command_active is None:
  5681. self.select_objects(key='multisel')
  5682. self.delete_hover_shape()
  5683. else:
  5684. # If there is no active command (self.command_active is None) then we check if we clicked
  5685. # on a object by checking the bounding limits against mouse click position
  5686. if self.command_active is None:
  5687. self.select_objects()
  5688. self.delete_hover_shape()
  5689. except Exception as e:
  5690. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5691. return
  5692. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5693. """
  5694. :param start_pos: mouse position when the selection LMB click was done
  5695. :param end_pos: mouse position when the left mouse button is released
  5696. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5697. :return:
  5698. """
  5699. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5700. # delete previous selection shape
  5701. self.delete_selection_shape()
  5702. # make all objects inactive
  5703. self.collection.set_all_inactive()
  5704. for obj in self.collection.get_list():
  5705. try:
  5706. # select the object(s) only if it is enabled (plotted)
  5707. if obj.options['plot']:
  5708. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5709. (obj.options['xmax'], obj.options['ymin']),
  5710. (obj.options['xmax'], obj.options['ymax']),
  5711. (obj.options['xmin'], obj.options['ymax'])])
  5712. if sel_type is True:
  5713. if poly_obj.within(poly_selection):
  5714. # create the selection box around the selected object
  5715. if self.defaults['global_selection_shape'] is True:
  5716. self.draw_selection_shape(obj)
  5717. self.collection.set_active(obj.options['name'])
  5718. else:
  5719. if poly_selection.intersects(poly_obj):
  5720. # create the selection box around the selected object
  5721. if self.defaults['global_selection_shape'] is True:
  5722. self.draw_selection_shape(obj)
  5723. self.collection.set_active(obj.options['name'])
  5724. obj.selection_shape_drawn = True
  5725. except Exception as e:
  5726. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5727. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5728. # In this case poly_obj creation (see above) will fail
  5729. log.debug("App.selection_area_handler() --> %s" % str(e))
  5730. def select_objects(self, key=None):
  5731. """
  5732. Will select objects clicked on canvas
  5733. :param key: for future use in cumulative selection
  5734. :return:
  5735. """
  5736. # list where we store the overlapped objects under our mouse left click position
  5737. if key is None:
  5738. self.objects_under_the_click_list = []
  5739. # Populate the list with the overlapped objects on the click position
  5740. curr_x, curr_y = self.pos
  5741. for obj in self.all_objects_list:
  5742. # ScriptObject and DocumentObject objects can't be selected
  5743. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5744. continue
  5745. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5746. continue
  5747. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5748. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5749. if obj.options['name'] not in self.objects_under_the_click_list:
  5750. if obj.options['plot']:
  5751. # add objects to the objects_under_the_click list only if the object is plotted
  5752. # (active and not disabled)
  5753. self.objects_under_the_click_list.append(obj.options['name'])
  5754. try:
  5755. if self.objects_under_the_click_list:
  5756. curr_sel_obj = self.collection.get_active()
  5757. # case when there is only an object under the click and we toggle it
  5758. if len(self.objects_under_the_click_list) == 1:
  5759. if curr_sel_obj is None:
  5760. self.collection.set_active(self.objects_under_the_click_list[0])
  5761. curr_sel_obj = self.collection.get_active()
  5762. # create the selection box around the selected object
  5763. if self.defaults['global_selection_shape'] is True:
  5764. self.draw_selection_shape(curr_sel_obj)
  5765. curr_sel_obj.selection_shape_drawn = True
  5766. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5767. self.on_objects_selection(False)
  5768. self.delete_selection_shape()
  5769. curr_sel_obj.selection_shape_drawn = False
  5770. self.collection.set_active(self.objects_under_the_click_list[0])
  5771. curr_sel_obj = self.collection.get_active()
  5772. # create the selection box around the selected object
  5773. if self.defaults['global_selection_shape'] is True:
  5774. self.draw_selection_shape(curr_sel_obj)
  5775. curr_sel_obj.selection_shape_drawn = True
  5776. self.selected_message(curr_sel_obj=curr_sel_obj)
  5777. elif curr_sel_obj.selection_shape_drawn is False:
  5778. if self.defaults['global_selection_shape'] is True:
  5779. self.draw_selection_shape(curr_sel_obj)
  5780. curr_sel_obj.selection_shape_drawn = True
  5781. else:
  5782. self.on_objects_selection(False)
  5783. self.delete_selection_shape()
  5784. if self.call_source != 'app':
  5785. self.call_source = 'app'
  5786. self.selected_message(curr_sel_obj=curr_sel_obj)
  5787. else:
  5788. # If there is no selected object
  5789. # make active the first element of the overlapped objects list
  5790. if self.collection.get_active() is None:
  5791. self.collection.set_active(self.objects_under_the_click_list[0])
  5792. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5793. name_sel_obj = self.collection.get_active().options['name']
  5794. # In case that there is a selected object but it is not in the overlapped object list
  5795. # make that object inactive and activate the first element in the overlapped object list
  5796. if name_sel_obj not in self.objects_under_the_click_list:
  5797. self.collection.set_inactive(name_sel_obj)
  5798. name_sel_obj = self.objects_under_the_click_list[0]
  5799. self.collection.set_active(name_sel_obj)
  5800. else:
  5801. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5802. self.collection.set_all_inactive()
  5803. self.collection.set_active(
  5804. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5805. curr_sel_obj = self.collection.get_active()
  5806. # delete the possible selection box around a possible selected object
  5807. self.delete_selection_shape()
  5808. curr_sel_obj.selection_shape_drawn = False
  5809. # create the selection box around the selected object
  5810. if self.defaults['global_selection_shape'] is True:
  5811. self.draw_selection_shape(curr_sel_obj)
  5812. curr_sel_obj.selection_shape_drawn = True
  5813. self.selected_message(curr_sel_obj=curr_sel_obj)
  5814. else:
  5815. # deselect everything
  5816. self.on_objects_selection(False)
  5817. # delete the possible selection box around a possible selected object
  5818. self.delete_selection_shape()
  5819. for o in self.collection.get_list():
  5820. o.selection_shape_drawn = False
  5821. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5822. # only when working on App
  5823. if self.call_source == 'app':
  5824. if self.click_noproject is False:
  5825. # if the Tool Tab is in focus don't change focus to Project Tab
  5826. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5827. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5828. else:
  5829. # restore auto open the Project Tab
  5830. self.click_noproject = False
  5831. # delete any text in the status bar, implicitly the last object name that was selected
  5832. # self.inform.emit("")
  5833. else:
  5834. self.call_source = 'app'
  5835. except Exception as e:
  5836. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5837. def selected_message(self, curr_sel_obj):
  5838. if curr_sel_obj:
  5839. if curr_sel_obj.kind == 'gerber':
  5840. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5841. color='green',
  5842. name=str(curr_sel_obj.options['name']),
  5843. tx=_("selected"))
  5844. )
  5845. elif curr_sel_obj.kind == 'excellon':
  5846. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5847. color='brown',
  5848. name=str(curr_sel_obj.options['name']),
  5849. tx=_("selected"))
  5850. )
  5851. elif curr_sel_obj.kind == 'cncjob':
  5852. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5853. color='blue',
  5854. name=str(curr_sel_obj.options['name']),
  5855. tx=_("selected"))
  5856. )
  5857. elif curr_sel_obj.kind == 'geometry':
  5858. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5859. color='red',
  5860. name=str(curr_sel_obj.options['name']),
  5861. tx=_("selected"))
  5862. )
  5863. def delete_hover_shape(self):
  5864. self.hover_shapes.clear()
  5865. self.hover_shapes.redraw()
  5866. def draw_hover_shape(self, sel_obj, color=None):
  5867. """
  5868. :param sel_obj: The object for which the hover shape must be drawn
  5869. :param color: The color of the hover shape
  5870. :return: None
  5871. """
  5872. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5873. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5874. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5875. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5876. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5877. if self.defaults['units'].upper() == 'MM':
  5878. hover_rect = hover_rect.buffer(-0.1)
  5879. hover_rect = hover_rect.buffer(0.2)
  5880. else:
  5881. hover_rect = hover_rect.buffer(-0.00393)
  5882. hover_rect = hover_rect.buffer(0.00787)
  5883. # if color:
  5884. # face = Color(color)
  5885. # face.alpha = 0.2
  5886. # outline = Color(color, alpha=0.8)
  5887. # else:
  5888. # face = Color(self.defaults['global_sel_fill'])
  5889. # face.alpha = 0.2
  5890. # outline = self.defaults['global_sel_line']
  5891. if color:
  5892. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5893. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5894. else:
  5895. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5896. outline = self.defaults['global_sel_line']
  5897. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5898. if self.is_legacy is True:
  5899. self.hover_shapes.redraw()
  5900. def delete_selection_shape(self):
  5901. self.move_tool.sel_shapes.clear()
  5902. self.move_tool.sel_shapes.redraw()
  5903. def draw_selection_shape(self, sel_obj, color=None):
  5904. """
  5905. Will draw a selection shape around the selected object.
  5906. :param sel_obj: The object for which the selection shape must be drawn
  5907. :param color: The color for the selection shape.
  5908. :return: None
  5909. """
  5910. if sel_obj is None:
  5911. return
  5912. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5913. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5914. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5915. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5916. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5917. if self.defaults['units'].upper() == 'MM':
  5918. sel_rect = sel_rect.buffer(-0.1)
  5919. sel_rect = sel_rect.buffer(0.2)
  5920. else:
  5921. sel_rect = sel_rect.buffer(-0.00393)
  5922. sel_rect = sel_rect.buffer(0.00787)
  5923. if color:
  5924. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5925. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5926. else:
  5927. if self.is_legacy is False:
  5928. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5929. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5930. else:
  5931. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5932. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5933. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5934. color=outline,
  5935. face_color=face,
  5936. update=True,
  5937. layer=0,
  5938. tolerance=None))
  5939. if self.is_legacy is True:
  5940. self.move_tool.sel_shapes.redraw()
  5941. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5942. """
  5943. Will draw a selection shape when dragging mouse on canvas.
  5944. :param old_coords: Old coordinates
  5945. :param coords: New coordinates
  5946. :param kwargs: Keyword arguments
  5947. :return:
  5948. """
  5949. if 'color' in kwargs:
  5950. color = kwargs['color']
  5951. else:
  5952. color = self.defaults['global_sel_line']
  5953. if 'face_color' in kwargs:
  5954. face_color = kwargs['face_color']
  5955. else:
  5956. face_color = self.defaults['global_sel_fill']
  5957. if 'face_alpha' in kwargs:
  5958. face_alpha = kwargs['face_alpha']
  5959. else:
  5960. face_alpha = 0.3
  5961. x0, y0 = old_coords
  5962. x1, y1 = coords
  5963. pt1 = (x0, y0)
  5964. pt2 = (x1, y0)
  5965. pt3 = (x1, y1)
  5966. pt4 = (x0, y1)
  5967. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5968. # color_t = Color(face_color)
  5969. # color_t.alpha = face_alpha
  5970. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5971. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5972. layer=0, tolerance=None)
  5973. if self.is_legacy is True:
  5974. self.move_tool.sel_shapes.redraw()
  5975. def on_file_new_click(self):
  5976. """
  5977. Callback for menu item File -> New.
  5978. Executed on clicking the Menu -> File -> New Project
  5979. :return:
  5980. """
  5981. if self.collection.get_list() and self.should_we_save:
  5982. msgbox = QtWidgets.QMessageBox()
  5983. # msgbox.setText("<B>Save changes ...</B>")
  5984. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5985. "Creating a New project will delete them.\n"
  5986. "Do you want to Save the project?"))
  5987. msgbox.setWindowTitle(_("Save changes"))
  5988. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5989. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5990. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5991. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5992. msgbox.setDefaultButton(bt_yes)
  5993. msgbox.exec_()
  5994. response = msgbox.clickedButton()
  5995. if response == bt_yes:
  5996. self.on_file_saveprojectas()
  5997. elif response == bt_cancel:
  5998. return
  5999. elif response == bt_no:
  6000. self.on_file_new()
  6001. else:
  6002. self.on_file_new()
  6003. self.inform.emit('[success] %s...' % _("New Project created"))
  6004. def on_file_new(self, cli=None):
  6005. """
  6006. Returns the application to its startup state. This method is thread-safe.
  6007. :param cli: Boolean. If True this method was run from command line
  6008. :return: None
  6009. """
  6010. self.defaults.report_usage("on_file_new")
  6011. # Remove everything from memory
  6012. App.log.debug("on_file_new()")
  6013. if self.call_source != 'app':
  6014. self.editor2object(cleanup=True)
  6015. # ## EDITOR section
  6016. self.geo_editor = FlatCAMGeoEditor(self)
  6017. self.exc_editor = FlatCAMExcEditor(self)
  6018. self.grb_editor = FlatCAMGrbEditor(self)
  6019. # Clear pool
  6020. self.clear_pool()
  6021. for obj in self.collection.get_list():
  6022. # delete shapes left drawn from mark shape_collections, if any
  6023. if isinstance(obj, GerberObject):
  6024. try:
  6025. for el in obj.mark_shapes:
  6026. obj.mark_shapes[el].clear(update=True)
  6027. obj.mark_shapes[el].enabled = False
  6028. del el
  6029. except AttributeError:
  6030. pass
  6031. # also delete annotation shapes, if any
  6032. elif isinstance(obj, CNCJobObject):
  6033. try:
  6034. obj.text_col.enabled = False
  6035. del obj.text_col
  6036. obj.annotation.clear(update=True)
  6037. del obj.annotation
  6038. except AttributeError:
  6039. pass
  6040. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6041. self.init_tcl()
  6042. self.delete_selection_shape()
  6043. self.collection.delete_all()
  6044. self.setup_component_editor()
  6045. # Clear project filename
  6046. self.project_filename = None
  6047. # Load the application defaults
  6048. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6049. # Re-fresh project options
  6050. self.on_options_app2project()
  6051. # Init Tools
  6052. self.init_tools()
  6053. if cli is None:
  6054. # Close any Tabs opened in the Plot Tab Area section
  6055. for index in range(self.ui.plot_tab_area.count()):
  6056. self.ui.plot_tab_area.closeTab(index)
  6057. # for whatever reason previous command does not close the last tab so I do it manually
  6058. self.ui.plot_tab_area.closeTab(0)
  6059. # # And then add again the Plot Area
  6060. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6061. self.ui.plot_tab_area.protectTab(0)
  6062. # take the focus of the Notebook on Project Tab.
  6063. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6064. self.set_ui_title(name=_("New Project - Not saved"))
  6065. def obj_properties(self):
  6066. """
  6067. Will launch the object Properties Tool
  6068. :return:
  6069. """
  6070. self.defaults.report_usage("obj_properties()")
  6071. self.properties_tool.run(toggle=False)
  6072. def on_project_context_save(self):
  6073. """
  6074. Wrapper, will save the object function of it's type
  6075. :return:
  6076. """
  6077. obj = self.collection.get_active()
  6078. if type(obj) == GeometryObject:
  6079. self.on_file_exportdxf()
  6080. elif type(obj) == ExcellonObject:
  6081. self.on_file_saveexcellon()
  6082. elif type(obj) == CNCJobObject:
  6083. obj.on_exportgcode_button_click()
  6084. elif type(obj) == GerberObject:
  6085. self.on_file_savegerber()
  6086. elif type(obj) == ScriptObject:
  6087. self.on_file_savescript()
  6088. elif type(obj) == DocumentObject:
  6089. self.on_file_savedocument()
  6090. def obj_move(self):
  6091. """
  6092. Callback for the Move menu entry in various Context Menu's.
  6093. :return:
  6094. """
  6095. self.defaults.report_usage("obj_move()")
  6096. self.move_tool.run(toggle=False)
  6097. def on_fileopengerber(self, signal, name=None):
  6098. """
  6099. File menu callback for opening a Gerber.
  6100. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6101. :param name:
  6102. :return: None
  6103. """
  6104. self.defaults.report_usage("on_fileopengerber")
  6105. App.log.debug("on_fileopengerber()")
  6106. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6107. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6108. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6109. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6110. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6111. "*.mil);;" \
  6112. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6113. "Allegro Files (*.art);;" \
  6114. "Mentor Files (*.pho *.gdo);;" \
  6115. "All Files (*.*)"
  6116. if name is None:
  6117. try:
  6118. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6119. directory=self.get_last_folder(),
  6120. filter=_filter_)
  6121. except TypeError:
  6122. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6123. filenames = [str(filename) for filename in filenames]
  6124. else:
  6125. filenames = [name]
  6126. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6127. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6128. _("Opening Gerber file.")),
  6129. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6130. color=QtGui.QColor("gray"))
  6131. if len(filenames) == 0:
  6132. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6133. else:
  6134. for filename in filenames:
  6135. if filename != '':
  6136. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6137. def on_fileopenexcellon(self, signal, name=None):
  6138. """
  6139. File menu callback for opening an Excellon file.
  6140. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6141. :param name:
  6142. :return: None
  6143. """
  6144. self.defaults.report_usage("on_fileopenexcellon")
  6145. App.log.debug("on_fileopenexcellon()")
  6146. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6147. "All Files (*.*)"
  6148. if name is None:
  6149. try:
  6150. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6151. directory=self.get_last_folder(),
  6152. filter=_filter_)
  6153. except TypeError:
  6154. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6155. filenames = [str(filename) for filename in filenames]
  6156. else:
  6157. filenames = [str(name)]
  6158. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6159. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6160. _("Opening Excellon file.")),
  6161. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6162. color=QtGui.QColor("gray"))
  6163. if len(filenames) == 0:
  6164. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6165. else:
  6166. for filename in filenames:
  6167. if filename != '':
  6168. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6169. def on_fileopengcode(self, signal, name=None):
  6170. """
  6171. File menu call back for opening gcode.
  6172. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6173. :param name:
  6174. :return:
  6175. """
  6176. self.defaults.report_usage("on_fileopengcode")
  6177. App.log.debug("on_fileopengcode()")
  6178. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6179. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6180. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6181. "All Files (*.*)"
  6182. if name is None:
  6183. try:
  6184. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6185. directory=self.get_last_folder(),
  6186. filter=_filter_)
  6187. except TypeError:
  6188. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6189. filenames = [str(filename) for filename in filenames]
  6190. else:
  6191. filenames = [name]
  6192. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6193. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6194. _("Opening G-Code file.")),
  6195. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6196. color=QtGui.QColor("gray"))
  6197. if len(filenames) == 0:
  6198. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6199. else:
  6200. for filename in filenames:
  6201. if filename != '':
  6202. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6203. def on_file_openproject(self, signal):
  6204. """
  6205. File menu callback for opening a project.
  6206. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6207. :return: None
  6208. """
  6209. self.defaults.report_usage("on_file_openproject")
  6210. App.log.debug("on_file_openproject()")
  6211. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6212. try:
  6213. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6214. directory=self.get_last_folder(), filter=_filter_)
  6215. except TypeError:
  6216. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6217. # The Qt methods above will return a QString which can cause problems later.
  6218. # So far json.dump() will fail to serialize it.
  6219. # TODO: Improve the serialization methods and remove this fix.
  6220. filename = str(filename)
  6221. if filename == "":
  6222. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6223. else:
  6224. # self.worker_task.emit({'fcn': self.open_project,
  6225. # 'params': [filename]})
  6226. # The above was failing because open_project() is not
  6227. # thread safe. The new_project()
  6228. self.open_project(filename)
  6229. def on_fileopenhpgl2(self, signal, name=None):
  6230. """
  6231. File menu callback for opening a HPGL2.
  6232. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6233. :param name:
  6234. :return: None
  6235. """
  6236. self.defaults.report_usage("on_fileopenhpgl2")
  6237. App.log.debug("on_fileopenhpgl2()")
  6238. _filter_ = "HPGL2 Files (*.plt);;" \
  6239. "All Files (*.*)"
  6240. if name is None:
  6241. try:
  6242. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6243. directory=self.get_last_folder(),
  6244. filter=_filter_)
  6245. except TypeError:
  6246. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6247. filenames = [str(filename) for filename in filenames]
  6248. else:
  6249. filenames = [name]
  6250. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6251. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6252. _("Opening HPGL2 file.")),
  6253. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6254. color=QtGui.QColor("gray"))
  6255. if len(filenames) == 0:
  6256. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6257. else:
  6258. for filename in filenames:
  6259. if filename != '':
  6260. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6261. def on_file_openconfig(self, signal):
  6262. """
  6263. File menu callback for opening a config file.
  6264. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6265. :return: None
  6266. """
  6267. self.defaults.report_usage("on_file_openconfig")
  6268. App.log.debug("on_file_openconfig()")
  6269. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6270. try:
  6271. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6272. directory=self.data_path, filter=_filter_)
  6273. except TypeError:
  6274. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6275. filter=_filter_)
  6276. if filename == "":
  6277. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6278. else:
  6279. self.open_config_file(filename)
  6280. def on_file_exportsvg(self):
  6281. """
  6282. Callback for menu item File->Export SVG.
  6283. :return: None
  6284. """
  6285. self.defaults.report_usage("on_file_exportsvg")
  6286. App.log.debug("on_file_exportsvg()")
  6287. obj = self.collection.get_active()
  6288. if obj is None:
  6289. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6290. msg = _("Please Select a Geometry object to export")
  6291. msgbox = QtWidgets.QMessageBox()
  6292. msgbox.setInformativeText(msg)
  6293. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6294. msgbox.setDefaultButton(bt_ok)
  6295. msgbox.exec_()
  6296. return
  6297. # Check for more compatible types and add as required
  6298. if (not isinstance(obj, GeometryObject)
  6299. and not isinstance(obj, GerberObject)
  6300. and not isinstance(obj, CNCJobObject)
  6301. and not isinstance(obj, ExcellonObject)):
  6302. msg = '[ERROR_NOTCL] %s' % \
  6303. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6304. msgbox = QtWidgets.QMessageBox()
  6305. msgbox.setInformativeText(msg)
  6306. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6307. msgbox.setDefaultButton(bt_ok)
  6308. msgbox.exec_()
  6309. return
  6310. name = obj.options["name"]
  6311. _filter = "SVG File (*.svg);;All Files (*.*)"
  6312. try:
  6313. filename, _f = FCFileSaveDialog.get_saved_filename(
  6314. caption=_("Export SVG"),
  6315. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6316. filter=_filter)
  6317. except TypeError:
  6318. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6319. filename = str(filename)
  6320. if filename == "":
  6321. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6322. return
  6323. else:
  6324. self.export_svg(name, filename)
  6325. if self.defaults["global_open_style"] is False:
  6326. self.file_opened.emit("SVG", filename)
  6327. self.file_saved.emit("SVG", filename)
  6328. def on_file_exportpng(self):
  6329. self.defaults.report_usage("on_file_exportpng")
  6330. App.log.debug("on_file_exportpng()")
  6331. self.date = str(datetime.today()).rpartition('.')[0]
  6332. self.date = ''.join(c for c in self.date if c not in ':-')
  6333. self.date = self.date.replace(' ', '_')
  6334. if self.is_legacy is False:
  6335. image = _screenshot()
  6336. data = np.asarray(image)
  6337. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6338. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6339. return
  6340. filter_ = "PNG File (*.png);;All Files (*.*)"
  6341. try:
  6342. filename, _f = FCFileSaveDialog.get_saved_filename(
  6343. caption=_("Export PNG Image"),
  6344. directory=self.get_last_save_folder() + '/png_' + self.date,
  6345. filter=filter_)
  6346. except TypeError:
  6347. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6348. filename = str(filename)
  6349. if filename == "":
  6350. self.inform.emit(_("Cancelled."))
  6351. return
  6352. else:
  6353. if self.is_legacy is False:
  6354. write_png(filename, data)
  6355. else:
  6356. self.plotcanvas.figure.savefig(filename)
  6357. if self.defaults["global_open_style"] is False:
  6358. self.file_opened.emit("png", filename)
  6359. self.file_saved.emit("png", filename)
  6360. def on_file_savegerber(self):
  6361. """
  6362. Callback for menu item in Project context menu.
  6363. :return: None
  6364. """
  6365. self.defaults.report_usage("on_file_savegerber")
  6366. App.log.debug("on_file_savegerber()")
  6367. obj = self.collection.get_active()
  6368. if obj is None:
  6369. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6370. return
  6371. # Check for more compatible types and add as required
  6372. if not isinstance(obj, GerberObject):
  6373. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6374. return
  6375. name = self.collection.get_active().options["name"]
  6376. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6377. try:
  6378. filename, _f = FCFileSaveDialog.get_saved_filename(
  6379. caption="Save Gerber source file",
  6380. directory=self.get_last_save_folder() + '/' + name,
  6381. filter=_filter)
  6382. except TypeError:
  6383. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6384. filename = str(filename)
  6385. if filename == "":
  6386. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6387. return
  6388. else:
  6389. self.save_source_file(name, filename)
  6390. if self.defaults["global_open_style"] is False:
  6391. self.file_opened.emit("Gerber", filename)
  6392. self.file_saved.emit("Gerber", filename)
  6393. def on_file_savescript(self):
  6394. """
  6395. Callback for menu item in Project context menu.
  6396. :return: None
  6397. """
  6398. self.defaults.report_usage("on_file_savescript")
  6399. App.log.debug("on_file_savescript()")
  6400. obj = self.collection.get_active()
  6401. if obj is None:
  6402. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6403. return
  6404. # Check for more compatible types and add as required
  6405. if not isinstance(obj, ScriptObject):
  6406. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6407. return
  6408. name = self.collection.get_active().options["name"]
  6409. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6410. try:
  6411. filename, _f = FCFileSaveDialog.get_saved_filename(
  6412. caption="Save Script source file",
  6413. directory=self.get_last_save_folder() + '/' + name,
  6414. filter=_filter)
  6415. except TypeError:
  6416. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6417. filename = str(filename)
  6418. if filename == "":
  6419. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6420. return
  6421. else:
  6422. self.save_source_file(name, filename)
  6423. if self.defaults["global_open_style"] is False:
  6424. self.file_opened.emit("Script", filename)
  6425. self.file_saved.emit("Script", filename)
  6426. def on_file_savedocument(self):
  6427. """
  6428. Callback for menu item in Project context menu.
  6429. :return: None
  6430. """
  6431. self.defaults.report_usage("on_file_savedocument")
  6432. App.log.debug("on_file_savedocument()")
  6433. obj = self.collection.get_active()
  6434. if obj is None:
  6435. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6436. return
  6437. # Check for more compatible types and add as required
  6438. if not isinstance(obj, ScriptObject):
  6439. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6440. return
  6441. name = self.collection.get_active().options["name"]
  6442. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6443. try:
  6444. filename, _f = FCFileSaveDialog.get_saved_filename(
  6445. caption="Save Document source file",
  6446. directory=self.get_last_save_folder() + '/' + name,
  6447. filter=_filter)
  6448. except TypeError:
  6449. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6450. filename = str(filename)
  6451. if filename == "":
  6452. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6453. return
  6454. else:
  6455. self.save_source_file(name, filename)
  6456. if self.defaults["global_open_style"] is False:
  6457. self.file_opened.emit("Document", filename)
  6458. self.file_saved.emit("Document", filename)
  6459. def on_file_saveexcellon(self):
  6460. """
  6461. Callback for menu item in project context menu.
  6462. :return: None
  6463. """
  6464. self.defaults.report_usage("on_file_saveexcellon")
  6465. App.log.debug("on_file_saveexcellon()")
  6466. obj = self.collection.get_active()
  6467. if obj is None:
  6468. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6469. return
  6470. # Check for more compatible types and add as required
  6471. if not isinstance(obj, ExcellonObject):
  6472. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6473. return
  6474. name = self.collection.get_active().options["name"]
  6475. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6476. try:
  6477. filename, _f = FCFileSaveDialog.get_saved_filename(
  6478. caption=_("Save Excellon source file"),
  6479. directory=self.get_last_save_folder() + '/' + name,
  6480. filter=_filter)
  6481. except TypeError:
  6482. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6483. filename = str(filename)
  6484. if filename == "":
  6485. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6486. return
  6487. else:
  6488. self.save_source_file(name, filename)
  6489. if self.defaults["global_open_style"] is False:
  6490. self.file_opened.emit("Excellon", filename)
  6491. self.file_saved.emit("Excellon", filename)
  6492. def on_file_exportexcellon(self):
  6493. """
  6494. Callback for menu item File->Export->Excellon.
  6495. :return: None
  6496. """
  6497. self.defaults.report_usage("on_file_exportexcellon")
  6498. App.log.debug("on_file_exportexcellon()")
  6499. obj = self.collection.get_active()
  6500. if obj is None:
  6501. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6502. return
  6503. # Check for more compatible types and add as required
  6504. if not isinstance(obj, ExcellonObject):
  6505. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6506. return
  6507. name = self.collection.get_active().options["name"]
  6508. _filter = self.defaults["excellon_save_filters"]
  6509. try:
  6510. filename, _f = FCFileSaveDialog.get_saved_filename(
  6511. caption=_("Export Excellon"),
  6512. directory=self.get_last_save_folder() + '/' + name,
  6513. filter=_filter)
  6514. except TypeError:
  6515. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6516. filename = str(filename)
  6517. if filename == "":
  6518. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6519. return
  6520. else:
  6521. used_extension = filename.rpartition('.')[2]
  6522. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6523. self.export_excellon(name, filename)
  6524. if self.defaults["global_open_style"] is False:
  6525. self.file_opened.emit("Excellon", filename)
  6526. self.file_saved.emit("Excellon", filename)
  6527. def on_file_exportgerber(self):
  6528. """
  6529. Callback for menu item File->Export->Gerber.
  6530. :return: None
  6531. """
  6532. self.defaults.report_usage("on_file_exportgerber")
  6533. App.log.debug("on_file_exportgerber()")
  6534. obj = self.collection.get_active()
  6535. if obj is None:
  6536. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6537. return
  6538. # Check for more compatible types and add as required
  6539. if not isinstance(obj, GerberObject):
  6540. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6541. return
  6542. name = self.collection.get_active().options["name"]
  6543. _filter_ = self.defaults['gerber_save_filters']
  6544. try:
  6545. filename, _f = FCFileSaveDialog.get_saved_filename(
  6546. caption=_("Export Gerber"),
  6547. directory=self.get_last_save_folder() + '/' + name,
  6548. filter=_filter_)
  6549. except TypeError:
  6550. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6551. filename = str(filename)
  6552. if filename == "":
  6553. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6554. return
  6555. else:
  6556. used_extension = filename.rpartition('.')[2]
  6557. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6558. self.export_gerber(name, filename)
  6559. if self.defaults["global_open_style"] is False:
  6560. self.file_opened.emit("Gerber", filename)
  6561. self.file_saved.emit("Gerber", filename)
  6562. def on_file_exportdxf(self):
  6563. """
  6564. Callback for menu item File->Export DXF.
  6565. :return: None
  6566. """
  6567. self.defaults.report_usage("on_file_exportdxf")
  6568. App.log.debug("on_file_exportdxf()")
  6569. obj = self.collection.get_active()
  6570. if obj is None:
  6571. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6572. msg = _("Please Select a Geometry object to export")
  6573. msgbox = QtWidgets.QMessageBox()
  6574. msgbox.setInformativeText(msg)
  6575. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6576. msgbox.setDefaultButton(bt_ok)
  6577. msgbox.exec_()
  6578. return
  6579. # Check for more compatible types and add as required
  6580. if not isinstance(obj, GeometryObject):
  6581. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6582. msgbox = QtWidgets.QMessageBox()
  6583. msgbox.setInformativeText(msg)
  6584. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6585. msgbox.setDefaultButton(bt_ok)
  6586. msgbox.exec_()
  6587. return
  6588. name = self.collection.get_active().options["name"]
  6589. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6590. try:
  6591. filename, _f = FCFileSaveDialog.get_saved_filename(
  6592. caption=_("Export DXF"),
  6593. directory=self.get_last_save_folder() + '/' + name,
  6594. filter=_filter_)
  6595. except TypeError:
  6596. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6597. filename = str(filename)
  6598. if filename == "":
  6599. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6600. return
  6601. else:
  6602. self.export_dxf(name, filename)
  6603. if self.defaults["global_open_style"] is False:
  6604. self.file_opened.emit("DXF", filename)
  6605. self.file_saved.emit("DXF", filename)
  6606. def on_file_importsvg(self, type_of_obj):
  6607. """
  6608. Callback for menu item File->Import SVG.
  6609. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6610. :type type_of_obj: str
  6611. :return: None
  6612. """
  6613. self.defaults.report_usage("on_file_importsvg")
  6614. App.log.debug("on_file_importsvg()")
  6615. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6616. try:
  6617. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6618. directory=self.get_last_folder(), filter=_filter_)
  6619. except TypeError:
  6620. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6621. filter=_filter_)
  6622. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6623. type_of_obj = "geometry"
  6624. filenames = [str(filename) for filename in filenames]
  6625. if len(filenames) == 0:
  6626. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6627. else:
  6628. for filename in filenames:
  6629. if filename != '':
  6630. self.worker_task.emit({'fcn': self.import_svg,
  6631. 'params': [filename, type_of_obj]})
  6632. def on_file_importdxf(self, type_of_obj):
  6633. """
  6634. Callback for menu item File->Import DXF.
  6635. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6636. :type type_of_obj: str
  6637. :return: None
  6638. """
  6639. self.defaults.report_usage("on_file_importdxf")
  6640. App.log.debug("on_file_importdxf()")
  6641. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6642. try:
  6643. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6644. directory=self.get_last_folder(),
  6645. filter=_filter_)
  6646. except TypeError:
  6647. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6648. filter=_filter_)
  6649. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6650. type_of_obj = "geometry"
  6651. filenames = [str(filename) for filename in filenames]
  6652. if len(filenames) == 0:
  6653. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6654. else:
  6655. for filename in filenames:
  6656. if filename != '':
  6657. self.worker_task.emit({'fcn': self.import_dxf,
  6658. 'params': [filename, type_of_obj]})
  6659. # ###############################################################################################################
  6660. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6661. # ###############################################################################################################
  6662. def init_code_editor(self, name):
  6663. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6664. # add the tab if it was closed
  6665. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6666. self.text_editor_tab.setObjectName('text_editor_tab')
  6667. # delete the absolute and relative position and messages in the infobar
  6668. self.ui.position_label.setText("")
  6669. self.ui.rel_position_label.setText("")
  6670. # first clear previous text in text editor (if any)
  6671. self.text_editor_tab.code_editor.clear()
  6672. self.text_editor_tab.code_editor.setReadOnly(False)
  6673. self.toggle_codeeditor = True
  6674. self.text_editor_tab.code_editor.completer_enable = False
  6675. self.text_editor_tab.buttonRun.hide()
  6676. # make sure to keep a reference to the code editor
  6677. self.reference_code_editor = self.text_editor_tab.code_editor
  6678. # Switch plot_area to CNCJob tab
  6679. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6680. def on_view_source(self):
  6681. """
  6682. Called when the user wants to see the source file of the selected object
  6683. :return:
  6684. """
  6685. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6686. self.proc_container.view.set_busy(_("Loading..."))
  6687. try:
  6688. obj = self.collection.get_active()
  6689. except Exception as e:
  6690. log.debug("App.on_view_source() --> %s" % str(e))
  6691. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6692. return 'fail'
  6693. if obj is None:
  6694. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6695. return 'fail'
  6696. flt = "All Files (*.*)"
  6697. if obj.kind == 'gerber':
  6698. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6699. elif obj.kind == 'excellon':
  6700. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6701. elif obj.kind == 'cncjob':
  6702. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6703. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6704. # add the tab if it was closed
  6705. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6706. self.source_editor_tab.setObjectName('source_editor_tab')
  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. # first clear previous text in text editor (if any)
  6711. self.source_editor_tab.code_editor.clear()
  6712. self.source_editor_tab.code_editor.setReadOnly(False)
  6713. self.source_editor_tab.code_editor.completer_enable = False
  6714. self.source_editor_tab.buttonRun.hide()
  6715. # Switch plot_area to CNCJob tab
  6716. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6717. try:
  6718. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6719. except TypeError:
  6720. pass
  6721. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6722. try:
  6723. self.source_editor_tab.buttonSave.clicked.disconnect()
  6724. except TypeError:
  6725. pass
  6726. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6727. # then append the text from GCode to the text editor
  6728. if obj.kind == 'cncjob':
  6729. try:
  6730. file = obj.export_gcode(
  6731. preamble=self.defaults["cncjob_prepend"],
  6732. postamble=self.defaults["cncjob_append"],
  6733. to_file=True)
  6734. if file == 'fail':
  6735. return 'fail'
  6736. except AttributeError:
  6737. self.inform.emit('[WARNING_NOTCL] %s' %
  6738. _("There is no selected object for which to see it's source file code."))
  6739. return 'fail'
  6740. else:
  6741. try:
  6742. file = StringIO(obj.source_file)
  6743. except (AttributeError, TypeError):
  6744. self.inform.emit('[WARNING_NOTCL] %s' %
  6745. _("There is no selected object for which to see it's source file code."))
  6746. return 'fail'
  6747. self.source_editor_tab.t_frame.hide()
  6748. try:
  6749. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6750. # for line in file:
  6751. # QtWidgets.QApplication.processEvents()
  6752. # proc_line = str(line).strip('\n')
  6753. # self.source_editor_tab.code_editor.append(proc_line)
  6754. except Exception as e:
  6755. log.debug('App.on_view_source() -->%s' % str(e))
  6756. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6757. return
  6758. self.source_editor_tab.handleTextChanged()
  6759. self.source_editor_tab.t_frame.show()
  6760. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6761. self.proc_container.view.set_idle()
  6762. # self.ui.show()
  6763. def on_toggle_code_editor(self):
  6764. self.defaults.report_usage("on_toggle_code_editor()")
  6765. if self.toggle_codeeditor is False:
  6766. self.init_code_editor(name=_("Code Editor"))
  6767. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6768. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6769. self.text_editor_tab.buttonSave.clicked.disconnect()
  6770. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6771. else:
  6772. for idx in range(self.ui.plot_tab_area.count()):
  6773. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6774. self.ui.plot_tab_area.closeTab(idx)
  6775. break
  6776. self.toggle_codeeditor = False
  6777. def on_code_editor_close(self):
  6778. self.toggle_codeeditor = False
  6779. def goto_text_line(self):
  6780. """
  6781. Will scroll a text to the specified text line.
  6782. :return: None
  6783. """
  6784. dia_box = Dialog_box(title=_("Go to Line ..."),
  6785. label=_("Line:"),
  6786. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6787. initial_text='')
  6788. try:
  6789. line = int(dia_box.location) - 1
  6790. except (ValueError, TypeError):
  6791. line = 0
  6792. if dia_box.ok:
  6793. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6794. # at the top of the window
  6795. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6796. # get the document() of the TextEditor
  6797. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6798. # create a Text Cursor based on the searched line
  6799. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6800. # set cursor of the code editor with the cursor at the searcehd line
  6801. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6802. def on_filenewscript(self, silent=False, name=None, text=None):
  6803. """
  6804. Will create a new script file and open it in the Code Editor
  6805. :param silent: if True will not display status messages
  6806. :param name: if specified will be the name of the new script
  6807. :param text: pass a source file to the newly created script to be loaded in it
  6808. :return: None
  6809. """
  6810. if silent is False:
  6811. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6812. # delete the absolute and relative position and messages in the infobar
  6813. self.ui.position_label.setText("")
  6814. self.ui.rel_position_label.setText("")
  6815. if name is not None:
  6816. self.new_script_object(name=name, text=text)
  6817. else:
  6818. self.new_script_object(text=text)
  6819. # script_text = script_obj.source_file
  6820. #
  6821. # self.proc_container.view.set_busy(_("Loading..."))
  6822. # script_obj.script_editor_tab.t_frame.hide()
  6823. #
  6824. # script_obj.script_editor_tab.t_frame.show()
  6825. # self.proc_container.view.set_idle()
  6826. def on_fileopenscript(self, name=None, silent=False):
  6827. """
  6828. Will open a Tcl script file into the Code Editor
  6829. :param silent: if True will not display status messages
  6830. :param name: name of a Tcl script file to open
  6831. :return:
  6832. """
  6833. self.defaults.report_usage("on_fileopenscript")
  6834. App.log.debug("on_fileopenscript()")
  6835. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6836. "All Files (*.*)"
  6837. if name:
  6838. filenames = [name]
  6839. else:
  6840. try:
  6841. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6842. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6843. except TypeError:
  6844. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6845. if len(filenames) == 0:
  6846. if silent is False:
  6847. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6848. else:
  6849. for filename in filenames:
  6850. if filename != '':
  6851. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6852. def on_filerunscript(self, name=None, silent=False):
  6853. """
  6854. File menu callback for loading and running a TCL script.
  6855. :param silent: if True will not display status messages
  6856. :param name: name of a Tcl script file to be run by FlatCAM
  6857. :return: None
  6858. """
  6859. self.defaults.report_usage("on_filerunscript")
  6860. App.log.debug("on_file_runscript()")
  6861. if name:
  6862. filename = name
  6863. if self.cmd_line_headless != 1:
  6864. self.splash.showMessage('%s: %ssec\n%s' %
  6865. (_("Canvas initialization started.\n"
  6866. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6867. _("Executing ScriptObject file.")
  6868. ),
  6869. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6870. color=QtGui.QColor("gray"))
  6871. else:
  6872. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6873. "All Files (*.*)"
  6874. try:
  6875. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6876. directory=self.get_last_folder(), filter=_filter_)
  6877. except TypeError:
  6878. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6879. # The Qt methods above will return a QString which can cause problems later.
  6880. # So far json.dump() will fail to serialize it.
  6881. filename = str(filename)
  6882. if filename == "":
  6883. if silent is False:
  6884. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6885. else:
  6886. if self.cmd_line_headless != 1:
  6887. if self.ui.shell_dock.isHidden():
  6888. self.ui.shell_dock.show()
  6889. try:
  6890. with open(filename, "r") as tcl_script:
  6891. cmd_line_shellfile_content = tcl_script.read()
  6892. if self.cmd_line_headless != 1:
  6893. self.shell.exec_command(cmd_line_shellfile_content)
  6894. else:
  6895. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6896. if silent is False:
  6897. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6898. except Exception as e:
  6899. log.debug("App.on_filerunscript() -> %s" % str(e))
  6900. sys.exit(2)
  6901. def on_file_saveproject(self, silent=False):
  6902. """
  6903. Callback for menu item File->Save Project. Saves the project to
  6904. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6905. if set to None. The project is saved by calling ``self.save_project()``.
  6906. :param silent: if True will not display status messages
  6907. :return: None
  6908. """
  6909. self.defaults.report_usage("on_file_saveproject")
  6910. if self.project_filename is None:
  6911. self.on_file_saveprojectas()
  6912. else:
  6913. self.worker_task.emit({'fcn': self.save_project,
  6914. 'params': [self.project_filename, silent]})
  6915. if self.defaults["global_open_style"] is False:
  6916. self.file_opened.emit("project", self.project_filename)
  6917. self.file_saved.emit("project", self.project_filename)
  6918. self.set_ui_title(name=self.project_filename)
  6919. self.should_we_save = False
  6920. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6921. """
  6922. Callback for menu item File->Save Project As... Opens a file
  6923. chooser and saves the project to the given file via
  6924. ``self.save_project()``.
  6925. :param make_copy if to be create a copy of the project; boolean
  6926. :param use_thread: if to be run in a separate thread; boolean
  6927. :param quit_action: if to be followed by quiting the application; boolean
  6928. :return: None
  6929. """
  6930. self.defaults.report_usage("on_file_saveprojectas")
  6931. self.date = str(datetime.today()).rpartition('.')[0]
  6932. self.date = ''.join(c for c in self.date if c not in ':-')
  6933. self.date = self.date.replace(' ', '_')
  6934. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6935. try:
  6936. filename, _f = FCFileSaveDialog.get_saved_filename(
  6937. caption=_("Save Project As ..."),
  6938. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6939. proj=_("Project")),
  6940. filter=filter_
  6941. )
  6942. except TypeError:
  6943. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6944. filename = str(filename)
  6945. if filename == '':
  6946. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6947. return
  6948. if use_thread is True:
  6949. self.worker_task.emit({'fcn': self.save_project,
  6950. 'params': [filename, quit_action]})
  6951. else:
  6952. self.save_project(filename, quit_action)
  6953. # self.save_project(filename)
  6954. if self.defaults["global_open_style"] is False:
  6955. self.file_opened.emit("project", filename)
  6956. self.file_saved.emit("project", filename)
  6957. if not make_copy:
  6958. self.project_filename = filename
  6959. self.set_ui_title(name=self.project_filename)
  6960. self.should_we_save = False
  6961. def on_file_save_objects_pdf(self, use_thread=True):
  6962. self.date = str(datetime.today()).rpartition('.')[0]
  6963. self.date = ''.join(c for c in self.date if c not in ':-')
  6964. self.date = self.date.replace(' ', '_')
  6965. try:
  6966. obj_selection = self.collection.get_selected()
  6967. if len(obj_selection) == 1:
  6968. obj_name = str(obj_selection[0].options['name'])
  6969. else:
  6970. obj_name = _("FlatCAM objects print")
  6971. except AttributeError as err:
  6972. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6973. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6974. return
  6975. if not obj_selection:
  6976. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6977. return
  6978. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6979. try:
  6980. filename, _f = FCFileSaveDialog.get_saved_filename(
  6981. caption=_("Save Object as PDF ..."),
  6982. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6983. obj_name=obj_name,
  6984. date=self.date),
  6985. filter=filter_
  6986. )
  6987. except TypeError:
  6988. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  6989. filename = str(filename)
  6990. if filename == '':
  6991. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6992. return
  6993. if use_thread is True:
  6994. proc = self.proc_container.new(_("Printing PDF ... Please wait."))
  6995. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6996. else:
  6997. self.save_pdf(filename, obj_selection)
  6998. # self.save_project(filename)
  6999. if self.defaults["global_open_style"] is False:
  7000. self.file_opened.emit("pdf", filename)
  7001. self.file_saved.emit("pdf", filename)
  7002. def save_pdf(self, file_name, obj_selection):
  7003. p_size = self.defaults['global_workspaceT']
  7004. orientation = self.defaults['global_workspace_orientation']
  7005. color = 'black'
  7006. transparency_level = 1.0
  7007. self.pagesize = {}
  7008. self.pagesize.update(
  7009. {
  7010. 'Bounds': None,
  7011. 'A0': (841 * mm, 1189 * mm),
  7012. 'A1': (594 * mm, 841 * mm),
  7013. 'A2': (420 * mm, 594 * mm),
  7014. 'A3': (297 * mm, 420 * mm),
  7015. 'A4': (210 * mm, 297 * mm),
  7016. 'A5': (148 * mm, 210 * mm),
  7017. 'A6': (105 * mm, 148 * mm),
  7018. 'A7': (74 * mm, 105 * mm),
  7019. 'A8': (52 * mm, 74 * mm),
  7020. 'A9': (37 * mm, 52 * mm),
  7021. 'A10': (26 * mm, 37 * mm),
  7022. 'B0': (1000 * mm, 1414 * mm),
  7023. 'B1': (707 * mm, 1000 * mm),
  7024. 'B2': (500 * mm, 707 * mm),
  7025. 'B3': (353 * mm, 500 * mm),
  7026. 'B4': (250 * mm, 353 * mm),
  7027. 'B5': (176 * mm, 250 * mm),
  7028. 'B6': (125 * mm, 176 * mm),
  7029. 'B7': (88 * mm, 125 * mm),
  7030. 'B8': (62 * mm, 88 * mm),
  7031. 'B9': (44 * mm, 62 * mm),
  7032. 'B10': (31 * mm, 44 * mm),
  7033. 'C0': (917 * mm, 1297 * mm),
  7034. 'C1': (648 * mm, 917 * mm),
  7035. 'C2': (458 * mm, 648 * mm),
  7036. 'C3': (324 * mm, 458 * mm),
  7037. 'C4': (229 * mm, 324 * mm),
  7038. 'C5': (162 * mm, 229 * mm),
  7039. 'C6': (114 * mm, 162 * mm),
  7040. 'C7': (81 * mm, 114 * mm),
  7041. 'C8': (57 * mm, 81 * mm),
  7042. 'C9': (40 * mm, 57 * mm),
  7043. 'C10': (28 * mm, 40 * mm),
  7044. # American paper sizes
  7045. 'LETTER': (8.5 * inch, 11 * inch),
  7046. 'LEGAL': (8.5 * inch, 14 * inch),
  7047. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7048. # From https://en.wikipedia.org/wiki/Paper_size
  7049. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7050. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7051. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7052. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7053. 'LEDGER': (17 * inch, 11 * inch),
  7054. }
  7055. )
  7056. exported_svg = []
  7057. for obj in obj_selection:
  7058. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7059. scale_factor_x=None, scale_factor_y=None,
  7060. skew_factor_x=None, skew_factor_y=None,
  7061. mirror=None)
  7062. if obj.kind.lower() == 'gerber':
  7063. # color = self.defaults["gerber_plot_fill"][:-2]
  7064. color = obj.fill_color[:-2]
  7065. elif obj.kind.lower() == 'excellon':
  7066. color = '#C40000'
  7067. elif obj.kind.lower() == 'geometry':
  7068. color = self.defaults["global_draw_color"]
  7069. # Change the attributes of the exported SVG
  7070. # We don't need stroke-width
  7071. # We set opacity to maximum
  7072. # We set the colour to WHITE
  7073. root = ET.fromstring(svg_obj)
  7074. for child in root:
  7075. child.set('fill', str(color))
  7076. child.set('opacity', str(transparency_level))
  7077. child.set('stroke', str(color))
  7078. exported_svg.append(ET.tostring(root))
  7079. xmin = Inf
  7080. ymin = Inf
  7081. xmax = -Inf
  7082. ymax = -Inf
  7083. for obj in obj_selection:
  7084. try:
  7085. gxmin, gymin, gxmax, gymax = obj.bounds()
  7086. xmin = min([xmin, gxmin])
  7087. ymin = min([ymin, gymin])
  7088. xmax = max([xmax, gxmax])
  7089. ymax = max([ymax, gymax])
  7090. except Exception as e:
  7091. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7092. # Determine bounding area for svg export
  7093. bounds = [xmin, ymin, xmax, ymax]
  7094. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7095. # This contain the measure units
  7096. uom = obj_selection[0].units.lower()
  7097. # Define a boundary around SVG of about 1.0mm (~39mils)
  7098. if uom in "mm":
  7099. boundary = 1.0
  7100. else:
  7101. boundary = 0.0393701
  7102. # Convert everything to strings for use in the xml doc
  7103. svgwidth = str(size[0] + (2 * boundary))
  7104. svgheight = str(size[1] + (2 * boundary))
  7105. minx = str(bounds[0] - boundary)
  7106. miny = str(bounds[1] + boundary + size[1])
  7107. # Add a SVG Header and footer to the svg output from shapely
  7108. # The transform flips the Y Axis so that everything renders
  7109. # properly within svg apps such as inkscape
  7110. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7111. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7112. svg_header += 'width="' + svgwidth + uom + '" '
  7113. svg_header += 'height="' + svgheight + uom + '" '
  7114. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7115. svg_header += '>'
  7116. svg_header += '<g transform="scale(1,-1)">'
  7117. svg_footer = '</g> </svg>'
  7118. svg_elem = str(svg_header)
  7119. for svg_item in exported_svg:
  7120. svg_elem += str(svg_item)
  7121. svg_elem += str(svg_footer)
  7122. # Parse the xml through a xml parser just to add line feeds
  7123. # and to make it look more pretty for the output
  7124. doc = parse_xml_string(svg_elem)
  7125. doc_final = doc.toprettyxml()
  7126. try:
  7127. if self.defaults['units'].upper() == 'IN':
  7128. unit = inch
  7129. else:
  7130. unit = mm
  7131. doc_final = StringIO(doc_final)
  7132. drawing = svg2rlg(doc_final)
  7133. if p_size == 'Bounds':
  7134. renderPDF.drawToFile(drawing, file_name)
  7135. else:
  7136. if orientation == 'p':
  7137. page_size = portrait(self.pagesize[p_size])
  7138. else:
  7139. page_size = landscape(self.pagesize[p_size])
  7140. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7141. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7142. renderPDF.draw(drawing, my_canvas, 0, 0)
  7143. my_canvas.save()
  7144. except Exception as e:
  7145. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7146. return 'fail'
  7147. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7148. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7149. """
  7150. Exports a Geometry Object to an SVG file.
  7151. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7152. :param filename: Path to the SVG file to save to.
  7153. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7154. :return:
  7155. """
  7156. self.defaults.report_usage("export_svg()")
  7157. if filename is None:
  7158. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7159. is not None else self.defaults["global_last_folder"]
  7160. self.log.debug("export_svg()")
  7161. try:
  7162. obj = self.collection.get_by_name(str(obj_name))
  7163. except Exception:
  7164. # TODO: The return behavior has not been established... should raise exception?
  7165. return "Could not retrieve object: %s" % obj_name
  7166. with self.proc_container.new(_("Exporting SVG")) as proc:
  7167. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7168. # Determine bounding area for svg export
  7169. bounds = obj.bounds()
  7170. size = obj.size()
  7171. # Convert everything to strings for use in the xml doc
  7172. svgwidth = str(size[0])
  7173. svgheight = str(size[1])
  7174. minx = str(bounds[0])
  7175. miny = str(bounds[1] - size[1])
  7176. uom = obj.units.lower()
  7177. # Add a SVG Header and footer to the svg output from shapely
  7178. # The transform flips the Y Axis so that everything renders
  7179. # properly within svg apps such as inkscape
  7180. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7181. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7182. svg_header += 'width="' + svgwidth + uom + '" '
  7183. svg_header += 'height="' + svgheight + uom + '" '
  7184. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7185. svg_header += '<g transform="scale(1,-1)">'
  7186. svg_footer = '</g> </svg>'
  7187. svg_elem = svg_header + exported_svg + svg_footer
  7188. # Parse the xml through a xml parser just to add line feeds
  7189. # and to make it look more pretty for the output
  7190. svgcode = parse_xml_string(svg_elem)
  7191. svgcode = svgcode.toprettyxml()
  7192. try:
  7193. with open(filename, 'w') as fp:
  7194. fp.write(svgcode)
  7195. except PermissionError:
  7196. self.inform.emit('[WARNING] %s' %
  7197. _("Permission denied, saving not possible.\n"
  7198. "Most likely another app is holding the file open and not accessible."))
  7199. return 'fail'
  7200. if self.defaults["global_open_style"] is False:
  7201. self.file_opened.emit("SVG", filename)
  7202. self.file_saved.emit("SVG", filename)
  7203. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7204. def save_source_file(self, obj_name, filename, use_thread=True):
  7205. """
  7206. Exports a FlatCAM Object to an Gerber/Excellon file.
  7207. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7208. :param filename: Path to the Gerber file to save to.
  7209. :param use_thread: if to be run in a separate thread
  7210. :return:
  7211. """
  7212. self.defaults.report_usage("save source file()")
  7213. if filename is None:
  7214. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7215. is not None else self.defaults["global_last_folder"]
  7216. self.log.debug("save source file()")
  7217. obj = self.collection.get_by_name(obj_name)
  7218. file_string = StringIO(obj.source_file)
  7219. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7220. if file_string.getvalue() == '':
  7221. self.inform.emit('[ERROR_NOTCL] %s' %
  7222. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7223. return 'fail'
  7224. try:
  7225. with open(filename, 'w') as file:
  7226. file.writelines('G04*\n')
  7227. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7228. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7229. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7230. file.writelines('G04 Created on : %s*\n' % time_string)
  7231. for line in file_string:
  7232. file.writelines(line)
  7233. except PermissionError:
  7234. self.inform.emit('[WARNING] %s' %
  7235. _("Permission denied, saving not possible.\n"
  7236. "Most likely another app is holding the file open and not accessible."))
  7237. return 'fail'
  7238. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7239. """
  7240. Exports a Excellon Object to an Excellon file.
  7241. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7242. :param filename: Path to the Excellon file to save to.
  7243. :param local_use:
  7244. :param use_thread: if to be run in a separate thread
  7245. :return:
  7246. """
  7247. self.defaults.report_usage("export_excellon()")
  7248. if filename is None:
  7249. if self.defaults["global_last_save_folder"]:
  7250. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7251. else:
  7252. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7253. self.log.debug("export_excellon()")
  7254. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7255. self.defaults["excellon_exp_decimals"]
  7256. )
  7257. if local_use is None:
  7258. try:
  7259. obj = self.collection.get_by_name(str(obj_name))
  7260. except Exception:
  7261. return "Could not retrieve object: %s" % obj_name
  7262. else:
  7263. obj = local_use
  7264. if not isinstance(obj, ExcellonObject):
  7265. self.inform.emit('[ERROR_NOTCL] %s' %
  7266. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7267. return
  7268. # updated units
  7269. eunits = self.defaults["excellon_exp_units"]
  7270. ewhole = self.defaults["excellon_exp_integer"]
  7271. efract = self.defaults["excellon_exp_decimals"]
  7272. ezeros = self.defaults["excellon_exp_zeros"]
  7273. eformat = self.defaults["excellon_exp_format"]
  7274. slot_type = self.defaults["excellon_exp_slot_type"]
  7275. fc_units = self.defaults['units'].upper()
  7276. if fc_units == 'MM':
  7277. factor = 1 if eunits == 'METRIC' else 0.03937
  7278. else:
  7279. factor = 25.4 if eunits == 'METRIC' else 1
  7280. def make_excellon():
  7281. try:
  7282. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7283. header = 'M48\n'
  7284. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7285. (str(self.version), str(self.version_date))
  7286. header += ';Filename: %s' % str(obj_name) + '\n'
  7287. header += ';Created on : %s' % time_str + '\n'
  7288. if eformat == 'dec':
  7289. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7290. header += eunits + '\n'
  7291. for tool in obj.tools:
  7292. if eunits == 'METRIC':
  7293. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7294. tool=str(tool),
  7295. dec=2)
  7296. else:
  7297. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7298. tool=str(tool),
  7299. dec=4)
  7300. else:
  7301. if ezeros == 'LZ':
  7302. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7303. form='ndec', e_zeros='LZ', factor=factor,
  7304. slot_type=slot_type)
  7305. header += '%s,%s\n' % (eunits, 'LZ')
  7306. header += format_exc
  7307. for tool in obj.tools:
  7308. if eunits == 'METRIC':
  7309. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7310. tool=str(tool),
  7311. dec=2)
  7312. else:
  7313. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7314. tool=str(tool),
  7315. dec=4)
  7316. else:
  7317. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7318. form='ndec', e_zeros='TZ', factor=factor,
  7319. slot_type=slot_type)
  7320. header += '%s,%s\n' % (eunits, 'TZ')
  7321. header += format_exc
  7322. for tool in obj.tools:
  7323. if eunits == 'METRIC':
  7324. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7325. tool=str(tool),
  7326. dec=2)
  7327. else:
  7328. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7329. tool=str(tool),
  7330. dec=4)
  7331. header += '%\n'
  7332. footer = 'M30\n'
  7333. exported_excellon = header
  7334. exported_excellon += excellon_code
  7335. exported_excellon += footer
  7336. if local_use is None:
  7337. try:
  7338. with open(filename, 'w') as fp:
  7339. fp.write(exported_excellon)
  7340. except PermissionError:
  7341. self.inform.emit('[WARNING] %s' %
  7342. _("Permission denied, saving not possible.\n"
  7343. "Most likely another app is holding the file open and not accessible."))
  7344. return 'fail'
  7345. if self.defaults["global_open_style"] is False:
  7346. self.file_opened.emit("Excellon", filename)
  7347. self.file_saved.emit("Excellon", filename)
  7348. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7349. else:
  7350. return exported_excellon
  7351. except Exception as e:
  7352. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7353. return 'fail'
  7354. if use_thread is True:
  7355. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7356. def job_thread_exc(app_obj):
  7357. ret = make_excellon()
  7358. if ret == 'fail':
  7359. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7360. return
  7361. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7362. else:
  7363. eret = make_excellon()
  7364. if eret == 'fail':
  7365. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7366. return 'fail'
  7367. if local_use is not None:
  7368. return eret
  7369. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7370. """
  7371. Exports a Gerber Object to an Gerber file.
  7372. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7373. :param filename: Path to the Gerber file to save to.
  7374. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7375. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7376. :param use_thread: if to be run in a separate thread
  7377. :return:
  7378. """
  7379. self.defaults.report_usage("export_gerber()")
  7380. if filename is None:
  7381. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7382. is not None else self.defaults["global_last_folder"]
  7383. self.log.debug("export_gerber()")
  7384. if local_use is None:
  7385. try:
  7386. obj = self.collection.get_by_name(str(obj_name))
  7387. except Exception:
  7388. return "Could not retrieve object: %s" % obj_name
  7389. else:
  7390. obj = local_use
  7391. # updated units
  7392. gunits = self.defaults["gerber_exp_units"]
  7393. gwhole = self.defaults["gerber_exp_integer"]
  7394. gfract = self.defaults["gerber_exp_decimals"]
  7395. gzeros = self.defaults["gerber_exp_zeros"]
  7396. fc_units = self.defaults['units'].upper()
  7397. if fc_units == 'MM':
  7398. factor = 1 if gunits == 'MM' else 0.03937
  7399. else:
  7400. factor = 25.4 if gunits == 'MM' else 1
  7401. def make_gerber():
  7402. try:
  7403. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7404. header = 'G04*\n'
  7405. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7406. (str(self.version), str(self.version_date))
  7407. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7408. header += 'G04 Created on : %s*' % time_str + '\n'
  7409. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7410. header += "%MO{units}*%\n".format(units=gunits)
  7411. for apid in obj.apertures:
  7412. if obj.apertures[apid]['type'] == 'C':
  7413. header += "%ADD{apid}{type},{size}*%\n".format(
  7414. apid=str(apid),
  7415. type='C',
  7416. size=(factor * obj.apertures[apid]['size'])
  7417. )
  7418. elif obj.apertures[apid]['type'] == 'R':
  7419. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7420. apid=str(apid),
  7421. type='R',
  7422. width=(factor * obj.apertures[apid]['width']),
  7423. height=(factor * obj.apertures[apid]['height'])
  7424. )
  7425. elif obj.apertures[apid]['type'] == 'O':
  7426. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7427. apid=str(apid),
  7428. type='O',
  7429. width=(factor * obj.apertures[apid]['width']),
  7430. height=(factor * obj.apertures[apid]['height'])
  7431. )
  7432. header += '\n'
  7433. # obsolete units but some software may need it
  7434. if gunits == 'IN':
  7435. header += 'G70*\n'
  7436. else:
  7437. header += 'G71*\n'
  7438. # Absolute Mode
  7439. header += 'G90*\n'
  7440. header += 'G01*\n'
  7441. # positive polarity
  7442. header += '%LPD*%\n'
  7443. footer = 'M02*\n'
  7444. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7445. exported_gerber = header
  7446. exported_gerber += gerber_code
  7447. exported_gerber += footer
  7448. if local_use is None:
  7449. try:
  7450. with open(filename, 'w') as fp:
  7451. fp.write(exported_gerber)
  7452. except PermissionError:
  7453. self.inform.emit('[WARNING] %s' %
  7454. _("Permission denied, saving not possible.\n"
  7455. "Most likely another app is holding the file open and not accessible."))
  7456. return 'fail'
  7457. if self.defaults["global_open_style"] is False:
  7458. self.file_opened.emit("Gerber", filename)
  7459. self.file_saved.emit("Gerber", filename)
  7460. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7461. else:
  7462. return exported_gerber
  7463. except Exception as e:
  7464. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7465. return 'fail'
  7466. if use_thread is True:
  7467. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7468. def job_thread_grb(app_obj):
  7469. ret = make_gerber()
  7470. if ret == 'fail':
  7471. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7472. return
  7473. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7474. else:
  7475. gret = make_gerber()
  7476. if gret == 'fail':
  7477. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7478. return 'fail'
  7479. if local_use is not None:
  7480. return gret
  7481. def export_dxf(self, obj_name, filename, use_thread=True):
  7482. """
  7483. Exports a Geometry Object to an DXF file.
  7484. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7485. :param filename: Path to the DXF file to save to.
  7486. :param use_thread: if to be run in a separate thread
  7487. :return:
  7488. """
  7489. self.defaults.report_usage("export_dxf()")
  7490. if filename is None:
  7491. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7492. is not None else self.defaults["global_last_folder"]
  7493. self.log.debug("export_dxf()")
  7494. try:
  7495. obj = self.collection.get_by_name(str(obj_name))
  7496. except Exception:
  7497. # TODO: The return behavior has not been established... should raise exception?
  7498. return "Could not retrieve object: %s" % obj_name
  7499. def make_dxf():
  7500. try:
  7501. dxf_code = obj.export_dxf()
  7502. dxf_code.saveas(filename)
  7503. if self.defaults["global_open_style"] is False:
  7504. self.file_opened.emit("DXF", filename)
  7505. self.file_saved.emit("DXF", filename)
  7506. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7507. except Exception:
  7508. return 'fail'
  7509. if use_thread is True:
  7510. with self.proc_container.new(_("Exporting DXF")) as proc:
  7511. def job_thread_exc(app_obj):
  7512. ret_dxf_val = make_dxf()
  7513. if ret_dxf_val == 'fail':
  7514. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7515. return
  7516. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7517. else:
  7518. ret = make_dxf()
  7519. if ret == 'fail':
  7520. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7521. return
  7522. def import_svg(self, filename, geo_type='geometry', outname=None):
  7523. """
  7524. Adds a new Geometry Object to the projects and populates
  7525. it with shapes extracted from the SVG file.
  7526. :param filename: Path to the SVG file.
  7527. :param geo_type: Type of FlatCAM object that will be created from SVG
  7528. :param outname:
  7529. :return:
  7530. """
  7531. self.defaults.report_usage("import_svg()")
  7532. log.debug("App.import_svg()")
  7533. obj_type = ""
  7534. if geo_type is None or geo_type == "geometry":
  7535. obj_type = "geometry"
  7536. elif geo_type == "gerber":
  7537. obj_type = "gerber"
  7538. else:
  7539. self.inform.emit('[ERROR_NOTCL] %s' %
  7540. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7541. return
  7542. units = self.defaults['units'].upper()
  7543. def obj_init(geo_obj, app_obj):
  7544. geo_obj.import_svg(filename, obj_type, units=units)
  7545. geo_obj.multigeo = False
  7546. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7547. with self.proc_container.new(_("Importing SVG")) as proc:
  7548. # Object name
  7549. name = outname or filename.split('/')[-1].split('\\')[-1]
  7550. self.new_object(obj_type, name, obj_init, autoselected=False)
  7551. # Register recent file
  7552. self.file_opened.emit("svg", filename)
  7553. # GUI feedback
  7554. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7555. def import_dxf(self, filename, geo_type='geometry', outname=None):
  7556. """
  7557. Adds a new Geometry Object to the projects and populates
  7558. it with shapes extracted from the DXF file.
  7559. :param filename: Path to the DXF file.
  7560. :param geo_type: Type of FlatCAM object that will be created from DXF
  7561. :param outname: Name for the imported Geometry
  7562. :return:
  7563. """
  7564. self.defaults.report_usage("import_dxf()")
  7565. obj_type = ""
  7566. if geo_type is None or geo_type == "geometry":
  7567. obj_type = "geometry"
  7568. elif geo_type == "gerber":
  7569. obj_type = geo_type
  7570. else:
  7571. self.inform.emit('[ERROR_NOTCL] %s' %
  7572. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7573. return
  7574. units = self.defaults['units'].upper()
  7575. def obj_init(geo_obj, app_obj):
  7576. geo_obj.import_dxf(filename, obj_type, units=units)
  7577. geo_obj.multigeo = False
  7578. with self.proc_container.new(_("Importing DXF")) as proc:
  7579. # Object name
  7580. name = outname or filename.split('/')[-1].split('\\')[-1]
  7581. self.new_object(obj_type, name, obj_init, autoselected=False)
  7582. # Register recent file
  7583. self.file_opened.emit("dxf", filename)
  7584. # GUI feedback
  7585. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7586. def open_gerber(self, filename, outname=None):
  7587. """
  7588. Opens a Gerber file, parses it and creates a new object for
  7589. it in the program. Thread-safe.
  7590. :param outname: Name of the resulting object. None causes the
  7591. name to be that of the file. Str.
  7592. :param filename: Gerber file filename
  7593. :type filename: str
  7594. :return: None
  7595. """
  7596. # How the object should be initialized
  7597. def obj_init(gerber_obj, app_obj):
  7598. assert isinstance(gerber_obj, GerberObject), \
  7599. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7600. # Opening the file happens here
  7601. try:
  7602. gerber_obj.parse_file(filename)
  7603. except IOError:
  7604. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7605. return "fail"
  7606. except ParseError as err:
  7607. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7608. app_obj.log.error(str(err))
  7609. return "fail"
  7610. except Exception as e:
  7611. log.debug("App.open_gerber() --> %s" % str(e))
  7612. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7613. msg += traceback.format_exc()
  7614. app_obj.inform.emit(msg)
  7615. return "fail"
  7616. if gerber_obj.is_empty():
  7617. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7618. _("Object is not Gerber file or empty. Aborting object creation."))
  7619. return "fail"
  7620. App.log.debug("open_gerber()")
  7621. with self.proc_container.new(_("Opening Gerber")) as proc:
  7622. # Object name
  7623. name = outname or filename.split('/')[-1].split('\\')[-1]
  7624. # # ## Object creation # ##
  7625. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  7626. if ret == 'fail':
  7627. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open Gerber failed. Probable not a Gerber file.'))
  7628. return 'fail'
  7629. # Register recent file
  7630. self.file_opened.emit("gerber", filename)
  7631. # GUI feedback
  7632. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7633. def open_excellon(self, filename, outname=None, plot=True):
  7634. """
  7635. Opens an Excellon file, parses it and creates a new object for
  7636. it in the program. Thread-safe.
  7637. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7638. :param filename: Excellon file filename
  7639. :type filename: str
  7640. :param plot: boolean, to plot or not the resulting object
  7641. :return: None
  7642. """
  7643. App.log.debug("open_excellon()")
  7644. # How the object should be initialized
  7645. def obj_init(excellon_obj, app_obj):
  7646. try:
  7647. ret = excellon_obj.parse_file(filename=filename)
  7648. if ret == "fail":
  7649. log.debug("Excellon parsing failed.")
  7650. self.inform.emit('[ERROR_NOTCL] %s' %
  7651. _("This is not Excellon file."))
  7652. return "fail"
  7653. except IOError:
  7654. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7655. (_("Cannot open file"), filename))
  7656. log.debug("Could not open Excellon object.")
  7657. return "fail"
  7658. except Exception:
  7659. msg = '[ERROR_NOTCL] %s' % \
  7660. _("An internal error has occurred. See shell.\n")
  7661. msg += traceback.format_exc()
  7662. app_obj.inform.emit(msg)
  7663. return "fail"
  7664. ret = excellon_obj.create_geometry()
  7665. if ret == 'fail':
  7666. log.debug("Could not create geometry for Excellon object.")
  7667. return "fail"
  7668. for tool in excellon_obj.tools:
  7669. if excellon_obj.tools[tool]['solid_geometry']:
  7670. return
  7671. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7672. (_("No geometry found in file"), filename))
  7673. return "fail"
  7674. with self.proc_container.new(_("Opening Excellon.")):
  7675. # Object name
  7676. name = outname or filename.split('/')[-1].split('\\')[-1]
  7677. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7678. if ret_val == 'fail':
  7679. self.inform.emit('[ERROR_NOTCL] %s' %
  7680. _('Open Excellon file failed. Probable not an Excellon file.'))
  7681. return
  7682. # Register recent file
  7683. self.file_opened.emit("excellon", filename)
  7684. # GUI feedback
  7685. self.inform.emit('[success] %s: %s' %
  7686. (_("Opened"), filename))
  7687. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  7688. """
  7689. Opens a G-gcode file, parses it and creates a new object for
  7690. it in the program. Thread-safe.
  7691. :param filename: G-code file filename
  7692. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7693. :param force_parsing:
  7694. :param plot:
  7695. :return: None
  7696. """
  7697. App.log.debug("open_gcode()")
  7698. # How the object should be initialized
  7699. def obj_init(job_obj, app_obj_):
  7700. """
  7701. :param job_obj: the resulting object
  7702. :type app_obj_: App
  7703. """
  7704. assert isinstance(app_obj_, App), \
  7705. "Initializer expected App, got %s" % type(app_obj_)
  7706. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7707. try:
  7708. f = open(filename)
  7709. gcode = f.read()
  7710. f.close()
  7711. except IOError:
  7712. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  7713. (_("Failed to open"), filename))
  7714. return "fail"
  7715. job_obj.gcode = gcode
  7716. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7717. if gcode_ret == "fail":
  7718. self.inform.emit('[ERROR_NOTCL] %s' %
  7719. _("This is not GCODE"))
  7720. return "fail"
  7721. job_obj.create_geometry()
  7722. with self.proc_container.new(_("Opening G-Code.")):
  7723. # Object name
  7724. name = outname or filename.split('/')[-1].split('\\')[-1]
  7725. # New object creation and file processing
  7726. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7727. if obj_ret == 'fail':
  7728. self.inform.emit('[ERROR_NOTCL] %s' %
  7729. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7730. "Try to load it from File menu.\n "
  7731. "Attempting to create a FlatCAM CNCJob Object from "
  7732. "G-Code file failed during processing"))
  7733. return "fail"
  7734. # Register recent file
  7735. self.file_opened.emit("cncjob", filename)
  7736. # GUI feedback
  7737. self.inform.emit('[success] %s: %s' %
  7738. (_("Opened"), filename))
  7739. def open_hpgl2(self, filename, outname=None):
  7740. """
  7741. Opens a HPGL2 file, parses it and creates a new object for
  7742. it in the program. Thread-safe.
  7743. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7744. :param filename: HPGL2 file filename
  7745. :return: None
  7746. """
  7747. filename = filename
  7748. # How the object should be initialized
  7749. def obj_init(geo_obj, app_obj):
  7750. assert isinstance(geo_obj, GeometryObject), \
  7751. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7752. # Opening the file happens here
  7753. obj = HPGL2(self)
  7754. try:
  7755. HPGL2.parse_file(obj, filename)
  7756. except IOError:
  7757. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7758. return "fail"
  7759. except ParseError as err:
  7760. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7761. app_obj.log.error(str(err))
  7762. return "fail"
  7763. except Exception as e:
  7764. log.debug("App.open_hpgl2() --> %s" % str(e))
  7765. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7766. msg += traceback.format_exc()
  7767. app_obj.inform.emit(msg)
  7768. return "fail"
  7769. geo_obj.multigeo = True
  7770. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7771. geo_obj.tools = deepcopy(obj.tools)
  7772. geo_obj.source_file = deepcopy(obj.source_file)
  7773. del obj
  7774. if not geo_obj.solid_geometry:
  7775. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7776. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7777. return "fail"
  7778. App.log.debug("open_hpgl2()")
  7779. with self.proc_container.new(_("Opening HPGL2")) as proc:
  7780. # Object name
  7781. name = outname or filename.split('/')[-1].split('\\')[-1]
  7782. # # ## Object creation # ##
  7783. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7784. if ret == 'fail':
  7785. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7786. return 'fail'
  7787. # Register recent file
  7788. self.file_opened.emit("geometry", filename)
  7789. # GUI feedback
  7790. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7791. def open_script(self, filename, outname=None, silent=False):
  7792. """
  7793. Opens a Script file, parses it and creates a new object for
  7794. it in the program. Thread-safe.
  7795. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7796. :param filename: Script file filename
  7797. :return: None
  7798. """
  7799. App.log.debug("open_script()")
  7800. with self.proc_container.new(_("Opening TCL Script...")):
  7801. try:
  7802. with open(filename, "r") as opened_script:
  7803. script_content = opened_script.readlines()
  7804. script_content = ''.join(script_content)
  7805. if silent is False:
  7806. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7807. except Exception as e:
  7808. log.debug("App.open_script() -> %s" % str(e))
  7809. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  7810. return
  7811. # Object name
  7812. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7813. # New object creation and file processing
  7814. self.on_filenewscript(name=script_name, text=script_content)
  7815. # Register recent file
  7816. self.file_opened.emit("script", filename)
  7817. # GUI feedback
  7818. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7819. def open_config_file(self, filename, run_from_arg=None):
  7820. """
  7821. Loads a config file from the specified file.
  7822. :param filename: Name of the file from which to load.
  7823. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7824. :return: None
  7825. """
  7826. App.log.debug("Opening config file: " + filename)
  7827. if run_from_arg:
  7828. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7829. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7830. _("Opening FlatCAM Config file.")),
  7831. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7832. color=QtGui.QColor("gray"))
  7833. # # add the tab if it was closed
  7834. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7835. # # first clear previous text in text editor (if any)
  7836. # self.ui.text_editor_tab.code_editor.clear()
  7837. #
  7838. # # Switch plot_area to CNCJob tab
  7839. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7840. # close the Code editor if already open
  7841. if self.toggle_codeeditor:
  7842. self.on_toggle_code_editor()
  7843. self.on_toggle_code_editor()
  7844. try:
  7845. if filename:
  7846. f = QtCore.QFile(filename)
  7847. if f.open(QtCore.QIODevice.ReadOnly):
  7848. stream = QtCore.QTextStream(f)
  7849. code_edited = stream.readAll()
  7850. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7851. f.close()
  7852. except IOError:
  7853. App.log.error("Failed to open config file: %s" % filename)
  7854. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7855. (_("Failed to open config file"), filename))
  7856. return
  7857. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  7858. """
  7859. Loads a project from the specified file.
  7860. 1) Loads and parses file
  7861. 2) Registers the file as recently opened.
  7862. 3) Calls on_file_new()
  7863. 4) Updates options
  7864. 5) Calls new_object() with the object's from_dict() as init method.
  7865. 6) Calls plot_all() if plot=True
  7866. :param filename: Name of the file from which to load.
  7867. :param run_from_arg: True if run for arguments
  7868. :param plot: If True plot all objects in the project
  7869. :param cli: Run from command line
  7870. :return: None
  7871. """
  7872. App.log.debug("Opening project: " + filename)
  7873. # block autosaving while a project is loaded
  7874. self.block_autosave = True
  7875. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7876. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7877. if cli is None:
  7878. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7879. if run_from_arg:
  7880. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7881. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7882. _("Opening FlatCAM Project file.")),
  7883. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7884. color=QtGui.QColor("gray"))
  7885. # Open and parse an uncompressed Project file
  7886. try:
  7887. f = open(filename, 'r')
  7888. except IOError:
  7889. App.log.error("Failed to open project file: %s" % filename)
  7890. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7891. (_("Failed to open project file"), filename))
  7892. return
  7893. try:
  7894. d = json.load(f, object_hook=dict2obj)
  7895. except Exception as e:
  7896. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7897. (filename, str(e)))
  7898. f.close()
  7899. # Open and parse a compressed Project file
  7900. try:
  7901. with lzma.open(filename) as f:
  7902. file_content = f.read().decode('utf-8')
  7903. d = json.loads(file_content, object_hook=dict2obj)
  7904. except Exception as e:
  7905. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7906. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7907. (_("Failed to open project file"), filename))
  7908. return
  7909. # Clear the current project
  7910. # # NOT THREAD SAFE # ##
  7911. if run_from_arg is True:
  7912. pass
  7913. elif cli is True:
  7914. self.delete_selection_shape()
  7915. else:
  7916. self.on_file_new()
  7917. # Project options
  7918. self.options.update(d['options'])
  7919. self.project_filename = filename
  7920. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7921. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7922. if cli is None:
  7923. self.set_screen_units(self.options["units"])
  7924. # Re create objects
  7925. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7926. for obj in d['objs']:
  7927. try:
  7928. def obj_init(obj_inst, app_inst):
  7929. obj_inst.from_dict(obj)
  7930. App.log.debug("Recreating from opened project an %s object: %s" %
  7931. (obj['kind'].capitalize(), obj['options']['name']))
  7932. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7933. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7934. if cli is None:
  7935. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7936. obj['kind'].upper(),
  7937. obj['options']['name']
  7938. )
  7939. )
  7940. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  7941. except Exception as e:
  7942. print('App.open_project() --> ' + str(e))
  7943. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7944. self.should_we_save = False
  7945. self.file_opened.emit("project", filename)
  7946. # restore autosaving after a project was loaded
  7947. self.block_autosave = False
  7948. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7949. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7950. if cli is None:
  7951. self.set_ui_title(name=self.project_filename)
  7952. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7953. def plot_all(self, fit_view=True, use_thread=True):
  7954. """
  7955. Re-generates all plots from all objects.
  7956. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7957. :param use_thread: if True will use threading for plotting the objects
  7958. :return: None
  7959. """
  7960. self.log.debug("Plot_all()")
  7961. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7962. for plot_obj in self.collection.get_list():
  7963. def worker_task(obj):
  7964. with self.proc_container.new("Plotting"):
  7965. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7966. if fit_view is True:
  7967. self.object_plotted.emit(obj)
  7968. if use_thread is True:
  7969. # Send to worker
  7970. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7971. else:
  7972. worker_task(plot_obj)
  7973. def register_folder(self, filename):
  7974. """
  7975. Register the last folder used by the app to open something
  7976. :param filename: the last folder is extracted from the filename
  7977. :return: None
  7978. """
  7979. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7980. def register_save_folder(self, filename):
  7981. """
  7982. Register the last folder used by the app to save something
  7983. :param filename: the last folder is extracted from the filename
  7984. :return: None
  7985. """
  7986. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7987. # def set_progress_bar(self, percentage, text=""):
  7988. # """
  7989. # Set a progress bar to a value (percentage)
  7990. #
  7991. # :param percentage: Value set to the progressbar
  7992. # :param text: Not used
  7993. # :return: None
  7994. # """
  7995. # self.ui.progress_bar.setValue(int(percentage))
  7996. def setup_recent_items(self):
  7997. """
  7998. Setup a dictionary with the recent files accessed, organized by type
  7999. :return:
  8000. """
  8001. icons = {
  8002. "gerber": self.resource_location + "/flatcam_icon16.png",
  8003. "excellon": self.resource_location + "/drill16.png",
  8004. 'geometry': self.resource_location + "/geometry16.png",
  8005. "cncjob": self.resource_location + "/cnc16.png",
  8006. "script": self.resource_location + "/script_new24.png",
  8007. "document": self.resource_location + "/notes16_1.png",
  8008. "project": self.resource_location + "/project16.png",
  8009. "svg": self.resource_location + "/geometry16.png",
  8010. "dxf": self.resource_location + "/dxf16.png",
  8011. "pdf": self.resource_location + "/pdf32.png",
  8012. "image": self.resource_location + "/image16.png"
  8013. }
  8014. try:
  8015. image_opener = self.image_tool.import_image
  8016. except AttributeError:
  8017. image_opener = None
  8018. openers = {
  8019. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8020. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8021. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8022. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8023. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8024. "document": None,
  8025. 'project': self.open_project,
  8026. 'svg': self.import_svg,
  8027. 'dxf': self.import_dxf,
  8028. 'image': image_opener,
  8029. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8030. }
  8031. # Open recent file for files
  8032. try:
  8033. f = open(self.data_path + '/recent.json')
  8034. except IOError:
  8035. App.log.error("Failed to load recent item list.")
  8036. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8037. return
  8038. try:
  8039. self.recent = json.load(f)
  8040. except json.errors.JSONDecodeError:
  8041. App.log.error("Failed to parse recent item list.")
  8042. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8043. f.close()
  8044. return
  8045. f.close()
  8046. # Open recent file for projects
  8047. try:
  8048. fp = open(self.data_path + '/recent_projects.json')
  8049. except IOError:
  8050. App.log.error("Failed to load recent project item list.")
  8051. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8052. return
  8053. try:
  8054. self.recent_projects = json.load(fp)
  8055. except json.errors.JSONDecodeError:
  8056. App.log.error("Failed to parse recent project item list.")
  8057. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8058. fp.close()
  8059. return
  8060. fp.close()
  8061. # Closure needed to create callbacks in a loop.
  8062. # Otherwise late binding occurs.
  8063. def make_callback(func, fname):
  8064. def opener():
  8065. func(fname)
  8066. return opener
  8067. def reset_recent_files():
  8068. # Reset menu
  8069. self.ui.recent.clear()
  8070. self.recent = []
  8071. try:
  8072. ff = open(self.data_path + '/recent.json', 'w')
  8073. except IOError:
  8074. App.log.error("Failed to open recent items file for writing.")
  8075. return
  8076. json.dump(self.recent, ff)
  8077. def reset_recent_projects():
  8078. # Reset menu
  8079. self.ui.recent_projects.clear()
  8080. self.recent_projects = []
  8081. try:
  8082. frp = open(self.data_path + '/recent_projects.json', 'w')
  8083. except IOError:
  8084. App.log.error("Failed to open recent projects items file for writing.")
  8085. return
  8086. json.dump(self.recent, frp)
  8087. # Reset menu
  8088. self.ui.recent.clear()
  8089. self.ui.recent_projects.clear()
  8090. # Create menu items for projects
  8091. for recent in self.recent_projects:
  8092. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8093. if recent['kind'] == 'project':
  8094. try:
  8095. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8096. # Attach callback
  8097. o = make_callback(openers[recent["kind"]], recent['filename'])
  8098. action.triggered.connect(o)
  8099. self.ui.recent_projects.addAction(action)
  8100. except KeyError:
  8101. App.log.error("Unsupported file type: %s" % recent["kind"])
  8102. # Last action in Recent Files menu is one that Clear the content
  8103. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8104. (_("Clear Recent projects")), self)
  8105. clear_action_proj.triggered.connect(reset_recent_projects)
  8106. self.ui.recent_projects.addSeparator()
  8107. self.ui.recent_projects.addAction(clear_action_proj)
  8108. # Create menu items for files
  8109. for recent in self.recent:
  8110. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8111. if recent['kind'] != 'project':
  8112. try:
  8113. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8114. # Attach callback
  8115. o = make_callback(openers[recent["kind"]], recent['filename'])
  8116. action.triggered.connect(o)
  8117. self.ui.recent.addAction(action)
  8118. except KeyError:
  8119. App.log.error("Unsupported file type: %s" % recent["kind"])
  8120. # Last action in Recent Files menu is one that Clear the content
  8121. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8122. (_("Clear Recent files")), self)
  8123. clear_action.triggered.connect(reset_recent_files)
  8124. self.ui.recent.addSeparator()
  8125. self.ui.recent.addAction(clear_action)
  8126. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8127. # self.ui.menufilerecent.set_submenu(recent_menu)
  8128. # recent_menu.show_all()
  8129. # self.ui.recent.show()
  8130. self.log.debug("Recent items list has been populated.")
  8131. def setup_component_editor(self):
  8132. """
  8133. Default text for the Selected tab when is not taken by the Object UI.
  8134. :return:
  8135. """
  8136. # label = QtWidgets.QLabel("Choose an item from Project")
  8137. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8138. sel_title = QtWidgets.QTextEdit(
  8139. _('<b>Shortcut Key List</b>'))
  8140. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8141. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8142. f_settings = QSettings("Open Source", "FlatCAM")
  8143. if f_settings.contains("notebook_font_size"):
  8144. fsize = f_settings.value('notebook_font_size', type=int)
  8145. else:
  8146. fsize = 12
  8147. tsize = fsize + int(fsize / 2)
  8148. # selected_text = (_('''
  8149. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8150. # </p>
  8151. #
  8152. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8153. # The normal flow when working in FlatCAM is the following:</span></p>
  8154. #
  8155. # <ol>
  8156. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8157. # file into
  8158. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8159. # even dragging and dropping the files on the GUI.<br />
  8160. # <br />
  8161. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8162. # drop of the
  8163. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8164. # &nbsp;</li>
  8165. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8166. # and then
  8167. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8168. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8169. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8170. # <br />
  8171. # If the selection of the object is done on the canvas by single click instead, and the
  8172. # <strong>SELECTED TAB</strong>
  8173. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8174. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8175. # it even if it was out of focus.<br />
  8176. # <br />
  8177. # You can change the parameters in this screen and the flow direction is like this:<br />
  8178. # <br />
  8179. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8180. # <strong> Geometry Object
  8181. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8182. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8183. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8184. # </ol>
  8185. #
  8186. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8187. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8188. # <strong>F3</strong>.</span></p>
  8189. #
  8190. # ''').format(fsize=fsize, tsize=tsize))
  8191. selected_text = '''
  8192. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8193. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8194. {s1}</span></p>
  8195. <ol>
  8196. <li><span style="font-size:{fsize}px">{s2}<br />
  8197. <br />
  8198. {s3}</span><br />
  8199. &nbsp;</li>
  8200. <li><span style="font-size:{fsize}px">{s4}<br />
  8201. &nbsp;</li>
  8202. <br />
  8203. <li><span style="font-size:{fsize}px">{s5}<br />
  8204. &nbsp;</li>
  8205. <br />
  8206. <li><span style="font-size:{fsize}px">{s6}<br />
  8207. <br />
  8208. {s7}</span></li>
  8209. </ol>
  8210. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8211. '''.format(
  8212. title=_("Selected Tab - Choose an Item from Project Tab"),
  8213. subtitle=_("Details"),
  8214. s1=_("The normal flow when working in FlatCAM is the following:"),
  8215. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8216. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8217. "files on the GUI."),
  8218. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8219. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8220. "actions offered within the app."),
  8221. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8222. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8223. "SELECTED TAB will be updated with the object properties according to its kind: "
  8224. "Gerber, Excellon, Geometry or CNCJob object."),
  8225. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8226. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8227. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8228. "the SELECTED TAB and populate it even if it was out of focus."),
  8229. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8230. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8231. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8232. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8233. "(again, done in SELECTED TAB) --> Save GCode."),
  8234. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8235. "or through its own key shortcut: <b>F3</b>."),
  8236. tsize=tsize,
  8237. fsize=fsize
  8238. )
  8239. sel_title.setText(selected_text)
  8240. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8241. self.ui.selected_scroll_area.setWidget(sel_title)
  8242. def setup_obj_classes(self):
  8243. """
  8244. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8245. class.
  8246. :return: None
  8247. """
  8248. FlatCAMObj.app = self
  8249. ObjectCollection.app = self
  8250. Gerber.app = self
  8251. Excellon.app = self
  8252. Geometry.app = self
  8253. CNCjob.app = self
  8254. FCProcess.app = self
  8255. FCProcessContainer.app = self
  8256. OptionsGroupUI.app = self
  8257. def version_check(self):
  8258. """
  8259. Checks for the latest version of the program. Alerts the
  8260. user if theirs is outdated. This method is meant to be run
  8261. in a separate thread.
  8262. :return: None
  8263. """
  8264. self.log.debug("version_check()")
  8265. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8266. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8267. App.version_url,
  8268. str(self.defaults['global_serial']),
  8269. str(self.version),
  8270. str(self.os),
  8271. urllib.parse.urlencode(self.defaults["global_stats"])
  8272. )
  8273. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8274. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8275. # urllib.parse.urlencode(self.defaults["global_stats"])
  8276. else:
  8277. # no_stats dict; just so it won't break things on website
  8278. no_ststs_dict = {}
  8279. no_ststs_dict["global_ststs"] = {}
  8280. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) +\
  8281. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8282. App.log.debug("Checking for updates @ %s" % full_url)
  8283. # ## Get the data
  8284. try:
  8285. f = urllib.request.urlopen(full_url)
  8286. except Exception:
  8287. # App.log.warning("Failed checking for latest version. Could not connect.")
  8288. self.log.warning("Failed checking for latest version. Could not connect.")
  8289. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8290. return
  8291. try:
  8292. data = json.load(f)
  8293. except Exception as e:
  8294. App.log.error("Could not parse information about latest version.")
  8295. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8296. App.log.debug("json.load(): %s" % str(e))
  8297. f.close()
  8298. return
  8299. f.close()
  8300. # ## Latest version?
  8301. if self.version >= data["version"]:
  8302. App.log.debug("FlatCAM is up to date!")
  8303. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8304. return
  8305. App.log.debug("Newer version available.")
  8306. self.message.emit(
  8307. _("Newer Version Available"),
  8308. '%s<br><br>><b>%s</b><br>%s' % (
  8309. _("There is a newer version of FlatCAM available for download:"),
  8310. str(data["name"]),
  8311. str(data["message"])
  8312. ),
  8313. _("info")
  8314. )
  8315. def on_plotcanvas_setup(self, container=None):
  8316. """
  8317. This is doing the setup for the plot area (canvas).
  8318. :param container: QT Widget where to install the canvas
  8319. :return: None
  8320. """
  8321. if container:
  8322. plot_container = container
  8323. else:
  8324. plot_container = self.ui.right_layout
  8325. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8326. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8327. self.is_legacy = True
  8328. self.defaults["global_graphic_engine"] = "2D"
  8329. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8330. else:
  8331. try:
  8332. self.plotcanvas = PlotCanvas(plot_container, self)
  8333. except Exception as er:
  8334. msg_txt = traceback.format_exc()
  8335. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8336. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8337. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8338. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8339. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8340. msg += msg_txt
  8341. self.inform.emit(msg)
  8342. return 'fail'
  8343. # So it can receive key presses
  8344. self.plotcanvas.native.setFocus()
  8345. if self.is_legacy is False:
  8346. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8347. # Set the mouse button for panning
  8348. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8349. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8350. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8351. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8352. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8353. # Keys over plot enabled
  8354. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8355. if self.defaults['global_cursor_type'] == 'small':
  8356. self.app_cursor = self.plotcanvas.new_cursor()
  8357. else:
  8358. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8359. if self.ui.grid_snap_btn.isChecked():
  8360. self.app_cursor.enabled = True
  8361. else:
  8362. self.app_cursor.enabled = False
  8363. if self.is_legacy is False:
  8364. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8365. else:
  8366. # will use the default Matplotlib axes
  8367. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8368. def on_zoom_fit(self, event):
  8369. """
  8370. Callback for zoom-fit request. This can be either from the corresponding
  8371. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8372. with axes limits from the geometry bounds of all objects.
  8373. :param event: Ignored.
  8374. :return: None
  8375. """
  8376. if self.is_legacy is False:
  8377. self.plotcanvas.fit_view()
  8378. else:
  8379. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8380. width = xmax - xmin
  8381. height = ymax - ymin
  8382. xmin -= 0.05 * width
  8383. xmax += 0.05 * width
  8384. ymin -= 0.05 * height
  8385. ymax += 0.05 * height
  8386. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8387. def on_zoom_in(self):
  8388. """
  8389. Callback for zoom-in request.
  8390. :return:
  8391. """
  8392. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8393. def on_zoom_out(self):
  8394. """
  8395. Callback for zoom-out request.
  8396. :return:
  8397. """
  8398. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8399. def disable_all_plots(self):
  8400. self.defaults.report_usage("disable_all_plots()")
  8401. self.disable_plots(self.collection.get_list())
  8402. self.inform.emit('[success] %s' %
  8403. _("All plots disabled."))
  8404. def disable_other_plots(self):
  8405. self.defaults.report_usage("disable_other_plots()")
  8406. self.disable_plots(self.collection.get_non_selected())
  8407. self.inform.emit('[success] %s' %
  8408. _("All non selected plots disabled."))
  8409. def enable_all_plots(self):
  8410. self.defaults.report_usage("enable_all_plots()")
  8411. self.enable_plots(self.collection.get_list())
  8412. self.inform.emit('[success] %s' %
  8413. _("All plots enabled."))
  8414. def on_enable_sel_plots(self):
  8415. log.debug("App.on_enable_sel_plot()")
  8416. object_list = self.collection.get_selected()
  8417. self.enable_plots(objects=object_list)
  8418. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8419. def on_disable_sel_plots(self):
  8420. log.debug("App.on_disable_sel_plot()")
  8421. # self.inform.emit(_("Disabling plots ..."))
  8422. object_list = self.collection.get_selected()
  8423. self.disable_plots(objects=object_list)
  8424. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8425. def enable_plots(self, objects):
  8426. """
  8427. Enable plots
  8428. :param objects: list of Objects to be enabled
  8429. :return:
  8430. """
  8431. log.debug("Enabling plots ...")
  8432. # self.inform.emit(_("Working ..."))
  8433. for obj in objects:
  8434. if obj.options['plot'] is False:
  8435. obj.options.set_change_callback(lambda x: None)
  8436. obj.options['plot'] = True
  8437. try:
  8438. # only the Gerber obj has on_plot_cb_click() method
  8439. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8440. # disable this cb while disconnected,
  8441. # in case the operation takes time the user is not allowed to change it
  8442. obj.ui.plot_cb.setDisabled(True)
  8443. except AttributeError:
  8444. pass
  8445. obj.set_form_item("plot")
  8446. try:
  8447. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8448. obj.ui.plot_cb.setDisabled(False)
  8449. except AttributeError:
  8450. pass
  8451. obj.options.set_change_callback(obj.on_options_change)
  8452. def worker_task(objs):
  8453. with self.proc_container.new(_("Enabling plots ...")):
  8454. for plot_obj in objs:
  8455. # obj.options['plot'] = True
  8456. if isinstance(plot_obj, CNCJobObject):
  8457. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8458. else:
  8459. plot_obj.plot(visible=True)
  8460. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8461. # self.plots_updated.emit()
  8462. def disable_plots(self, objects):
  8463. """
  8464. Disables plots
  8465. :param objects: list of Objects to be disabled
  8466. :return:
  8467. """
  8468. # if no objects selected then do nothing
  8469. if not self.collection.get_selected():
  8470. return
  8471. log.debug("Disabling plots ...")
  8472. # self.inform.emit(_("Working ..."))
  8473. for obj in objects:
  8474. if obj.options['plot'] is True:
  8475. obj.options.set_change_callback(lambda x: None)
  8476. obj.options['plot'] = False
  8477. try:
  8478. # only the Gerber obj has on_plot_cb_click() method
  8479. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8480. obj.ui.plot_cb.setDisabled(True)
  8481. except AttributeError:
  8482. pass
  8483. obj.set_form_item("plot")
  8484. try:
  8485. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8486. obj.ui.plot_cb.setDisabled(False)
  8487. except AttributeError:
  8488. pass
  8489. obj.options.set_change_callback(obj.on_options_change)
  8490. try:
  8491. self.delete_selection_shape()
  8492. except Exception as e:
  8493. log.debug("App.disable_plots() --> %s" % str(e))
  8494. # self.plots_updated.emit()
  8495. def worker_task(objs):
  8496. with self.proc_container.new(_("Disabling plots ...")):
  8497. for plot_obj in objs:
  8498. # obj.options['plot'] = True
  8499. if isinstance(plot_obj, CNCJobObject):
  8500. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8501. else:
  8502. plot_obj.plot(visible=False)
  8503. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8504. def toggle_plots(self, objects):
  8505. """
  8506. Toggle plots visibility
  8507. :param objects: list of Objects for which to be toggled the visibility
  8508. :return: None
  8509. """
  8510. # if no objects selected then do nothing
  8511. if not self.collection.get_selected():
  8512. return
  8513. log.debug("Toggling plots ...")
  8514. self.inform.emit(_("Working ..."))
  8515. for obj in objects:
  8516. if obj.options['plot'] is False:
  8517. obj.options['plot'] = True
  8518. else:
  8519. obj.options['plot'] = False
  8520. self.plots_updated.emit()
  8521. def clear_plots(self):
  8522. """
  8523. Clear the plots
  8524. :return: None
  8525. """
  8526. objects = self.collection.get_list()
  8527. for obj in objects:
  8528. obj.clear(obj == objects[-1])
  8529. # Clear pool to free memory
  8530. self.clear_pool()
  8531. def on_set_color_action_triggered(self):
  8532. """
  8533. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8534. :return:
  8535. """
  8536. new_color = self.defaults['gerber_plot_fill']
  8537. clicked_action = self.sender()
  8538. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8539. act_name = clicked_action.text()
  8540. sel_obj_list = self.collection.get_selected()
  8541. if not sel_obj_list:
  8542. return
  8543. # a default value, I just chose this one
  8544. alpha_level = 'BF'
  8545. for sel_obj in sel_obj_list:
  8546. if sel_obj.kind == 'excellon':
  8547. alpha_level = str(hex(
  8548. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8549. elif sel_obj.kind == 'gerber':
  8550. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8551. elif sel_obj.kind == 'geometry':
  8552. alpha_level = 'FF'
  8553. else:
  8554. log.debug(
  8555. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8556. continue
  8557. sel_obj.alpha_level = alpha_level
  8558. if act_name == _('Red'):
  8559. new_color = '#FF0000' + alpha_level
  8560. if act_name == _('Blue'):
  8561. new_color = '#0000FF' + alpha_level
  8562. if act_name == _('Yellow'):
  8563. new_color = '#FFDF00' + alpha_level
  8564. if act_name == _('Green'):
  8565. new_color = '#00FF00' + alpha_level
  8566. if act_name == _('Purple'):
  8567. new_color = '#FF00FF' + alpha_level
  8568. if act_name == _('Brown'):
  8569. new_color = '#A52A2A' + alpha_level
  8570. if act_name == _('White'):
  8571. new_color = '#FFFFFF' + alpha_level
  8572. if act_name == _('Black'):
  8573. new_color = '#000000' + alpha_level
  8574. if act_name == _('Custom'):
  8575. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8576. c_dialog = QtWidgets.QColorDialog()
  8577. plot_fill_color = c_dialog.getColor(initial=new_color)
  8578. if plot_fill_color.isValid() is False:
  8579. return
  8580. new_color = str(plot_fill_color.name()) + alpha_level
  8581. if act_name == _("Default"):
  8582. for sel_obj in sel_obj_list:
  8583. if sel_obj.kind == 'excellon':
  8584. new_color = self.defaults['excellon_plot_fill']
  8585. new_line_color = self.defaults['excellon_plot_line']
  8586. elif sel_obj.kind == 'gerber':
  8587. new_color = self.defaults['gerber_plot_fill']
  8588. new_line_color = self.defaults['gerber_plot_line']
  8589. elif sel_obj.kind == 'geometry':
  8590. new_color = self.defaults['geometry_plot_line']
  8591. new_line_color = self.defaults['geometry_plot_line']
  8592. else:
  8593. log.debug(
  8594. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8595. continue
  8596. sel_obj.fill_color = new_color
  8597. sel_obj.outline_color = new_line_color
  8598. sel_obj.shapes.redraw(
  8599. update_colors=(new_color, new_line_color)
  8600. )
  8601. return
  8602. if act_name == _("Opacity"):
  8603. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8604. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8605. if ok_button:
  8606. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8607. for sel_obj in sel_obj_list:
  8608. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8609. sel_obj.shapes.redraw(
  8610. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8611. )
  8612. return
  8613. new_line_color = color_variant(new_color[:7], 0.7)
  8614. if act_name == _("White"):
  8615. new_line_color = color_variant("#dedede", 0.7)
  8616. for sel_obj in sel_obj_list:
  8617. sel_obj.fill_color = new_color
  8618. sel_obj.outline_color = new_line_color
  8619. sel_obj.shapes.redraw(
  8620. update_colors=(new_color, new_line_color)
  8621. )
  8622. def on_grid_snap_triggered(self, state):
  8623. """
  8624. :param state: A parameter with the state of the grid, boolean
  8625. :return:
  8626. """
  8627. if state:
  8628. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_filled_16.png'))
  8629. else:
  8630. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_16.png'))
  8631. self.ui.snap_infobar_label.clicked_state = state
  8632. def on_grid_icon_snap_clicked(self):
  8633. """
  8634. Slot called by clicking a GUI element, in this case a FCLabel
  8635. :return:
  8636. """
  8637. if isinstance(self.sender(), FCLabel):
  8638. self.ui.grid_snap_btn.trigger()
  8639. def generate_cnc_job(self, objects):
  8640. """
  8641. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8642. :param objects: Selected objects in the Project Tab
  8643. :return:
  8644. """
  8645. self.defaults.report_usage("generate_cnc_job()")
  8646. # for obj in objects:
  8647. # obj.generatecncjob()
  8648. for obj in objects:
  8649. obj.on_generatecnc_button_click()
  8650. def save_project(self, filename, quit_action=False, silent=False):
  8651. """
  8652. Saves the current project to the specified file.
  8653. :param filename: Name of the file in which to save.
  8654. :type filename: str
  8655. :param quit_action: if the project saving will be followed by an app quit; boolean
  8656. :param silent: if True will not display status messages
  8657. :return: None
  8658. """
  8659. self.log.debug("save_project()")
  8660. self.save_in_progress = True
  8661. with self.proc_container.new(_("Saving FlatCAM Project")):
  8662. # Capture the latest changes
  8663. # Current object
  8664. try:
  8665. current_object = self.collection.get_active()
  8666. if current_object:
  8667. current_object.read_form()
  8668. except Exception as e:
  8669. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8670. pass
  8671. # Serialize the whole project
  8672. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8673. "options": self.options,
  8674. "version": self.version}
  8675. if self.defaults["global_save_compressed"] is True:
  8676. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8677. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8678. # # Write
  8679. f.write(g)
  8680. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8681. else:
  8682. # Open file
  8683. try:
  8684. f = open(filename, 'w')
  8685. except IOError:
  8686. App.log.error("Failed to open file for saving: %s", filename)
  8687. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8688. return
  8689. # Write
  8690. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8691. f.close()
  8692. # verification of the saved project
  8693. # Open and parse
  8694. try:
  8695. saved_f = open(filename, 'r')
  8696. except IOError:
  8697. if silent is False:
  8698. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8699. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8700. return
  8701. try:
  8702. saved_d = json.load(saved_f, object_hook=dict2obj)
  8703. except Exception:
  8704. if silent is False:
  8705. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8706. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8707. f.close()
  8708. return
  8709. saved_f.close()
  8710. if silent is False:
  8711. if 'version' in saved_d:
  8712. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8713. else:
  8714. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8715. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8716. tb_settings = QSettings("Open Source", "FlatCAM")
  8717. lock_state = self.ui.lock_action.isChecked()
  8718. tb_settings.setValue('toolbar_lock', lock_state)
  8719. # This will write the setting to the platform specific storage.
  8720. del tb_settings
  8721. # if quit:
  8722. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8723. # t.start()
  8724. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8725. def start_delayed_quit(self, delay, filename, should_quit=None):
  8726. """
  8727. :param delay: period of checking if project file size is more than zero; in seconds
  8728. :param filename: the name of the project file to be checked periodically for size more than zero
  8729. :param should_quit: if the task finished will be followed by an app quit; boolean
  8730. :return:
  8731. """
  8732. to_quit = should_quit
  8733. self.save_timer = QtCore.QTimer()
  8734. self.save_timer.setInterval(delay)
  8735. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8736. self.save_timer.start()
  8737. def check_project_file_size(self, filename, should_quit=None):
  8738. """
  8739. :param filename: the name of the project file to be checked periodically for size more than zero
  8740. :param should_quit: will quit the app if True; boolean
  8741. :return:
  8742. """
  8743. try:
  8744. if os.stat(filename).st_size > 0:
  8745. self.save_in_progress = False
  8746. self.save_timer.stop()
  8747. if should_quit:
  8748. self.app_quit.emit()
  8749. except Exception:
  8750. traceback.print_exc()
  8751. def save_project_auto(self):
  8752. """
  8753. Called periodically to save the project.
  8754. 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
  8755. # progress.
  8756. :return:
  8757. """
  8758. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8759. self.on_file_saveproject()
  8760. def save_project_auto_update(self):
  8761. """
  8762. Update the auto save time interval value.
  8763. :return:
  8764. """
  8765. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8766. try:
  8767. if self.autosave_timer.isActive():
  8768. self.autosave_timer.stop()
  8769. except Exception:
  8770. pass
  8771. if self.defaults['global_autosave'] is True:
  8772. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8773. self.autosave_timer.start()
  8774. def on_plotarea_tab_closed(self, tab_idx):
  8775. """
  8776. :param tab_idx: Index of the Tab from the plotarea that was closed
  8777. :return:
  8778. """
  8779. widget = self.ui.plot_tab_area.widget(tab_idx)
  8780. if widget is not None:
  8781. widget.deleteLater()
  8782. self.ui.plot_tab_area.removeTab(tab_idx)
  8783. def on_options_app2project(self):
  8784. """
  8785. Callback for Options->Transfer Options->App=>Project. Copies options
  8786. from application defaults to project defaults.
  8787. :return: None
  8788. """
  8789. self.defaults.report_usage("on_options_app2project")
  8790. self.preferencesUiManager.defaults_read_form()
  8791. self.options.update(self.defaults)
  8792. def toggle_shell(self):
  8793. """
  8794. Toggle shell: if is visible close it, if it is closed then open it
  8795. :return: None
  8796. """
  8797. self.defaults.report_usage("toggle_shell()")
  8798. if self.ui.shell_dock.isVisible():
  8799. self.ui.shell_dock.hide()
  8800. self.plotcanvas.native.setFocus()
  8801. else:
  8802. self.ui.shell_dock.show()
  8803. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8804. # self.shell._edit.setFocus()
  8805. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8806. # HACK - simulate a mouse click - alternative
  8807. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8808. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8809. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8810. # no_km)
  8811. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8812. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8813. # no_km)
  8814. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8815. def on_toggle_shell_from_settings(self, state):
  8816. """
  8817. Toggle shell: if is visible close it, if it is closed then open it
  8818. :return: None
  8819. """
  8820. self.defaults.report_usage("on_toggle_shell_from_settings()")
  8821. if state is True:
  8822. if not self.ui.shell_dock.isVisible():
  8823. self.ui.shell_dock.show()
  8824. else:
  8825. if self.ui.shell_dock.isVisible():
  8826. self.ui.shell_dock.hide()
  8827. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8828. """
  8829. Shows a message on the FlatCAM Shell
  8830. :param msg: Message to display.
  8831. :param show: Opens the shell.
  8832. :param error: Shows the message as an error.
  8833. :param warning: Shows the message as an warning.
  8834. :param success: Shows the message as an success.
  8835. :param selected: Indicate that something was selected on canvas
  8836. :return: None
  8837. """
  8838. if show:
  8839. self.ui.shell_dock.show()
  8840. try:
  8841. if error:
  8842. self.shell.append_error(msg + "\n")
  8843. elif warning:
  8844. self.shell.append_warning(msg + "\n")
  8845. elif success:
  8846. self.shell.append_success(msg + "\n")
  8847. elif selected:
  8848. self.shell.append_selected(msg + "\n")
  8849. else:
  8850. self.shell.append_output(msg + "\n")
  8851. except AttributeError:
  8852. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8853. class ArgsThread(QtCore.QObject):
  8854. open_signal = pyqtSignal(list)
  8855. start = pyqtSignal()
  8856. if sys.platform == 'win32':
  8857. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8858. else:
  8859. address = ('/tmp/testipc', 'AF_UNIX')
  8860. def __init__(self):
  8861. super(ArgsThread, self).__init__()
  8862. self.listener = None
  8863. self.start.connect(self.run)
  8864. def my_loop(self, address):
  8865. try:
  8866. self.listener = Listener(*address)
  8867. while True:
  8868. conn = self.listener.accept()
  8869. self.serve(conn)
  8870. except socket.error:
  8871. conn = Client(*address)
  8872. conn.send(sys.argv)
  8873. conn.send('close')
  8874. # close the current instance only if there are args
  8875. if len(sys.argv) > 1:
  8876. try:
  8877. self.listener.close()
  8878. except Exception:
  8879. pass
  8880. sys.exit()
  8881. def serve(self, conn):
  8882. while True:
  8883. msg = conn.recv()
  8884. if msg == 'close':
  8885. break
  8886. self.open_signal.emit(msg)
  8887. conn.close()
  8888. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8889. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8890. @pyqtSlot()
  8891. def run(self):
  8892. self.my_loop(self.address)
  8893. # end of file