FlatCAMApp.py 488 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import shutil
  16. from datetime import datetime
  17. import time
  18. import ctypes
  19. import traceback
  20. from PyQt5.QtCore import pyqtSlot, Qt
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Diverse
  37. from FlatCAMCommon import LoudDict, color_variant, ExclusionAreas
  38. from FlatCAMBookmark import BookmarkManager
  39. from FlatCAMDB import ToolsDB2
  40. from vispy.gloo.util import _screenshot
  41. from vispy.io import write_png
  42. # FlatCAM Objects
  43. from defaults import FlatCAMDefaults
  44. from flatcamGUI.preferences.OptionsGroupUI import OptionsGroupUI
  45. from flatcamGUI.preferences.PreferencesUIManager import PreferencesUIManager
  46. from flatcamObjects.ObjectCollection import *
  47. from flatcamObjects.FlatCAMObj import FlatCAMObj
  48. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  49. from flatcamObjects.FlatCAMDocument import DocumentObject
  50. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  51. from flatcamObjects.FlatCAMGeometry import GeometryObject
  52. from flatcamObjects.FlatCAMGerber import GerberObject
  53. from flatcamObjects.FlatCAMScript import ScriptObject
  54. # FlatCAM Parsing files
  55. from flatcamParsers.ParseExcellon import Excellon
  56. from flatcamParsers.ParseGerber import Gerber
  57. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  58. # FlatCAM GUI
  59. from flatcamGUI.PlotCanvas import *
  60. from flatcamGUI.PlotCanvasLegacy import *
  61. from flatcamGUI.FlatCAMGUI import *
  62. from flatcamGUI.GUIElements import FCFileSaveDialog
  63. # FlatCAM Pre-processors
  64. from FlatCAMPostProc import load_preprocessors
  65. # FlatCAM Editors
  66. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  67. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  68. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  69. from flatcamEditors.FlatCAMTextEditor import TextEditor
  70. from flatcamParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from FlatCAMProcess import *
  73. from FlatCAMWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from flatcamTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import FlatCAMTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = 8.993
  138. version_date = "2020/08/01"
  139. beta = True
  140. engine = '3D'
  141. # current date now
  142. date = str(datetime.today()).rpartition('.')[0]
  143. date = ''.join(c for c in date if c not in ':-')
  144. date = date.replace(' ', '_')
  145. # ###############################################################################################################
  146. # ############################################ URLS's ###########################################################
  147. # ###############################################################################################################
  148. # URL for update checks and statistics
  149. version_url = "http://flatcam.org/version"
  150. # App URL
  151. app_url = "http://flatcam.org"
  152. # Manual URL
  153. manual_url = "http://flatcam.org/manual/index.html"
  154. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  155. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  156. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  157. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  158. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  159. # this variable will hold the project status
  160. # if True it will mean that the project was modified and not saved
  161. should_we_save = False
  162. # flag is True if saving action has been triggered
  163. save_in_progress = False
  164. # ###############################################################################################################
  165. # ####################################### APP Signals ######################################################
  166. # ###############################################################################################################
  167. # Inform the user
  168. # Handled by:
  169. # * App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal(str)
  171. app_quit = QtCore.pyqtSignal()
  172. # General purpose background task
  173. worker_task = QtCore.pyqtSignal(dict)
  174. # File opened
  175. # Handled by:
  176. # * register_folder()
  177. # * register_recent()
  178. # Note: Setting the parameters to unicode does not seem
  179. # to have an effect. Then are received as Qstring
  180. # anyway.
  181. # File type and filename
  182. file_opened = QtCore.pyqtSignal(str, str)
  183. # File type and filename
  184. file_saved = QtCore.pyqtSignal(str, str)
  185. # Percentage of progress
  186. progress = QtCore.pyqtSignal(int)
  187. plots_updated = QtCore.pyqtSignal()
  188. # Emitted by new_object() and passes the new object as argument, plot flag.
  189. # on_object_created() adds the object to the collection, plots on appropriate flag
  190. # and emits new_object_available.
  191. object_created = QtCore.pyqtSignal(object, bool, bool)
  192. # Emitted when a object has been changed (like scaled, mirrored)
  193. object_changed = QtCore.pyqtSignal(object)
  194. # Emitted after object has been plotted.
  195. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  196. object_plotted = QtCore.pyqtSignal(object)
  197. # Emitted when a new object has been added or deleted from/to the collection
  198. object_status_changed = QtCore.pyqtSignal(object, str, str)
  199. message = QtCore.pyqtSignal(str, str, str)
  200. # Emmited when shell command is finished(one command only)
  201. shell_command_finished = QtCore.pyqtSignal(object)
  202. # Emitted when multiprocess pool has been recreated
  203. pool_recreated = QtCore.pyqtSignal(object)
  204. # Emitted when an unhandled exception happens
  205. # in the worker task.
  206. thread_exception = QtCore.pyqtSignal(object)
  207. # used to signal that there are arguments for the app
  208. args_at_startup = QtCore.pyqtSignal(list)
  209. # a reusable signal to replot a list of objects
  210. # should be disconnected after use so it can be reused
  211. replot_signal = pyqtSignal(list)
  212. # signal emitted when jumping
  213. jump_signal = pyqtSignal(tuple)
  214. # signal emitted when jumping
  215. locate_signal = pyqtSignal(tuple, str)
  216. # close app signal
  217. close_app_signal = pyqtSignal()
  218. # will perform the cleanup operation after a Graceful Exit
  219. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  220. # graphic residues behind
  221. cleanup = pyqtSignal()
  222. def __init__(self, user_defaults=True):
  223. """
  224. Starts the application.
  225. :return: app
  226. :rtype: App
  227. """
  228. App.log.info("FlatCAM Starting...")
  229. self.main_thread = QtWidgets.QApplication.instance().thread()
  230. # ############################################################################################################
  231. # ################# Setup the listening thread for another instance launching with args ######################
  232. # ############################################################################################################
  233. if sys.platform == 'win32' or sys.platform == 'linux':
  234. # make sure the thread is stored by using a self. otherwise it's garbage collected
  235. self.th = QtCore.QThread()
  236. self.th.start(priority=QtCore.QThread.LowestPriority)
  237. self.new_launch = ArgsThread()
  238. self.new_launch.open_signal[list].connect(self.on_startup_args)
  239. self.new_launch.moveToThread(self.th)
  240. self.new_launch.start.emit()
  241. # ############################################################################################################
  242. # # ######################################## OS-specific #####################################################
  243. # ############################################################################################################
  244. portable = False
  245. # Folder for user settings.
  246. if sys.platform == 'win32':
  247. if platform.architecture()[0] == '32bit':
  248. App.log.debug("Win32!")
  249. else:
  250. App.log.debug("Win64!")
  251. # #######################################################################################################
  252. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  253. # #######################################################################################################
  254. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  255. try:
  256. with open(config_file, 'r'):
  257. pass
  258. except FileNotFoundError:
  259. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  260. try:
  261. with open(config_file, 'r') as f:
  262. try:
  263. for line in f:
  264. param = str(line).replace('\n', '').rpartition('=')
  265. if param[0] == 'portable':
  266. try:
  267. portable = eval(param[2])
  268. except NameError:
  269. portable = False
  270. if param[0] == 'headless':
  271. if param[2].lower() == 'true':
  272. self.cmd_line_headless = 1
  273. else:
  274. self.cmd_line_headless = None
  275. except Exception as e:
  276. log.debug('App.__init__() -->%s' % str(e))
  277. return
  278. except FileNotFoundError as e:
  279. log.debug(str(e))
  280. pass
  281. if portable is False:
  282. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  283. else:
  284. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  285. self.os = 'windows'
  286. else: # Linux/Unix/MacOS
  287. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  288. self.os = 'unix'
  289. # ############################################################################################################
  290. # ################################# Setup folders and files ##################################################
  291. # ############################################################################################################
  292. if not os.path.exists(self.data_path):
  293. os.makedirs(self.data_path)
  294. App.log.debug('Created data folder: ' + self.data_path)
  295. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  296. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  297. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  298. if not os.path.exists(self.preprocessorpaths):
  299. os.makedirs(self.preprocessorpaths)
  300. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  301. # create geo_tools_db.FlatDB file if there is none
  302. try:
  303. f = open(self.data_path + '/geo_tools_db.FlatDB')
  304. f.close()
  305. except IOError:
  306. App.log.debug('Creating empty geo_tool_db.FlatDB')
  307. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  308. json.dump({}, f)
  309. f.close()
  310. # create current_defaults.FlatConfig file if there is none
  311. try:
  312. f = open(self.data_path + '/current_defaults.FlatConfig')
  313. f.close()
  314. except IOError:
  315. App.log.debug('Creating empty current_defaults.FlatConfig')
  316. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  317. json.dump({}, f)
  318. f.close()
  319. # Write factory_defaults.FlatConfig file to disk
  320. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  321. # create a recent files json file if there is none
  322. try:
  323. f = open(self.data_path + '/recent.json')
  324. f.close()
  325. except IOError:
  326. App.log.debug('Creating empty recent.json')
  327. f = open(self.data_path + '/recent.json', 'w')
  328. json.dump([], f)
  329. f.close()
  330. # create a recent projects json file if there is none
  331. try:
  332. fp = open(self.data_path + '/recent_projects.json')
  333. fp.close()
  334. except IOError:
  335. App.log.debug('Creating empty recent_projects.json')
  336. fp = open(self.data_path + '/recent_projects.json', 'w')
  337. json.dump([], fp)
  338. fp.close()
  339. # Application directory. CHDIR to it. Otherwise, trying to load
  340. # GUI icons will fail as their path is relative.
  341. # This will fail under cx_freeze ...
  342. self.app_home = os.path.dirname(os.path.realpath(__file__))
  343. App.log.debug("Application path is " + self.app_home)
  344. App.log.debug("Started in " + os.getcwd())
  345. # cx_freeze workaround
  346. if os.path.isfile(self.app_home):
  347. self.app_home = os.path.dirname(self.app_home)
  348. os.chdir(self.app_home)
  349. # ############################################################################################################
  350. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  351. # ############################################################################################################
  352. self.defaults = FlatCAMDefaults()
  353. self.defaults["root_folder_path"] = self.app_home
  354. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  355. if user_defaults:
  356. self.defaults.load(filename=current_defaults_path)
  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. if self.defaults["global_gray_icons"] is False:
  362. self.resource_location = 'assets/resources'
  363. else:
  364. self.resource_location = 'assets/resources/dark_resources'
  365. self.current_units = self.defaults['units']
  366. # ###########################################################################################################
  367. # #################################### SETUP OBJECT CLASSES #################################################
  368. # ###########################################################################################################
  369. self.setup_obj_classes()
  370. # ###########################################################################################################
  371. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  372. # ###########################################################################################################
  373. self.pool = Pool()
  374. # ###########################################################################################################
  375. # ###################################### Setting the Splash Screen ##########################################
  376. # ###########################################################################################################
  377. splash_settings = QSettings("Open Source", "FlatCAM")
  378. if splash_settings.contains("splash_screen"):
  379. show_splash = splash_settings.value("splash_screen")
  380. else:
  381. splash_settings.setValue('splash_screen', 1)
  382. # This will write the setting to the platform specific storage.
  383. del splash_settings
  384. show_splash = 1
  385. if show_splash and self.cmd_line_headless != 1:
  386. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  387. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  388. # self.splash.setMask(splash_pix.mask())
  389. # move splashscreen to the current monitor
  390. desktop = QtWidgets.QApplication.desktop()
  391. screen = desktop.screenNumber(QtGui.QCursor.pos())
  392. current_screen_center = desktop.availableGeometry(screen).center()
  393. self.splash.move(current_screen_center - self.splash.rect().center())
  394. self.splash.show()
  395. self.splash.showMessage(_("FlatCAM is initializing ..."),
  396. alignment=Qt.AlignBottom | Qt.AlignLeft,
  397. color=QtGui.QColor("gray"))
  398. else:
  399. show_splash = 0
  400. # ###########################################################################################################
  401. # ######################################### Initialize GUI ##################################################
  402. # ###########################################################################################################
  403. # FlatCAM colors used in plotting
  404. self.FC_light_green = '#BBF268BF'
  405. self.FC_dark_green = '#006E20BF'
  406. self.FC_light_blue = '#a5a5ffbf'
  407. self.FC_dark_blue = '#0000ffbf'
  408. QtCore.QObject.__init__(self)
  409. self.ui = FlatCAMGUI(self)
  410. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  411. if theme_settings.contains("theme"):
  412. theme = theme_settings.value('theme', type=str)
  413. else:
  414. theme = 'white'
  415. if self.defaults["global_cursor_color_enabled"]:
  416. self.cursor_color_3D = self.defaults["global_cursor_color"]
  417. else:
  418. if theme == 'white':
  419. self.cursor_color_3D = 'black'
  420. else:
  421. self.cursor_color_3D = 'gray'
  422. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  423. self.ui.final_save.connect(self.final_save)
  424. # restore the toolbar view
  425. self.restore_toolbar_view()
  426. # restore the GUI geometry
  427. self.restore_main_win_geom()
  428. # set FlatCAM units in the Status bar
  429. self.set_screen_units(self.defaults['units'])
  430. # ###########################################################################################################
  431. # ########################################### AUTOSAVE SETUP ################################################
  432. # ###########################################################################################################
  433. self.block_autosave = False
  434. self.autosave_timer = QtCore.QTimer(self)
  435. self.save_project_auto_update()
  436. self.autosave_timer.timeout.connect(self.save_project_auto)
  437. # ###########################################################################################################
  438. # #################################### LOAD PREPROCESSORS ###################################################
  439. # ###########################################################################################################
  440. # ----------------------------------------- WARNING --------------------------------------------------------
  441. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  442. # That's because the number of preprocessors can vary and here the comboboxes are populated
  443. # -----------------------------------------------------------------------------------------------------------
  444. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  445. # the preprocessor file
  446. self.preprocessors = load_preprocessors(self)
  447. # make sure that always the 'default' preprocessor is the first item in the dictionary
  448. if 'default' in self.preprocessors.keys():
  449. new_ppp_dict = {}
  450. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  451. default_pp = self.preprocessors.pop('default')
  452. new_ppp_dict['default'] = default_pp
  453. # then add the rest of the keys
  454. for name, val_class in self.preprocessors.items():
  455. new_ppp_dict[name] = val_class
  456. # and now put back the ordered dict with 'default' key first
  457. self.preprocessors = new_ppp_dict
  458. for name in list(self.preprocessors.keys()):
  459. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  460. if name.partition('_')[0] == 'Paste':
  461. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  462. continue
  463. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  464. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  465. if name == 'hpgl':
  466. continue
  467. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  468. # ###########################################################################################################
  469. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  470. # ###########################################################################################################
  471. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  472. inform=self.inform)
  473. self.preferencesUiManager.defaults_write_form()
  474. # When the self.defaults dictionary changes will update the Preferences GUI forms
  475. self.defaults.set_change_callback(self.on_defaults_dict_change)
  476. # ###########################################################################################################
  477. # ##################################### FIRST RUN SECTION ###################################################
  478. # ################################ It's done only once after install #####################################
  479. # ###########################################################################################################
  480. if self.defaults["first_run"] is True:
  481. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  482. initial_lay = 'minimal'
  483. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  484. # Set the combobox in Preferences to the current layout
  485. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  486. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  487. # after the first run, this object should be False
  488. self.defaults["first_run"] = False
  489. self.preferencesUiManager.save_defaults(silent=True)
  490. # ###########################################################################################################
  491. # ############################################ Data #########################################################
  492. # ###########################################################################################################
  493. self.recent = []
  494. self.recent_projects = []
  495. self.clipboard = QtWidgets.QApplication.clipboard()
  496. self.project_filename = None
  497. self.toggle_units_ignore = False
  498. # ###########################################################################################################
  499. # ########################################## LOAD LANGUAGES ################################################
  500. # ###########################################################################################################
  501. self.languages = fcTranslate.load_languages()
  502. for name in sorted(self.languages.values()):
  503. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  504. # ###########################################################################################################
  505. # ####################################### APPLY APP LANGUAGE ################################################
  506. # ###########################################################################################################
  507. ret_val = fcTranslate.apply_language('strings')
  508. if ret_val == "no language":
  509. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  510. log.debug("Could not find the Language files. The App strings are missing.")
  511. else:
  512. # make the current language the current selection on the language combobox
  513. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  514. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  515. # ###########################################################################################################
  516. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  517. # ###########################################################################################################
  518. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  519. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  520. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  521. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  522. self.defaults.propagate_defaults()
  523. # ###########################################################################################################
  524. # ######################################## UPDATE THE OPTIONS ###############################################
  525. # ###########################################################################################################
  526. self.options = LoudDict()
  527. # -----------------------------------------------------------------------------------------------------------
  528. # Update the self.options from the self.defaults
  529. # The self.defaults holds the application defaults while the self.options holds the object defaults
  530. # -----------------------------------------------------------------------------------------------------------
  531. # Copy app defaults to project options
  532. for def_key, def_val in self.defaults.items():
  533. self.options[def_key] = deepcopy(def_val)
  534. self.preferencesUiManager.show_preferences_gui()
  535. # ### End of Data ####
  536. # ###########################################################################################################
  537. # #################################### SETUP OBJECT COLLECTION ##############################################
  538. # ###########################################################################################################
  539. self.collection = ObjectCollection(self)
  540. self.ui.project_tab_layout.addWidget(self.collection.view)
  541. # ### Adjust tabs width ## ##
  542. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  543. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  544. self.collection.view.setMinimumWidth(290)
  545. self.log.debug("Finished creating Object Collection.")
  546. # ###########################################################################################################
  547. # ######################################## SETUP Plot Area ##################################################
  548. # ###########################################################################################################
  549. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  550. if self.defaults["global_graphic_engine"] == '3D':
  551. self.is_legacy = False
  552. else:
  553. self.is_legacy = True
  554. # Event signals disconnect id holders
  555. self.mp = None
  556. self.mm = None
  557. self.mr = None
  558. self.mdc = None
  559. self.mp_zc = None
  560. self.kp = None
  561. # Matplotlib axis
  562. self.axes = None
  563. if show_splash:
  564. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  565. "Canvas initialization started."),
  566. alignment=Qt.AlignBottom | Qt.AlignLeft,
  567. color=QtGui.QColor("gray"))
  568. start_plot_time = time.time() # debug
  569. self.plotcanvas = None
  570. self.app_cursor = None
  571. self.hover_shapes = None
  572. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  573. # setup the PlotCanvas
  574. self.on_plotcanvas_setup()
  575. end_plot_time = time.time()
  576. self.used_time = end_plot_time - start_plot_time
  577. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  578. if show_splash:
  579. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  580. "Canvas initialization started.\n"
  581. "Canvas initialization finished in"), '%.2f' % self.used_time),
  582. alignment=Qt.AlignBottom | Qt.AlignLeft,
  583. color=QtGui.QColor("gray"))
  584. self.ui.splitter.setStretchFactor(1, 2)
  585. # ###########################################################################################################
  586. # ############################################### SYS TRAY ##################################################
  587. # ###########################################################################################################
  588. if self.defaults["global_systray_icon"]:
  589. self.parent_w = QtWidgets.QWidget()
  590. if self.cmd_line_headless == 1:
  591. self.trayIcon = FlatCAMSystemTray(app=self,
  592. icon=QtGui.QIcon(self.resource_location +
  593. '/flatcam_icon32_green.png'),
  594. headless=True,
  595. parent=self.parent_w)
  596. else:
  597. self.trayIcon = FlatCAMSystemTray(app=self,
  598. icon=QtGui.QIcon(self.resource_location +
  599. '/flatcam_icon32_green.png'),
  600. parent=self.parent_w)
  601. # ###########################################################################################################
  602. # ############################################### Worker SETUP ##############################################
  603. # ###########################################################################################################
  604. if self.defaults["global_worker_number"]:
  605. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  606. else:
  607. self.workers = WorkerStack(workers_number=2)
  608. self.worker_task.connect(self.workers.add_task)
  609. self.log.debug("Finished creating Workers crew.")
  610. # ###########################################################################################################
  611. # ############################################# Activity Monitor ###########################################
  612. # ###########################################################################################################
  613. self.activity_view = FlatCAMActivityView(app=self)
  614. self.ui.infobar.addWidget(self.activity_view)
  615. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  616. # ###########################################################################################################
  617. # ############################################# Signal handling #############################################
  618. # ###########################################################################################################
  619. # ########################################## Custom signals ################################################
  620. # signal for displaying messages in status bar
  621. self.inform.connect(self.info)
  622. # signal to be called when the app is quiting
  623. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  624. self.message.connect(self.message_dialog)
  625. # self.progress.connect(self.set_progress_bar)
  626. # signals that are emitted when object state changes
  627. self.object_created.connect(self.on_object_created)
  628. self.object_changed.connect(self.on_object_changed)
  629. self.object_plotted.connect(self.on_object_plotted)
  630. self.plots_updated.connect(self.on_plots_updated)
  631. # signals emitted when file state change
  632. self.file_opened.connect(self.register_recent)
  633. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  634. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  635. # ########################################## Standard signals ###############################################
  636. # ### Menu
  637. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  638. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  639. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  640. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  641. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  642. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  643. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  644. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  645. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  646. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  647. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  648. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  649. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  650. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  651. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  652. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  653. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  654. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  655. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  656. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  657. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  658. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  659. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  660. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  661. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  662. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  663. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  664. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  665. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  666. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  667. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  668. self.ui.menufile_exit.triggered.connect(self.final_save)
  669. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  670. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  671. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  672. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  673. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  674. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  675. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  676. self.ui.menueditdelete.triggered.connect(self.on_delete)
  677. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  678. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  679. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  680. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  681. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  682. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  683. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  684. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  685. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  686. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  687. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  688. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  689. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  690. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  691. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  692. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  693. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  694. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  695. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  696. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  697. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  698. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  699. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  700. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  701. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  702. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  703. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  704. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  705. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  706. self.ui.menuview_replot.triggered.connect(self.plot_all)
  707. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  708. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  709. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  710. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  711. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  712. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  713. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  714. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  715. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  716. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  717. self.ui.menuhelp_about.triggered.connect(self.on_about)
  718. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  719. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  720. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  721. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  722. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  723. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  724. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  725. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  726. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  727. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  728. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  729. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  730. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  731. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  732. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  733. # ToolBar signals
  734. self.connect_toolbar_signals()
  735. # Notebook and Plot Tab Area signals
  736. # make the right click on the notebook tab and plot tab area tab raise a menu
  737. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  738. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  739. self.on_tab_setup_context_menu()
  740. # activate initial state
  741. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  742. # Context Menu
  743. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  744. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  745. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  746. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  747. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  748. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  749. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  750. self.ui.clearplot.triggered.connect(self.clear_plots)
  751. self.ui.replot.triggered.connect(self.plot_all)
  752. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  753. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  754. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  755. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  756. self.ui.popmenu_move.triggered.connect(self.obj_move)
  757. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  758. # Project Context Menu -> Color Setting
  759. for act in self.ui.menuprojectcolor.actions():
  760. act.triggered.connect(self.on_set_color_action_triggered)
  761. # ###########################################################################################################
  762. # #################################### GUI PREFERENCES SIGNALS ##############################################
  763. # ###########################################################################################################
  764. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  765. lambda: self.on_toggle_units(no_pref=False))
  766. # ##################################### Workspace Setting Signals ###########################################
  767. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  768. self.on_workspace_modified)
  769. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  770. self.on_workspace_modified
  771. )
  772. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  773. # ###########################################################################################################
  774. # ######################################## GUI SETTINGS SIGNALS #############################################
  775. # ###########################################################################################################
  776. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  777. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  778. # ######################################## Tools related signals ############################################
  779. # Film Tool
  780. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  781. self.on_film_color_entry)
  782. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  783. self.on_film_color_button)
  784. # QRCode Tool
  785. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  786. self.on_qrcode_fill_color_entry)
  787. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  788. self.on_qrcode_fill_color_button)
  789. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  790. self.on_qrcode_back_color_entry)
  791. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  792. self.on_qrcode_back_color_button)
  793. # portability changed signal
  794. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  795. # Object list
  796. self.collection.view.activated.connect(self.on_row_activated)
  797. self.collection.item_selected.connect(self.on_row_selected)
  798. self.object_status_changed.connect(self.on_collection_updated)
  799. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  800. # Export Excellon parameters.
  801. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  802. self.on_update_exc_export
  803. )
  804. # call it once to make sure it is updated at startup
  805. self.on_update_exc_export(state=self.defaults["excellon_update"])
  806. # when there are arguments at application startup this get launched
  807. self.args_at_startup[list].connect(self.on_startup_args)
  808. # ###########################################################################################################
  809. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  810. # ###########################################################################################################
  811. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  812. lambda: self.restore_extensions(ext_type='excellon'))
  813. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  814. lambda: self.restore_extensions(ext_type='gcode'))
  815. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  816. lambda: self.restore_extensions(ext_type='gerber'))
  817. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  818. lambda: self.delete_all_extensions(ext_type='excellon'))
  819. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  820. lambda: self.delete_all_extensions(ext_type='gcode'))
  821. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  822. lambda: self.delete_all_extensions(ext_type='gerber'))
  823. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  824. lambda: self.add_extension(ext_type='excellon'))
  825. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  826. lambda: self.add_extension(ext_type='gcode'))
  827. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  828. lambda: self.add_extension(ext_type='gerber'))
  829. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  830. lambda: self.del_extension(ext_type='excellon'))
  831. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  832. lambda: self.del_extension(ext_type='gcode'))
  833. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  834. lambda: self.del_extension(ext_type='gerber'))
  835. # connect the 'Apply' buttons from the Preferences/File Associations
  836. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  837. lambda: self.on_register_files(obj_type='excellon'))
  838. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  839. lambda: self.on_register_files(obj_type='gcode'))
  840. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  841. lambda: self.on_register_files(obj_type='gerber'))
  842. # ###########################################################################################################
  843. # ########################################### KEYWORDS SIGNALS ##############################################
  844. # ###########################################################################################################
  845. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  846. lambda: self.restore_extensions(ext_type='keyword'))
  847. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  848. lambda: self.delete_all_extensions(ext_type='keyword'))
  849. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  850. lambda: self.add_extension(ext_type='keyword'))
  851. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  852. lambda: self.del_extension(ext_type='keyword'))
  853. # connect the abort_all_tasks related slots to the related signals
  854. self.proc_container.idle_flag.connect(self.app_is_idle)
  855. # signal emitted when a tab is closed in the Plot Area
  856. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  857. # signal to close the application
  858. self.close_app_signal.connect(self.kill_app)
  859. # ################################# FINISHED CONNECTING SIGNALS #############################################
  860. # ###########################################################################################################
  861. # ###########################################################################################################
  862. # ###########################################################################################################
  863. self.log.debug("Finished connecting Signals.")
  864. # ###########################################################################################################
  865. # ########################################## Other setups ###################################################
  866. # ###########################################################################################################
  867. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  868. # depending on from where those tools are called different actions can be done
  869. self.call_source = 'app'
  870. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  871. self.tool_tab_locked = False
  872. # decide if to show or hide the Notebook side of the screen at startup
  873. if self.defaults["global_project_at_startup"] is True:
  874. self.ui.splitter.setSizes([1, 1])
  875. else:
  876. self.ui.splitter.setSizes([0, 1])
  877. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  878. self.setup_component_editor()
  879. # ###########################################################################################################
  880. # ####################################### Auto-complete KEYWORDS ############################################
  881. # ###########################################################################################################
  882. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  883. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  884. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  885. 'export_exc',
  886. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  887. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  888. 'interiors', 'isolate', 'join_excellon',
  889. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  890. 'mirror', 'ncc',
  891. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  892. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  893. 'options', 'origin',
  894. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  895. 'save', 'save_project',
  896. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  897. 'skew', 'subtract_poly', 'subtract_rectangle',
  898. 'version', 'write_gcode'
  899. ]
  900. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  901. 'Paste_1',
  902. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  903. 'Toolchange_manual', 'True', 'Users',
  904. 'all', 'auto', 'axis',
  905. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  906. 'contour', 'default',
  907. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  908. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  909. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  910. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  911. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  912. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  913. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  914. 'spacing_columns',
  915. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  916. 'toolchange_xy', 'toolchangez', 'travelz',
  917. 'tooldia', 'use_threads', 'value',
  918. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  919. ]
  920. self.tcl_keywords = [
  921. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  922. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  923. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  924. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  925. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  926. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  927. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  928. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  929. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  930. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  931. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  932. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  933. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  934. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  935. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  936. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  937. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  938. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  939. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  940. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  941. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  942. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  943. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  944. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  945. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  946. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  947. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  948. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  949. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  950. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  951. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  952. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  953. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  954. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  955. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  956. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  957. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  958. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  959. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  960. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  961. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  962. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  963. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  964. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  965. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  966. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  967. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  968. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  969. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  970. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  971. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  972. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  973. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  974. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  975. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  976. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  977. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  978. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  979. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  980. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  981. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  982. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  983. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  984. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  985. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  986. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  987. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  988. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  989. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  990. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  991. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  992. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  993. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  994. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  995. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  996. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  997. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  998. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  999. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1000. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1001. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1002. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1003. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1004. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1005. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1006. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1007. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1008. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1009. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1010. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1011. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1012. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1013. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1014. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1015. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1016. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1017. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1018. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1019. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1020. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1021. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1022. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1023. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1024. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1025. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1026. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1027. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1028. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1029. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1030. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1031. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1032. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1033. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1034. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1035. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1036. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1037. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1038. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1039. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1040. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1041. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1042. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1043. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1044. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1045. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1046. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1047. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1048. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1049. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1050. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1051. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1052. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1053. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1054. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1055. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1056. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1057. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1058. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1059. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1060. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1061. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1062. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1063. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1064. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1065. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1066. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1067. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1068. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1069. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1070. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1071. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1072. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1073. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1074. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1075. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1076. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1077. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1078. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1079. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1080. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1081. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1082. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1083. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1084. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1085. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1086. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1087. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1088. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1089. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1090. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1091. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1092. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1093. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1094. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1095. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1096. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1097. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1098. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1099. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1100. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1101. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1102. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1103. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1104. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1105. ]
  1106. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1107. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1108. # ###########################################################################################################
  1109. # ############################################## Shell SETUP ################################################
  1110. # ###########################################################################################################
  1111. self.shell = FCShell(app=self, version=self.version)
  1112. self.ui.shell_dock.setWidget(self.shell)
  1113. self.log.debug("TCL Shell has been initialized.")
  1114. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1115. if self.defaults["global_shell_at_startup"]:
  1116. self.ui.shell_dock.show()
  1117. else:
  1118. self.ui.shell_dock.hide()
  1119. # ###########################################################################################################
  1120. # ########################################## Tools and Plugins ##############################################
  1121. # ###########################################################################################################
  1122. self.dblsidedtool = None
  1123. self.distance_tool = None
  1124. self.distance_min_tool = None
  1125. self.panelize_tool = None
  1126. self.film_tool = None
  1127. self.paste_tool = None
  1128. self.calculator_tool = None
  1129. self.rules_tool = None
  1130. self.sub_tool = None
  1131. self.move_tool = None
  1132. self.cutout_tool = None
  1133. self.ncclear_tool = None
  1134. self.optimal_tool = None
  1135. self.paint_tool = None
  1136. self.transform_tool = None
  1137. self.properties_tool = None
  1138. self.pdf_tool = None
  1139. self.image_tool = None
  1140. self.pcb_wizard_tool = None
  1141. self.cal_exc_tool = None
  1142. self.qrcode_tool = None
  1143. self.copper_thieving_tool = None
  1144. self.fiducial_tool = None
  1145. self.edrills_tool = None
  1146. self.align_objects_tool = None
  1147. self.punch_tool = None
  1148. self.invert_tool = None
  1149. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1150. try:
  1151. self.install_tools()
  1152. except AttributeError as e:
  1153. log.debug("App.__init__() install tools() --> %s" % str(e))
  1154. # ###########################################################################################################
  1155. # ############################################ SETUP RECENT ITEMS ###########################################
  1156. # ###########################################################################################################
  1157. self.setup_recent_items()
  1158. # ###########################################################################################################
  1159. # ######################################### BookMarks Manager ###############################################
  1160. # ###########################################################################################################
  1161. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1162. self.install_bookmarks()
  1163. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1164. # ###########################################################################################################
  1165. # ########################################### Tools Database ################################################
  1166. # ###########################################################################################################
  1167. self.tools_db_tab = None
  1168. # ### System Font Parsing ###
  1169. # self.f_parse = ParseFont(self)
  1170. # self.parse_system_fonts()
  1171. # ###########################################################################################################
  1172. # ######################################### Check for updates ###############################################
  1173. # ###########################################################################################################
  1174. # Separate thread (Not worker)
  1175. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1176. if (self.beta is False or self.beta is None) and \
  1177. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1178. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1179. # self.thr2 = QtCore.QThread()
  1180. self.worker_task.emit({'fcn': self.version_check,
  1181. 'params': []})
  1182. # self.thr2.start(QtCore.QThread.LowPriority)
  1183. # ###########################################################################################################
  1184. # ##################################### Register files with FlatCAM; #######################################
  1185. # ################################### It works only for Windows for now ####################################
  1186. # ###########################################################################################################
  1187. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1188. self.on_register_files()
  1189. # ###########################################################################################################
  1190. # ######################################## Variables for global usage #######################################
  1191. # ###########################################################################################################
  1192. # hold the App units
  1193. self.units = 'MM'
  1194. # coordinates for relative position display
  1195. self.rel_point1 = (0, 0)
  1196. self.rel_point2 = (0, 0)
  1197. # variable to store coordinates
  1198. self.pos = (0, 0)
  1199. self.pos_canvas = (0, 0)
  1200. self.pos_jump = (0, 0)
  1201. # variable to store mouse coordinates
  1202. self.mouse = [0, 0]
  1203. # variable to store the delta positions on cavnas
  1204. self.dx = 0
  1205. self.dy = 0
  1206. # decide if we have a double click or single click
  1207. self.doubleclick = False
  1208. # store here the is_dragging value
  1209. self.event_is_dragging = False
  1210. # variable to store if a command is active (then the var is not None) and which one it is
  1211. self.command_active = None
  1212. # variable to store the status of moving selection action
  1213. # None value means that it's not an selection action
  1214. # True value = a selection from left to right
  1215. # False value = a selection from right to left
  1216. self.selection_type = None
  1217. # List to store the objects that are currently loaded in FlatCAM
  1218. # This list is updated on each object creation or object delete
  1219. self.all_objects_list = []
  1220. self.objects_under_the_click_list = []
  1221. # List to store the objects that are selected
  1222. self.sel_objects_list = []
  1223. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1224. self.key_modifiers = None
  1225. # Variable to hold the status of the axis
  1226. self.toggle_axis = True
  1227. # Variable to hold the status of the grid lines
  1228. self.toggle_grid_lines = True
  1229. # Variable to store the status of the fullscreen event
  1230. self.toggle_fscreen = False
  1231. # Variable to store the status of the code editor
  1232. self.toggle_codeeditor = False
  1233. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1234. self.click_noproject = False
  1235. self.cursor = None
  1236. # Variable to store the GCODE that was edited
  1237. self.gcode_edited = ""
  1238. self.text_editor_tab = None
  1239. # reference for the self.ui.code_editor
  1240. self.reference_code_editor = None
  1241. self.script_code = ''
  1242. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1243. self.tools_db_changed_flag = False
  1244. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1245. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1246. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1247. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1248. 'tsm']
  1249. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1250. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1251. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1252. 'sbp', 'tap', 'xpi']
  1253. self.svg_list = ['svg']
  1254. self.dxf_list = ['dxf']
  1255. self.pdf_list = ['pdf']
  1256. self.prj_list = ['flatprj']
  1257. self.conf_list = ['flatconfig']
  1258. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1259. # flag for polygons not cleared
  1260. self.poly_not_cleared = False
  1261. # VisPy visuals
  1262. self.isHovering = False
  1263. self.notHovering = True
  1264. # Window geometry
  1265. self.x_pos = None
  1266. self.y_pos = None
  1267. self.width = None
  1268. self.height = None
  1269. # when True, the app has to return from any thread
  1270. self.abort_flag = False
  1271. # set the value used in the Windows Title
  1272. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1273. # this holds a widget that is installed in the Plot Area when View Source option is used
  1274. self.source_editor_tab = None
  1275. self.pagesize = {}
  1276. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1277. # VisPy visuals
  1278. if self.is_legacy is False:
  1279. try:
  1280. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1281. except AttributeError:
  1282. self.tool_shapes = None
  1283. else:
  1284. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1285. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1286. # used in the delayed shutdown self.start_delayed_quit() method
  1287. self.save_timer = None
  1288. # ###########################################################################################################
  1289. # ################################## ADDING FlatCAM EDITORS section #########################################
  1290. # ###########################################################################################################
  1291. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1292. # at the first launch of the App , the editors will not be functional.
  1293. try:
  1294. self.geo_editor = FlatCAMGeoEditor(self)
  1295. except AttributeError:
  1296. pass
  1297. try:
  1298. self.exc_editor = FlatCAMExcEditor(self)
  1299. except AttributeError:
  1300. pass
  1301. try:
  1302. self.grb_editor = FlatCAMGrbEditor(self)
  1303. except AttributeError:
  1304. pass
  1305. self.log.debug("Finished adding FlatCAM Editor's.")
  1306. self.set_ui_title(name=_("New Project - Not saved"))
  1307. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1308. current_platform = platform.architecture()[0]
  1309. if current_platform != '64bit':
  1310. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1311. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1312. # ###########################################################################################################
  1313. # ########################################### EXCLUSION AREAS ###############################################
  1314. # ###########################################################################################################
  1315. self.exc_areas = ExclusionAreas(app=self)
  1316. # ###########################################################################################################
  1317. # ##################################### Finished the CONSTRUCTOR ############################################
  1318. # ###########################################################################################################
  1319. App.log.debug("END of constructor. Releasing control.")
  1320. # ###########################################################################################################
  1321. # ########################################## SHOW GUI #######################################################
  1322. # ###########################################################################################################
  1323. # if the app is not started as headless, show it
  1324. if self.cmd_line_headless != 1:
  1325. if show_splash:
  1326. # finish the splash
  1327. self.splash.finish(self.ui)
  1328. mgui_settings = QSettings("Open Source", "FlatCAM")
  1329. if mgui_settings.contains("maximized_gui"):
  1330. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1331. if maximized_ui is True:
  1332. self.ui.showMaximized()
  1333. else:
  1334. self.ui.show()
  1335. else:
  1336. self.ui.show()
  1337. if self.defaults["global_systray_icon"]:
  1338. self.trayIcon.show()
  1339. else:
  1340. log.warning("******************* RUNNING HEADLESS *******************")
  1341. # ###########################################################################################################
  1342. # ######################################## START-UP ARGUMENTS ###############################################
  1343. # ###########################################################################################################
  1344. # test if the program was started with a script as parameter
  1345. if self.cmd_line_shellvar:
  1346. try:
  1347. cnt = 0
  1348. command_tcl = 0
  1349. for i in self.cmd_line_shellvar.split(','):
  1350. if i is not None:
  1351. # noinspection PyBroadException
  1352. try:
  1353. command_tcl = eval(i)
  1354. except Exception:
  1355. command_tcl = i
  1356. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1357. cnt += 1
  1358. # if there are Windows paths then replace the path separator with a Unix like one
  1359. if sys.platform == 'win32':
  1360. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1361. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1362. except Exception as ext:
  1363. print("ERROR: ", ext)
  1364. sys.exit(2)
  1365. if self.cmd_line_shellfile:
  1366. if self.cmd_line_headless != 1:
  1367. if self.ui.shell_dock.isHidden():
  1368. self.ui.shell_dock.show()
  1369. try:
  1370. with open(self.cmd_line_shellfile, "r") as myfile:
  1371. # if show_splash:
  1372. # self.splash.showMessage('%s: %ssec\n%s' % (
  1373. # _("Canvas initialization started.\n"
  1374. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1375. # _("Executing Tcl Script ...")),
  1376. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1377. # color=QtGui.QColor("gray"))
  1378. cmd_line_shellfile_text = myfile.read()
  1379. if self.cmd_line_headless != 1:
  1380. self.shell.exec_command(cmd_line_shellfile_text)
  1381. else:
  1382. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1383. except Exception as ext:
  1384. print("ERROR: ", ext)
  1385. sys.exit(2)
  1386. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1387. # the path/file_name must be enclosed in quotes if it contain spaces
  1388. if App.args:
  1389. self.args_at_startup.emit(App.args)
  1390. if self.defaults.old_defaults_found is True:
  1391. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1392. "Please reboot the application to update."))
  1393. self.defaults.old_defaults_found = False
  1394. # ######################################### INIT FINISHED #######################################################
  1395. # #################################################################################################################
  1396. # #################################################################################################################
  1397. # #################################################################################################################
  1398. # #################################################################################################################
  1399. # #################################################################################################################
  1400. @staticmethod
  1401. def copy_and_overwrite(from_path, to_path):
  1402. """
  1403. From here:
  1404. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1405. :param from_path: source path
  1406. :param to_path: destination path
  1407. :return: None
  1408. """
  1409. if os.path.exists(to_path):
  1410. shutil.rmtree(to_path)
  1411. try:
  1412. shutil.copytree(from_path, to_path)
  1413. except FileNotFoundError:
  1414. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1415. shutil.copytree(from_new_path, to_path)
  1416. def on_startup_args(self, args, silent=False):
  1417. """
  1418. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1419. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1420. :param args: a list containing the application args at startup
  1421. :return: None
  1422. """
  1423. if args is not None:
  1424. args_to_process = args
  1425. else:
  1426. args_to_process = App.args
  1427. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1428. for argument in args_to_process:
  1429. if '.FlatPrj'.lower() in argument.lower():
  1430. try:
  1431. project_name = str(argument)
  1432. if project_name == "":
  1433. if silent is False:
  1434. self.inform.emit(_("Cancelled."))
  1435. else:
  1436. # self.open_project(project_name)
  1437. run_from_arg = True
  1438. # self.worker_task.emit({'fcn': self.open_project,
  1439. # 'params': [project_name, run_from_arg]})
  1440. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1441. except Exception as e:
  1442. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1443. elif '.FlatConfig'.lower() in argument.lower():
  1444. try:
  1445. file_name = str(argument)
  1446. if file_name == "":
  1447. if silent is False:
  1448. self.inform.emit(_("Open Config file failed."))
  1449. else:
  1450. run_from_arg = True
  1451. # self.worker_task.emit({'fcn': self.open_config_file,
  1452. # 'params': [file_name, run_from_arg]})
  1453. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1454. except Exception as e:
  1455. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1456. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1457. try:
  1458. file_name = str(argument)
  1459. if file_name == "":
  1460. if silent is False:
  1461. self.inform.emit(_("Open Script file failed."))
  1462. else:
  1463. if silent is False:
  1464. self.on_fileopenscript(name=file_name)
  1465. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1466. self.on_filerunscript(name=file_name)
  1467. except Exception as e:
  1468. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1469. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1470. log.debug("App.on_startup_args() --> Quit event.")
  1471. sys.exit()
  1472. elif 'save'.lower() in argument.lower():
  1473. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1474. self.preferencesUiManager.save_defaults()
  1475. else:
  1476. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1477. proc_arg = argument.lower()
  1478. for ext in exc_list:
  1479. proc_ext = ext.replace(' ', '')
  1480. proc_ext = '.%s' % proc_ext
  1481. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1482. file_name = str(argument)
  1483. if file_name == "":
  1484. if silent is False:
  1485. self.inform.emit(_("Open Excellon file failed."))
  1486. else:
  1487. self.on_fileopenexcellon(name=file_name, signal=None)
  1488. return
  1489. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1490. for ext in gco_list:
  1491. proc_ext = ext.replace(' ', '')
  1492. proc_ext = '.%s' % proc_ext
  1493. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1494. file_name = str(argument)
  1495. if file_name == "":
  1496. if silent is False:
  1497. self.inform.emit(_("Open GCode file failed."))
  1498. else:
  1499. self.on_fileopengcode(name=file_name, signal=None)
  1500. return
  1501. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1502. for ext in grb_list:
  1503. proc_ext = ext.replace(' ', '')
  1504. proc_ext = '.%s' % proc_ext
  1505. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1506. file_name = str(argument)
  1507. if file_name == "":
  1508. if silent is False:
  1509. self.inform.emit(_("Open Gerber file failed."))
  1510. else:
  1511. self.on_fileopengerber(name=file_name, signal=None)
  1512. return
  1513. # if it reached here without already returning then the app was registered with a file that it does not
  1514. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1515. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1516. # for arg in args_to_process:
  1517. # if 'FlatCAM.exe' in arg:
  1518. # continue
  1519. # else:
  1520. # sys.exit(2)
  1521. def set_ui_title(self, name):
  1522. """
  1523. Sets the title of the main window.
  1524. :param name: String that store the project path and project name
  1525. :return: None
  1526. """
  1527. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1528. (self.version,
  1529. ('BETA' if self.beta else ''),
  1530. platform.architecture()[0],
  1531. self.engine,
  1532. name)
  1533. )
  1534. def on_app_restart(self):
  1535. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1536. # be left in the SySTray
  1537. try:
  1538. self.trayIcon.hide()
  1539. except Exception:
  1540. pass
  1541. fcTranslate.restart_program(app=self)
  1542. def clear_pool(self):
  1543. """
  1544. Clear the multiprocessing pool and calls garbage collector.
  1545. :return: None
  1546. """
  1547. self.pool.close()
  1548. self.pool = Pool()
  1549. self.pool_recreated.emit(self.pool)
  1550. gc.collect()
  1551. def install_tools(self):
  1552. """
  1553. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1554. Instantiation of the Tools classes.
  1555. The order that the tools are installed is important as they can depend on each other install position.
  1556. :return: None
  1557. """
  1558. self.distance_tool = Distance(self)
  1559. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1560. before=self.ui.menueditorigin,
  1561. separator=False)
  1562. self.distance_min_tool = DistanceMin(self)
  1563. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1564. pos=self.ui.menuedit,
  1565. before=self.ui.menueditorigin,
  1566. separator=True)
  1567. self.dblsidedtool = DblSidedTool(self)
  1568. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1569. self.cal_exc_tool = ToolCalibration(self)
  1570. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1571. before=self.dblsidedtool.menuAction,
  1572. separator=False)
  1573. self.align_objects_tool = AlignObjects(self)
  1574. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1575. self.edrills_tool = ToolExtractDrills(self)
  1576. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1577. self.panelize_tool = Panelize(self)
  1578. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1579. self.film_tool = Film(self)
  1580. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1581. self.paste_tool = SolderPaste(self)
  1582. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1583. self.calculator_tool = ToolCalculator(self)
  1584. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1585. self.sub_tool = ToolSub(self)
  1586. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1587. pos=self.ui.menutool, separator=True)
  1588. self.rules_tool = RulesCheck(self)
  1589. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1590. pos=self.ui.menutool, separator=False)
  1591. self.optimal_tool = ToolOptimal(self)
  1592. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1593. pos=self.ui.menutool, separator=True)
  1594. self.move_tool = ToolMove(self)
  1595. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1596. before=self.ui.menueditorigin, separator=True)
  1597. self.cutout_tool = CutOut(self)
  1598. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1599. before=self.sub_tool.menuAction)
  1600. self.ncclear_tool = NonCopperClear(self)
  1601. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1602. before=self.sub_tool.menuAction, separator=True)
  1603. self.paint_tool = ToolPaint(self)
  1604. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1605. before=self.sub_tool.menuAction, separator=True)
  1606. self.copper_thieving_tool = ToolCopperThieving(self)
  1607. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1608. pos=self.ui.menutool)
  1609. self.fiducial_tool = ToolFiducials(self)
  1610. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1611. pos=self.ui.menutool)
  1612. self.qrcode_tool = QRCode(self)
  1613. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1614. pos=self.ui.menutool)
  1615. self.punch_tool = ToolPunchGerber(self)
  1616. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1617. self.invert_tool = ToolInvertGerber(self)
  1618. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1619. self.transform_tool = ToolTransform(self)
  1620. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1621. pos=self.ui.menuoptions, separator=True)
  1622. self.properties_tool = Properties(self)
  1623. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1624. pos=self.ui.menuoptions)
  1625. self.pdf_tool = ToolPDF(self)
  1626. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1627. pos=self.ui.menufileimport,
  1628. separator=True)
  1629. self.image_tool = ToolImage(self)
  1630. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1631. pos=self.ui.menufileimport,
  1632. separator=True)
  1633. self.pcb_wizard_tool = PcbWizard(self)
  1634. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1635. pos=self.ui.menufileimport)
  1636. self.log.debug("Tools are installed.")
  1637. def remove_tools(self):
  1638. """
  1639. Will remove all the actions in the Tool menu.
  1640. :return: None
  1641. """
  1642. for act in self.ui.menutool.actions():
  1643. self.ui.menutool.removeAction(act)
  1644. def init_tools(self):
  1645. """
  1646. Initialize the Tool tab in the notebook side of the central widget.
  1647. Remove the actions in the Tools menu.
  1648. Instantiate again the FlatCAM tools (plugins).
  1649. All this is required when changing the layout: standard, compact etc.
  1650. :return: None
  1651. """
  1652. log.debug("init_tools()")
  1653. # delete the data currently in the Tools Tab and the Tab itself
  1654. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1655. if widget is not None:
  1656. widget.deleteLater()
  1657. self.ui.notebook.removeTab(2)
  1658. # rebuild the Tools Tab
  1659. self.ui.tool_tab = QtWidgets.QWidget()
  1660. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1661. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1662. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1663. self.ui.tool_scroll_area = VerticalScrollArea()
  1664. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1665. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1666. # first remove all of them
  1667. self.remove_tools()
  1668. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1669. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1670. '&Command Line\tS')
  1671. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1672. # third install all of them
  1673. try:
  1674. self.install_tools()
  1675. except AttributeError:
  1676. pass
  1677. self.log.debug("Tools are initialized.")
  1678. # def parse_system_fonts(self):
  1679. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1680. # 'params': []})
  1681. def connect_toolbar_signals(self):
  1682. """
  1683. Reconnect the signals to the actions in the toolbar.
  1684. This has to be done each time after the FlatCAM tools are removed/installed.
  1685. :return: None
  1686. """
  1687. # Toolbar
  1688. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1689. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1690. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1691. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1692. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1693. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1694. self.ui.replot_btn.triggered.connect(self.plot_all)
  1695. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1696. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1697. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1698. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1699. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1700. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1701. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1702. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1703. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1704. self.ui.delete_btn.triggered.connect(self.on_delete)
  1705. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1706. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1707. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1708. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1709. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1710. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1711. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1712. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1713. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1714. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1715. # Tools Toolbar Signals
  1716. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1717. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1718. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1719. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1720. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1721. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1722. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1723. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1724. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1725. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1726. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1727. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1728. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1729. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1730. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1731. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1732. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1733. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1734. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1735. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1736. def object2editor(self):
  1737. """
  1738. Send the current Geometry or Excellon object (if any) into the it's editor.
  1739. :return: None
  1740. """
  1741. self.defaults.report_usage("object2editor()")
  1742. # disable the objects menu as it may interfere with the Editors
  1743. self.ui.menuobjects.setDisabled(True)
  1744. edited_object = self.collection.get_active()
  1745. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1746. isinstance(edited_object, ExcellonObject):
  1747. pass
  1748. else:
  1749. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1750. return
  1751. if isinstance(edited_object, GeometryObject):
  1752. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1753. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1754. # we set the notebook to hidden
  1755. # self.ui.splitter.setSizes([0, 1])
  1756. if edited_object.multigeo is True:
  1757. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1758. if len(sel_rows) > 1:
  1759. self.inform.emit('[WARNING_NOTCL] %s' %
  1760. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1761. "is not possible.\n"
  1762. "Edit only one geometry at a time."))
  1763. # determine the tool dia of the selected tool
  1764. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1765. # now find the key in the edited_object.tools that has this tooldia
  1766. multi_tool = 1
  1767. for tool in edited_object.tools:
  1768. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1769. multi_tool = tool
  1770. break
  1771. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1772. else:
  1773. self.geo_editor.edit_fcgeometry(edited_object)
  1774. # set call source to the Editor we go into
  1775. self.call_source = 'geo_editor'
  1776. elif isinstance(edited_object, ExcellonObject):
  1777. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1778. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1779. if self.ui.splitter.sizes()[0] == 0:
  1780. self.ui.splitter.setSizes([1, 1])
  1781. self.exc_editor.edit_fcexcellon(edited_object)
  1782. # set call source to the Editor we go into
  1783. self.call_source = 'exc_editor'
  1784. elif isinstance(edited_object, GerberObject):
  1785. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1786. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1787. if self.ui.splitter.sizes()[0] == 0:
  1788. self.ui.splitter.setSizes([1, 1])
  1789. self.grb_editor.edit_fcgerber(edited_object)
  1790. # set call source to the Editor we go into
  1791. self.call_source = 'grb_editor'
  1792. # reset the following variables so the UI is built again after edit
  1793. edited_object.ui_build = False
  1794. edited_object.build_aperture_storage = False
  1795. # make sure that we can't select another object while in Editor Mode:
  1796. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1797. self.ui.project_frame.setDisabled(True)
  1798. # delete any selection shape that might be active as they are not relevant in Editor
  1799. self.delete_selection_shape()
  1800. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1801. self.ui.plot_tab_area.protectTab(0)
  1802. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1803. self.should_we_save = True
  1804. def editor2object(self, cleanup=None):
  1805. """
  1806. Transfers the Geometry or Excellon from it's editor to the current object.
  1807. :return: None
  1808. """
  1809. self.defaults.report_usage("editor2object()")
  1810. # re-enable the objects menu that was disabled on entry in Editor mode
  1811. self.ui.menuobjects.setDisabled(False)
  1812. # do not update a geometry or excellon object unless it comes out of an editor
  1813. if self.call_source != 'app':
  1814. edited_obj = self.collection.get_active()
  1815. if cleanup is None:
  1816. msgbox = QtWidgets.QMessageBox()
  1817. msgbox.setText(_("Do you want to save the edited object?"))
  1818. msgbox.setWindowTitle(_("Close Editor"))
  1819. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1820. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1821. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1822. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1823. msgbox.setDefaultButton(bt_yes)
  1824. msgbox.exec_()
  1825. response = msgbox.clickedButton()
  1826. if response == bt_yes:
  1827. # clean the Tools Tab
  1828. self.ui.tool_scroll_area.takeWidget()
  1829. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1830. self.ui.notebook.setTabText(2, "Tool")
  1831. if isinstance(edited_obj, GeometryObject):
  1832. obj_type = "Geometry"
  1833. if cleanup is None:
  1834. self.geo_editor.update_fcgeometry(edited_obj)
  1835. # self.geo_editor.update_options(edited_obj)
  1836. self.geo_editor.deactivate()
  1837. # restore GUI to the Selected TAB
  1838. # Remove anything else in the GUI
  1839. self.ui.tool_scroll_area.takeWidget()
  1840. # update the geo object options so it is including the bounding box values
  1841. try:
  1842. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1843. edited_obj.options['xmin'] = xmin
  1844. edited_obj.options['ymin'] = ymin
  1845. edited_obj.options['xmax'] = xmax
  1846. edited_obj.options['ymax'] = ymax
  1847. except AttributeError as e:
  1848. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1849. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1850. edited_obj.build_ui()
  1851. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1852. elif isinstance(edited_obj, GerberObject):
  1853. obj_type = "Gerber"
  1854. if cleanup is None:
  1855. self.grb_editor.update_fcgerber()
  1856. self.grb_editor.update_options(edited_obj)
  1857. self.grb_editor.deactivate_grb_editor()
  1858. # delete the old object (the source object) if it was an empty one
  1859. try:
  1860. if len(edited_obj.solid_geometry) == 0:
  1861. old_name = edited_obj.options['name']
  1862. self.collection.set_active(old_name)
  1863. self.collection.delete_active()
  1864. except TypeError:
  1865. # if the solid_geometry is a single Polygon the len() will not work
  1866. # in any case, falling here means that we have something in the solid_geometry, even if only
  1867. # a single Polygon, therefore we pass this
  1868. pass
  1869. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1870. # restore GUI to the Selected TAB
  1871. # Remove anything else in the GUI
  1872. self.ui.selected_scroll_area.takeWidget()
  1873. elif isinstance(edited_obj, ExcellonObject):
  1874. obj_type = "Excellon"
  1875. if cleanup is None:
  1876. self.exc_editor.update_fcexcellon(edited_obj)
  1877. # self.exc_editor.update_options(edited_obj)
  1878. self.exc_editor.deactivate()
  1879. # restore GUI to the Selected TAB
  1880. # Remove anything else in the GUI
  1881. self.ui.tool_scroll_area.takeWidget()
  1882. # delete the old object (the source object) if it was an empty one
  1883. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1884. old_name = edited_obj.options['name']
  1885. self.collection.delete_by_name(name=old_name)
  1886. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1887. else:
  1888. self.inform.emit('[WARNING_NOTCL] %s' %
  1889. _("Select a Gerber, Geometry or Excellon Object to update."))
  1890. return
  1891. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1892. elif response == bt_no:
  1893. # clean the Tools Tab
  1894. self.ui.tool_scroll_area.takeWidget()
  1895. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1896. self.ui.notebook.setTabText(2, "Tool")
  1897. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1898. if isinstance(edited_obj, GeometryObject):
  1899. self.geo_editor.deactivate()
  1900. edited_obj.build_ui()
  1901. elif isinstance(edited_obj, GerberObject):
  1902. self.grb_editor.deactivate_grb_editor()
  1903. edited_obj.build_ui()
  1904. elif isinstance(edited_obj, ExcellonObject):
  1905. self.exc_editor.deactivate()
  1906. edited_obj.build_ui()
  1907. else:
  1908. self.inform.emit('[WARNING_NOTCL] %s' %
  1909. _("Select a Gerber, Geometry or Excellon Object to update."))
  1910. return
  1911. elif response == bt_cancel:
  1912. return
  1913. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1914. # edited_obj.build_ui()
  1915. # Switch notebook to Selected page
  1916. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1917. else:
  1918. if isinstance(edited_obj, GeometryObject):
  1919. self.geo_editor.deactivate()
  1920. elif isinstance(edited_obj, GerberObject):
  1921. self.grb_editor.deactivate_grb_editor()
  1922. elif isinstance(edited_obj, ExcellonObject):
  1923. self.exc_editor.deactivate()
  1924. else:
  1925. self.inform.emit('[WARNING_NOTCL] %s' %
  1926. _("Select a Gerber, Geometry or Excellon Object to update."))
  1927. return
  1928. # if notebook is hidden we show it
  1929. if self.ui.splitter.sizes()[0] == 0:
  1930. self.ui.splitter.setSizes([1, 1])
  1931. # restore the call_source to app
  1932. self.call_source = 'app'
  1933. edited_obj.plot()
  1934. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1935. self.ui.plot_tab_area.protectTab(0)
  1936. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1937. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1938. self.ui.project_frame.setDisabled(False)
  1939. def get_last_folder(self):
  1940. """
  1941. Get the folder path from where the last file was opened.
  1942. :return: String, last opened folder path
  1943. """
  1944. return self.defaults["global_last_folder"]
  1945. def get_last_save_folder(self):
  1946. """
  1947. Get the folder path from where the last file was saved.
  1948. :return: String, last saved folder path
  1949. """
  1950. loc = self.defaults["global_last_save_folder"]
  1951. if loc is None:
  1952. loc = self.defaults["global_last_folder"]
  1953. if loc is None:
  1954. loc = os.path.dirname(__file__)
  1955. return loc
  1956. def info(self, msg):
  1957. """
  1958. Informs the user. Normally on the status bar, optionally
  1959. also on the shell.
  1960. :param msg: Text to write.
  1961. :return: None
  1962. """
  1963. # Type of message in brackets at the beginning of the message.
  1964. match = re.search(r"\[(.*)\](.*)", msg)
  1965. if match:
  1966. level = match.group(1)
  1967. msg_ = match.group(2)
  1968. self.ui.fcinfo.set_status(str(msg_), level=level)
  1969. if level.lower() == "error":
  1970. self.shell_message(msg, error=True, show=True)
  1971. elif level.lower() == "warning":
  1972. self.shell_message(msg, warning=True, show=True)
  1973. elif level.lower() == "error_notcl":
  1974. self.shell_message(msg, error=True, show=False)
  1975. elif level.lower() == "warning_notcl":
  1976. self.shell_message(msg, warning=True, show=False)
  1977. elif level.lower() == "success":
  1978. self.shell_message(msg, success=True, show=False)
  1979. elif level.lower() == "selected":
  1980. self.shell_message(msg, selected=True, show=False)
  1981. else:
  1982. self.shell_message(msg, show=False)
  1983. else:
  1984. self.ui.fcinfo.set_status(str(msg), level="info")
  1985. # make sure that if the message is to clear the infobar with a space
  1986. # is not printed over and over on the shell
  1987. if msg != '':
  1988. self.shell_message(msg)
  1989. def restore_toolbar_view(self):
  1990. """
  1991. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1992. was saved in the defaults dictionary.
  1993. :return: None
  1994. """
  1995. tb = self.defaults["global_toolbar_view"]
  1996. if tb & 1:
  1997. self.ui.toolbarfile.setVisible(True)
  1998. else:
  1999. self.ui.toolbarfile.setVisible(False)
  2000. if tb & 2:
  2001. self.ui.toolbargeo.setVisible(True)
  2002. else:
  2003. self.ui.toolbargeo.setVisible(False)
  2004. if tb & 4:
  2005. self.ui.toolbarview.setVisible(True)
  2006. else:
  2007. self.ui.toolbarview.setVisible(False)
  2008. if tb & 8:
  2009. self.ui.toolbartools.setVisible(True)
  2010. else:
  2011. self.ui.toolbartools.setVisible(False)
  2012. if tb & 16:
  2013. self.ui.exc_edit_toolbar.setVisible(True)
  2014. else:
  2015. self.ui.exc_edit_toolbar.setVisible(False)
  2016. if tb & 32:
  2017. self.ui.geo_edit_toolbar.setVisible(True)
  2018. else:
  2019. self.ui.geo_edit_toolbar.setVisible(False)
  2020. if tb & 64:
  2021. self.ui.grb_edit_toolbar.setVisible(True)
  2022. else:
  2023. self.ui.grb_edit_toolbar.setVisible(False)
  2024. if tb & 128:
  2025. self.ui.snap_toolbar.setVisible(True)
  2026. else:
  2027. self.ui.snap_toolbar.setVisible(False)
  2028. if tb & 256:
  2029. self.ui.toolbarshell.setVisible(True)
  2030. else:
  2031. self.ui.toolbarshell.setVisible(False)
  2032. def on_import_preferences(self):
  2033. """
  2034. Loads the application default settings from a saved file into
  2035. ``self.defaults`` dictionary.
  2036. :return: None
  2037. """
  2038. self.defaults.report_usage("on_import_preferences")
  2039. App.log.debug("App.on_import_preferences()")
  2040. # Show file chooser
  2041. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2042. try:
  2043. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2044. directory=self.data_path,
  2045. filter=filter_)
  2046. except TypeError:
  2047. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2048. filter=filter_)
  2049. filename = str(filename)
  2050. if filename == "":
  2051. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2052. return
  2053. # Load in the defaults from the chosen file
  2054. self.defaults.load(filename=filename)
  2055. self.preferencesUiManager.on_preferences_edited()
  2056. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2057. def on_export_preferences(self):
  2058. """
  2059. Save the defaults dictionary to a file.
  2060. :return: None
  2061. """
  2062. self.defaults.report_usage("on_export_preferences")
  2063. App.log.debug("on_export_preferences()")
  2064. # defaults_file_content = None
  2065. # Show file chooser
  2066. date = str(datetime.today()).rpartition('.')[0]
  2067. date = ''.join(c for c in date if c not in ':-')
  2068. date = date.replace(' ', '_')
  2069. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2070. try:
  2071. filename, _f = FCFileSaveDialog.get_saved_filename(
  2072. caption=_("Export FlatCAM Preferences"),
  2073. directory=self.data_path + '/preferences_' + date,
  2074. filter=filter__
  2075. )
  2076. except TypeError:
  2077. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2078. filename = str(filename)
  2079. if filename == "":
  2080. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2081. return
  2082. # Update options
  2083. self.preferencesUiManager.defaults_read_form()
  2084. self.defaults.propagate_defaults()
  2085. # Save update options
  2086. try:
  2087. self.defaults.write(filename=filename)
  2088. except Exception:
  2089. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2090. return
  2091. if self.defaults["global_open_style"] is False:
  2092. self.file_opened.emit("preferences", filename)
  2093. self.file_saved.emit("preferences", filename)
  2094. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2095. def save_to_file(self, content_to_save, txt_content):
  2096. """
  2097. Save something to a file.
  2098. :return: None
  2099. """
  2100. self.defaults.report_usage("save_to_file")
  2101. App.log.debug("save_to_file()")
  2102. self.date = str(datetime.today()).rpartition('.')[0]
  2103. self.date = ''.join(c for c in self.date if c not in ':-')
  2104. self.date = self.date.replace(' ', '_')
  2105. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2106. path_to_save = self.defaults["global_last_save_folder"] if \
  2107. self.defaults["global_last_save_folder"] is not None else self.data_path
  2108. try:
  2109. filename, _f = FCFileSaveDialog.get_saved_filename(
  2110. caption=_("Save to file"),
  2111. directory=path_to_save + '/file_' + self.date,
  2112. filter=filter__
  2113. )
  2114. except TypeError:
  2115. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2116. filename = str(filename)
  2117. if filename == "":
  2118. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2119. return
  2120. else:
  2121. try:
  2122. with open(filename, 'w') as f:
  2123. ___ = f.read()
  2124. except PermissionError:
  2125. self.inform.emit('[WARNING] %s' %
  2126. _("Permission denied, saving not possible.\n"
  2127. "Most likely another app is holding the file open and not accessible."))
  2128. return
  2129. except IOError:
  2130. App.log.debug('Creating a new file ...')
  2131. f = open(filename, 'w')
  2132. f.close()
  2133. except Exception:
  2134. e = sys.exc_info()[0]
  2135. App.log.error("Could not load the file.")
  2136. App.log.error(str(e))
  2137. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2138. return
  2139. # Save content
  2140. if filename.rpartition('.')[2].lower() == 'html':
  2141. file_content = content_to_save
  2142. else:
  2143. file_content = txt_content
  2144. try:
  2145. with open(filename, "w") as f:
  2146. f.write(file_content)
  2147. except Exception:
  2148. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2149. return
  2150. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2151. def save_geometry(self, x, y, width, height, notebook_width):
  2152. """
  2153. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2154. launch of the application.
  2155. :param x: X position of the main window
  2156. :param y: Y position of the main window
  2157. :param width: width of the main window
  2158. :param height: height of the main window
  2159. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2160. :return: None
  2161. """
  2162. self.defaults["global_def_win_x"] = x
  2163. self.defaults["global_def_win_y"] = y
  2164. self.defaults["global_def_win_w"] = width
  2165. self.defaults["global_def_win_h"] = height
  2166. self.defaults["global_def_notebook_width"] = notebook_width
  2167. self.preferencesUiManager.save_defaults()
  2168. def restore_main_win_geom(self):
  2169. try:
  2170. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2171. self.defaults["global_def_win_y"],
  2172. self.defaults["global_def_win_w"],
  2173. self.defaults["global_def_win_h"])
  2174. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2175. except KeyError as e:
  2176. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2177. def message_dialog(self, title, message, kind="info"):
  2178. """
  2179. Builds and show a custom QMessageBox to be used in FlatCAM.
  2180. :param title: title of the QMessageBox
  2181. :param message: message to be displayed
  2182. :param kind: type of QMessageBox; will display a specific icon.
  2183. :return:
  2184. """
  2185. icon = {"info": QtWidgets.QMessageBox.Information,
  2186. "warning": QtWidgets.QMessageBox.Warning,
  2187. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2188. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2189. dlg.setText(message)
  2190. dlg.exec_()
  2191. def register_recent(self, kind, filename):
  2192. """
  2193. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2194. dictionary.
  2195. :param kind: type of file that was opened
  2196. :param filename: the path and file name for the file that was opened
  2197. :return:
  2198. """
  2199. self.log.debug("register_recent()")
  2200. self.log.debug(" %s" % kind)
  2201. self.log.debug(" %s" % filename)
  2202. record = {'kind': str(kind), 'filename': str(filename)}
  2203. if record in self.recent:
  2204. return
  2205. if record in self.recent_projects:
  2206. return
  2207. if record['kind'] == 'project':
  2208. self.recent_projects.insert(0, record)
  2209. else:
  2210. self.recent.insert(0, record)
  2211. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2212. self.recent.pop()
  2213. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2214. self.recent_projects.pop()
  2215. try:
  2216. f = open(self.data_path + '/recent.json', 'w')
  2217. except IOError:
  2218. App.log.error("Failed to open recent items file for writing.")
  2219. self.inform.emit('[ERROR_NOTCL] %s' %
  2220. _('Failed to open recent files file for writing.'))
  2221. return
  2222. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2223. f.close()
  2224. try:
  2225. fp = open(self.data_path + '/recent_projects.json', 'w')
  2226. except IOError:
  2227. App.log.error("Failed to open recent items file for writing.")
  2228. self.inform.emit('[ERROR_NOTCL] %s' %
  2229. _('Failed to open recent projects file for writing.'))
  2230. return
  2231. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2232. fp.close()
  2233. # Re-build the recent items menu
  2234. self.setup_recent_items()
  2235. def new_object(self, kind, name, initialize, plot=True, autoselected=True):
  2236. """
  2237. Creates a new specialized FlatCAMObj and attaches it to the application,
  2238. this is, updates the GUI accordingly, any other records and plots it.
  2239. This method is thread-safe.
  2240. Notes:
  2241. * If the name is in use, the self.collection will modify it
  2242. when appending it to the collection. There is no need to handle
  2243. name conflicts here.
  2244. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2245. :type kind: str
  2246. :param name: Name for the object.
  2247. :type name: str
  2248. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2249. The function is called with 2 parameters: the new object and the App instance.
  2250. :type initialize: function
  2251. :param plot: If to plot the resulting object
  2252. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2253. self.collection
  2254. :return: None
  2255. :rtype: None
  2256. """
  2257. App.log.debug("new_object()")
  2258. obj_plot = plot
  2259. obj_autoselected = autoselected
  2260. t0 = time.time() # Debug
  2261. # ## Create object
  2262. classdict = {
  2263. "gerber": GerberObject,
  2264. "excellon": ExcellonObject,
  2265. "cncjob": CNCJobObject,
  2266. "geometry": GeometryObject,
  2267. "script": ScriptObject,
  2268. "document": DocumentObject
  2269. }
  2270. App.log.debug("Calling object constructor...")
  2271. # Object creation/instantiation
  2272. obj = classdict[kind](name)
  2273. obj.units = self.options["units"]
  2274. # IMPORTANT
  2275. # The key names in defaults and options dictionary's are not random:
  2276. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2277. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2278. # copied to self.options. After that, below, depending on the type of
  2279. # object that is created, it will strip the name of the object and the underline (if the original key was
  2280. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2281. # "toolchange"
  2282. for option in self.options:
  2283. if option.find(kind + "_") == 0:
  2284. oname = option[len(kind) + 1:]
  2285. obj.options[oname] = self.options[option]
  2286. obj.isHovering = False
  2287. obj.notHovering = True
  2288. # Initialize as per user request
  2289. # User must take care to implement initialize
  2290. # in a thread-safe way as is is likely that we
  2291. # have been invoked in a separate thread.
  2292. t1 = time.time()
  2293. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2294. try:
  2295. return_value = initialize(obj, self)
  2296. except Exception as e:
  2297. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2298. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2299. msg += traceback.format_exc()
  2300. self.inform.emit(msg)
  2301. return "fail"
  2302. t2 = time.time()
  2303. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2304. if return_value == 'fail':
  2305. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2306. return "fail"
  2307. # Check units and convert if necessary
  2308. # This condition CAN be true because initialize() can change obj.units
  2309. if self.options["units"].upper() != obj.units.upper():
  2310. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2311. obj.convert_units(self.options["units"])
  2312. t3 = time.time()
  2313. self.log.debug("%f seconds converting units." % (t3 - t2))
  2314. # Create the bounding box for the object and then add the results to the obj.options
  2315. # But not for Scripts or for Documents
  2316. if kind != 'document' and kind != 'script':
  2317. try:
  2318. xmin, ymin, xmax, ymax = obj.bounds()
  2319. obj.options['xmin'] = xmin
  2320. obj.options['ymin'] = ymin
  2321. obj.options['xmax'] = xmax
  2322. obj.options['ymax'] = ymax
  2323. except Exception as e:
  2324. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2325. return "fail"
  2326. try:
  2327. if kind == 'excellon':
  2328. obj.fill_color = self.defaults["excellon_plot_fill"]
  2329. obj.outline_color = self.defaults["excellon_plot_line"]
  2330. if kind == 'gerber':
  2331. obj.fill_color = self.defaults["gerber_plot_fill"]
  2332. obj.outline_color = self.defaults["gerber_plot_line"]
  2333. except Exception as e:
  2334. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2335. # update the KeyWords list with the name of the file
  2336. self.myKeywords.append(obj.options['name'])
  2337. log.debug("Moving new object back to main thread.")
  2338. # Move the object to the main thread and let the app know that it is available.
  2339. obj.moveToThread(self.main_thread)
  2340. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2341. return obj
  2342. def new_excellon_object(self):
  2343. """
  2344. Creates a new, blank Excellon object.
  2345. :return: None
  2346. """
  2347. self.defaults.report_usage("new_excellon_object()")
  2348. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2349. def new_geometry_object(self):
  2350. """
  2351. Creates a new, blank and single-tool Geometry object.
  2352. :return: None
  2353. """
  2354. self.defaults.report_usage("new_geometry_object()")
  2355. def initialize(obj, app):
  2356. obj.multitool = False
  2357. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2358. def new_gerber_object(self):
  2359. """
  2360. Creates a new, blank Gerber object.
  2361. :return: None
  2362. """
  2363. self.defaults.report_usage("new_gerber_object()")
  2364. def initialize(grb_obj, app):
  2365. grb_obj.multitool = False
  2366. grb_obj.source_file = []
  2367. grb_obj.multigeo = False
  2368. grb_obj.follow = False
  2369. grb_obj.apertures = {}
  2370. grb_obj.solid_geometry = []
  2371. try:
  2372. grb_obj.options['xmin'] = 0
  2373. grb_obj.options['ymin'] = 0
  2374. grb_obj.options['xmax'] = 0
  2375. grb_obj.options['ymax'] = 0
  2376. except KeyError:
  2377. pass
  2378. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2379. def new_script_object(self):
  2380. """
  2381. Creates a new, blank TCL Script object.
  2382. :return: None
  2383. """
  2384. self.defaults.report_usage("new_script_object()")
  2385. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2386. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2387. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2388. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2389. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2390. # "ListSys, MillDrills,\n" \
  2391. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2392. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2393. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2394. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2395. # "# SubtractRectangle, Version, WriteGCode\n"
  2396. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2397. '# %s:\n' % _('TCL Tutorial is here') + \
  2398. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2399. '# %s:\n' % _("FlatCAM commands list")
  2400. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2401. "(displayed in Tcl Shell).")
  2402. def initialize(obj, app):
  2403. obj.source_file = deepcopy(new_source_file)
  2404. outname = 'new_script'
  2405. self.new_object('script', outname, initialize, plot=False)
  2406. def new_document_object(self):
  2407. """
  2408. Creates a new, blank Document object.
  2409. :return: None
  2410. """
  2411. self.defaults.report_usage("new_document_object()")
  2412. def initialize(obj, app):
  2413. obj.source_file = ""
  2414. self.new_object('document', 'new_document', initialize, plot=False)
  2415. def on_object_created(self, obj, plot, auto_select):
  2416. """
  2417. Event callback for object creation.
  2418. It will add the new object to the collection. After that it will plot the object in a threaded way
  2419. :param obj: The newly created FlatCAM object.
  2420. :param plot: if the newly create object t obe plotted
  2421. :param auto_select: if the newly created object to be autoselected after creation
  2422. :return: None
  2423. """
  2424. t0 = time.time() # DEBUG
  2425. self.log.debug("on_object_created()")
  2426. # The Collection might change the name if there is a collision
  2427. self.collection.append(obj)
  2428. # after adding the object to the collection always update the list of objects that are in the collection
  2429. self.all_objects_list = self.collection.get_list()
  2430. # self.inform.emit('[selected] %s created & selected: %s' %
  2431. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2432. if obj.kind == 'gerber':
  2433. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2434. kind=obj.kind.capitalize(),
  2435. color='green',
  2436. name=str(obj.options['name']), tx=_("created/selected"))
  2437. )
  2438. elif obj.kind == 'excellon':
  2439. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2440. kind=obj.kind.capitalize(),
  2441. color='brown',
  2442. name=str(obj.options['name']), tx=_("created/selected"))
  2443. )
  2444. elif obj.kind == 'cncjob':
  2445. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2446. kind=obj.kind.capitalize(),
  2447. color='blue',
  2448. name=str(obj.options['name']), tx=_("created/selected"))
  2449. )
  2450. elif obj.kind == 'geometry':
  2451. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2452. kind=obj.kind.capitalize(),
  2453. color='red',
  2454. name=str(obj.options['name']), tx=_("created/selected"))
  2455. )
  2456. elif obj.kind == 'script':
  2457. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2458. kind=obj.kind.capitalize(),
  2459. color='orange',
  2460. name=str(obj.options['name']), tx=_("created/selected"))
  2461. )
  2462. elif obj.kind == 'document':
  2463. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2464. kind=obj.kind.capitalize(),
  2465. color='darkCyan',
  2466. name=str(obj.options['name']), tx=_("created/selected"))
  2467. )
  2468. # update the SHELL auto-completer model with the name of the new object
  2469. self.shell._edit.set_model_data(self.myKeywords)
  2470. if auto_select:
  2471. # select the just opened object but deselect the previous ones
  2472. self.collection.set_all_inactive()
  2473. self.collection.set_active(obj.options["name"])
  2474. else:
  2475. self.collection.set_all_inactive()
  2476. # here it is done the object plotting
  2477. def worker_task(t_obj):
  2478. with self.proc_container.new(_("Plotting")):
  2479. if isinstance(t_obj, CNCJobObject):
  2480. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2481. else:
  2482. t_obj.plot()
  2483. t1 = time.time() # DEBUG
  2484. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2485. self.object_plotted.emit(t_obj)
  2486. # Send to worker
  2487. # self.worker.add_task(worker_task, [self])
  2488. if plot is True:
  2489. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2490. def on_object_changed(self, obj):
  2491. """
  2492. Called whenever the geometry of the object was changed in some way.
  2493. This require the update of it's bounding values so it can be the selected on canvas.
  2494. Update the bounding box data from obj.options
  2495. :param obj: the object that was changed
  2496. :return: None
  2497. """
  2498. xmin, ymin, xmax, ymax = obj.bounds()
  2499. obj.options['xmin'] = xmin
  2500. obj.options['ymin'] = ymin
  2501. obj.options['xmax'] = xmax
  2502. obj.options['ymax'] = ymax
  2503. log.debug("Object changed, updating the bounding box data on self.options")
  2504. # delete the old selection shape
  2505. self.delete_selection_shape()
  2506. self.should_we_save = True
  2507. def on_object_plotted(self):
  2508. """
  2509. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2510. :return: None
  2511. """
  2512. self.on_zoom_fit(None)
  2513. def on_about(self):
  2514. """
  2515. Displays the "about" dialog found in the Menu --> Help.
  2516. :return: None
  2517. """
  2518. self.defaults.report_usage("on_about")
  2519. version = self.version
  2520. version_date = self.version_date
  2521. beta = self.beta
  2522. class AboutDialog(QtWidgets.QDialog):
  2523. def __init__(self, app, parent=None):
  2524. QtWidgets.QDialog.__init__(self, parent)
  2525. self.app = app
  2526. # Icon and title
  2527. self.setWindowIcon(parent.app_icon)
  2528. self.setWindowTitle(_("About FlatCAM"))
  2529. self.resize(600, 200)
  2530. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2531. # self.setStyleSheet(
  2532. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2533. # "background-attachment: fixed"
  2534. # )
  2535. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2536. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2537. # palette = QtGui.QPalette()
  2538. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2539. # self.setPalette(palette)
  2540. logo = QtWidgets.QLabel()
  2541. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2542. title = QtWidgets.QLabel(
  2543. "<font size=8><B>FlatCAM</B></font><BR>"
  2544. "{title}<BR>"
  2545. "<BR>"
  2546. "<BR>"
  2547. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2548. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2549. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2550. "<B>{issue}</B></a><BR>".format(
  2551. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2552. devel=_("Development"),
  2553. down=_("DOWNLOAD"),
  2554. issue=_("Issue tracker"))
  2555. )
  2556. title.setOpenExternalLinks(True)
  2557. closebtn = QtWidgets.QPushButton(_("Close"))
  2558. tab_widget = QtWidgets.QTabWidget()
  2559. description_label = QtWidgets.QLabel(
  2560. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2561. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2562. version=version,
  2563. beta=('BETA' if beta else ''),
  2564. date=version_date,
  2565. arch=platform.architecture()[0])
  2566. )
  2567. description_label.setOpenExternalLinks(True)
  2568. lic_lbl_header = QtWidgets.QLabel(
  2569. '%s:<br>%s<br>' % (
  2570. _('Licensed under the MIT license'),
  2571. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2572. "http://www.opensource.org/licenses/mit-license.php</a>"
  2573. )
  2574. )
  2575. lic_lbl_header.setOpenExternalLinks(True)
  2576. lic_lbl_body = QtWidgets.QLabel(
  2577. _(
  2578. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2579. 'of this software and associated documentation files (the "Software"), to deal\n'
  2580. 'in the Software without restriction, including without limitation the rights\n'
  2581. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2582. 'copies of the Software, and to permit persons to whom the Software is\n'
  2583. 'furnished to do so, subject to the following conditions:\n\n'
  2584. 'The above copyright notice and this permission notice shall be included in\n'
  2585. 'all copies or substantial portions of the Software.\n\n'
  2586. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2587. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2588. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2589. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2590. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2591. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2592. 'THE SOFTWARE.'
  2593. )
  2594. )
  2595. attributions_label = QtWidgets.QLabel(
  2596. _(
  2597. 'Some of the icons used are from the following sources:<br>'
  2598. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2599. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2600. 'title="Flaticon">www.flaticon.com</a></div>'
  2601. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2602. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2603. )
  2604. )
  2605. attributions_label.setOpenExternalLinks(True)
  2606. # layouts
  2607. layout1 = QtWidgets.QVBoxLayout()
  2608. layout1_1 = QtWidgets.QHBoxLayout()
  2609. layout1_2 = QtWidgets.QHBoxLayout()
  2610. layout2 = QtWidgets.QHBoxLayout()
  2611. layout3 = QtWidgets.QHBoxLayout()
  2612. self.setLayout(layout1)
  2613. layout1.addLayout(layout1_1)
  2614. layout1.addLayout(layout1_2)
  2615. layout1.addLayout(layout2)
  2616. layout1.addLayout(layout3)
  2617. layout1_1.addStretch()
  2618. layout1_1.addWidget(description_label)
  2619. layout1_2.addWidget(tab_widget)
  2620. self.splash_tab = QtWidgets.QWidget()
  2621. self.splash_tab.setObjectName("splash_about")
  2622. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2623. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2624. tab_widget.addTab(self.splash_tab, _("Splash"))
  2625. self.programmmers_tab = QtWidgets.QWidget()
  2626. self.programmmers_tab.setObjectName("programmers_about")
  2627. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2628. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2629. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2630. self.translators_tab = QtWidgets.QWidget()
  2631. self.translators_tab.setObjectName("translators_about")
  2632. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2633. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2634. tab_widget.addTab(self.translators_tab, _("Translators"))
  2635. self.license_tab = QtWidgets.QWidget()
  2636. self.license_tab.setObjectName("license_about")
  2637. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2638. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2639. tab_widget.addTab(self.license_tab, _("License"))
  2640. self.attributions_tab = QtWidgets.QWidget()
  2641. self.attributions_tab.setObjectName("attributions_about")
  2642. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2643. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2644. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2645. self.splash_tab_layout.addWidget(logo, stretch=0)
  2646. self.splash_tab_layout.addWidget(title, stretch=1)
  2647. pal = QtGui.QPalette()
  2648. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2649. self.prog_grid_lay = QtWidgets.QGridLayout()
  2650. self.prog_grid_lay.setHorizontalSpacing(20)
  2651. self.prog_grid_lay.setColumnStretch(0, 0)
  2652. self.prog_grid_lay.setColumnStretch(2, 1)
  2653. prog_widget = QtWidgets.QWidget()
  2654. prog_widget.setLayout(self.prog_grid_lay)
  2655. prog_scroll = QtWidgets.QScrollArea()
  2656. prog_scroll.setWidget(prog_widget)
  2657. prog_scroll.setWidgetResizable(True)
  2658. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2659. prog_scroll.setPalette(pal)
  2660. self.programmmers_tab_layout.addWidget(prog_scroll)
  2661. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2662. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2663. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2664. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2665. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2666. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2704. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2705. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2706. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2707. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2708. self.translator_grid_lay = QtWidgets.QGridLayout()
  2709. self.translator_grid_lay.setColumnStretch(0, 0)
  2710. self.translator_grid_lay.setColumnStretch(1, 0)
  2711. self.translator_grid_lay.setColumnStretch(2, 1)
  2712. self.translator_grid_lay.setColumnStretch(3, 0)
  2713. # trans_widget = QtWidgets.QWidget()
  2714. # trans_widget.setLayout(self.translator_grid_lay)
  2715. # self.translators_tab_layout.addWidget(trans_widget)
  2716. # self.translators_tab_layout.addStretch()
  2717. trans_widget = QtWidgets.QWidget()
  2718. trans_widget.setLayout(self.translator_grid_lay)
  2719. trans_scroll = QtWidgets.QScrollArea()
  2720. trans_scroll.setWidget(trans_widget)
  2721. trans_scroll.setWidgetResizable(True)
  2722. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2723. trans_scroll.setPalette(pal)
  2724. self.translators_tab_layout.addWidget(trans_scroll)
  2725. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2726. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2727. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2728. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2729. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2750. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2751. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2752. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2753. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2754. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2755. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2756. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2757. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2758. self.translator_grid_lay.setColumnStretch(0, 0)
  2759. self.translators_tab_layout.addStretch()
  2760. self.license_tab_layout.addWidget(lic_lbl_header)
  2761. self.license_tab_layout.addWidget(lic_lbl_body)
  2762. self.license_tab_layout.addStretch()
  2763. self.attributions_tab_layout.addWidget(attributions_label)
  2764. self.attributions_tab_layout.addStretch()
  2765. layout3.addStretch()
  2766. layout3.addWidget(closebtn)
  2767. closebtn.clicked.connect(self.accept)
  2768. AboutDialog(app=self, parent=self.ui).exec_()
  2769. def install_bookmarks(self, book_dict=None):
  2770. """
  2771. Install the bookmarks actions in the Help menu -> Bookmarks
  2772. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2773. :return: None
  2774. """
  2775. if book_dict is None:
  2776. self.defaults["global_bookmarks"].update(
  2777. {
  2778. '1': ['FlatCAM', "http://flatcam.org"],
  2779. '2': ['Backup Site', ""]
  2780. }
  2781. )
  2782. else:
  2783. self.defaults["global_bookmarks"].clear()
  2784. self.defaults["global_bookmarks"].update(book_dict)
  2785. # first try to disconnect if somehow they get connected from elsewhere
  2786. for act in self.ui.menuhelp_bookmarks.actions():
  2787. try:
  2788. act.triggered.disconnect()
  2789. except TypeError:
  2790. pass
  2791. # clear all actions except the last one who is the Bookmark manager
  2792. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2793. pass
  2794. else:
  2795. self.ui.menuhelp_bookmarks.removeAction(act)
  2796. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2797. if self.defaults["global_bookmarks"]:
  2798. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2799. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2800. # the JSON is first making the keys as strings (therefore I have to use strings too
  2801. # or do the conversion :(
  2802. # )
  2803. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2804. # the '10' entry jsut after '1' therefore ordering as strings
  2805. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2806. key=lambda x: int(x[0]))
  2807. for entry, bookmark in sorted_bookmarks:
  2808. title = bookmark[0]
  2809. weblink = bookmark[1]
  2810. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2811. act.setText(title)
  2812. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2813. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2814. if title == 'Backup Site' and weblink == "":
  2815. act.triggered.connect(self.on_backup_site)
  2816. else:
  2817. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2818. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2819. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2820. def on_bookmarks_manager(self):
  2821. """
  2822. Adds the bookmark manager in a Tab in Plot Area
  2823. :return:
  2824. """
  2825. for idx in range(self.ui.plot_tab_area.count()):
  2826. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2827. # there can be only one instance of Bookmark Manager at one time
  2828. return
  2829. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2830. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2831. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2832. # add the tab if it was closed
  2833. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2834. # delete the absolute and relative position and messages in the infobar
  2835. self.ui.position_label.setText("")
  2836. self.ui.rel_position_label.setText("")
  2837. # Switch plot_area to preferences page
  2838. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2839. def on_backup_site(self):
  2840. msgbox = QtWidgets.QMessageBox()
  2841. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2842. "1. FlatCAM.org website is down\n"
  2843. "2. Someone forked FlatCAM project and wants to point\n"
  2844. "to his own website\n\n"
  2845. "If you can't get any informations about FlatCAM beta\n"
  2846. "use the YouTube channel link from the Help menu."))
  2847. msgbox.setWindowTitle(_("Alternative website"))
  2848. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2849. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2850. msgbox.setDefaultButton(bt_yes)
  2851. msgbox.exec_()
  2852. # response = msgbox.clickedButton()
  2853. def on_file_savedefaults(self):
  2854. """
  2855. Callback for menu item File->Save Defaults. Saves application default options
  2856. ``self.defaults`` to current_defaults.FlatConfig.
  2857. :return: None
  2858. """
  2859. self.preferencesUiManager.save_defaults()
  2860. def final_save(self):
  2861. """
  2862. Callback for doing a preferences save to file whenever the application is about to quit.
  2863. If the project has changes, it will ask the user to save the project.
  2864. :return: None
  2865. """
  2866. if self.save_in_progress:
  2867. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2868. return
  2869. if self.should_we_save and self.collection.get_list():
  2870. msgbox = QtWidgets.QMessageBox()
  2871. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2872. "\n"
  2873. "Do you want to Save the project?"))
  2874. msgbox.setWindowTitle(_("Save changes"))
  2875. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2876. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2877. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2878. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2879. msgbox.setDefaultButton(bt_yes)
  2880. msgbox.exec_()
  2881. response = msgbox.clickedButton()
  2882. if response == bt_yes:
  2883. try:
  2884. self.trayIcon.hide()
  2885. except Exception:
  2886. pass
  2887. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2888. elif response == bt_no:
  2889. try:
  2890. self.trayIcon.hide()
  2891. except Exception:
  2892. pass
  2893. self.quit_application()
  2894. elif response == bt_cancel:
  2895. return
  2896. else:
  2897. try:
  2898. self.trayIcon.hide()
  2899. except Exception:
  2900. pass
  2901. self.quit_application()
  2902. def quit_application(self):
  2903. """
  2904. Called (as a pyslot or not) when the application is quit.
  2905. :return: None
  2906. """
  2907. self.preferencesUiManager.save_defaults(silent=True)
  2908. log.debug("App.quit_application() --> App Defaults saved.")
  2909. if self.cmd_line_headless != 1:
  2910. # save app state to file
  2911. stgs = QSettings("Open Source", "FlatCAM")
  2912. stgs.setValue('saved_gui_state', self.ui.saveState())
  2913. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2914. stgs.setValue(
  2915. 'language',
  2916. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2917. )
  2918. stgs.setValue(
  2919. 'notebook_font_size',
  2920. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2921. )
  2922. stgs.setValue(
  2923. 'axis_font_size',
  2924. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2925. )
  2926. stgs.setValue(
  2927. 'textbox_font_size',
  2928. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2929. )
  2930. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2931. stgs.setValue(
  2932. 'machinist',
  2933. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2934. )
  2935. # This will write the setting to the platform specific storage.
  2936. del stgs
  2937. log.debug("App.quit_application() --> App UI state saved.")
  2938. # try to quit the Socket opened by ArgsThread class
  2939. try:
  2940. self.new_launch.thread_exit = True
  2941. self.new_launch.listener.close()
  2942. except Exception as err:
  2943. log.debug("App.quit_application() --> %s" % str(err))
  2944. # try to quit the QThread that run ArgsThread class
  2945. try:
  2946. self.th.terminate()
  2947. except Exception as e:
  2948. log.debug("App.quit_application() --> %s" % str(e))
  2949. # terminate workers
  2950. self.workers.__del__()
  2951. # quit app by signalling for self.kill_app() method
  2952. # self.close_app_signal.emit()
  2953. QtWidgets.qApp.quit()
  2954. # QtCore.QCoreApplication.exit()
  2955. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2956. # we use the following command
  2957. minor_v = sys.version_info.minor
  2958. if minor_v < 8:
  2959. sys.exit(0)
  2960. else:
  2961. os._exit(0) # fix to work with Python 3.8
  2962. @staticmethod
  2963. def kill_app():
  2964. # QtCore.QCoreApplication.quit()
  2965. QtWidgets.qApp.quit()
  2966. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2967. # we use the following command
  2968. sys.exit(0)
  2969. def on_portable_checked(self, state):
  2970. """
  2971. Callback called when the checkbox in Preferences GUI is checked.
  2972. It will set the application as portable by creating the preferences and recent files in the
  2973. 'config' folder found in the FlatCAM installation folder.
  2974. :param state: boolean, the state of the checkbox when clicked/checked
  2975. :return:
  2976. """
  2977. line_no = 0
  2978. data = None
  2979. if sys.platform != 'win32':
  2980. # this won't work in Linux or MacOS
  2981. return
  2982. # test if the app was frozen and choose the path for the configuration file
  2983. if getattr(sys, "frozen", False) is True:
  2984. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2985. else:
  2986. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2987. config_file = current_data_path + '\\configuration.txt'
  2988. try:
  2989. with open(config_file, 'r') as f:
  2990. try:
  2991. data = f.readlines()
  2992. except Exception as e:
  2993. log.debug('App.__init__() -->%s' % str(e))
  2994. return
  2995. except FileNotFoundError:
  2996. pass
  2997. for line in data:
  2998. line = line.strip('\n')
  2999. param = str(line).rpartition('=')
  3000. if param[0] == 'portable':
  3001. break
  3002. line_no += 1
  3003. if state:
  3004. data[line_no] = 'portable=True\n'
  3005. # create the new defauults files
  3006. # create current_defaults.FlatConfig file if there is none
  3007. try:
  3008. f = open(current_data_path + '/current_defaults.FlatConfig')
  3009. f.close()
  3010. except IOError:
  3011. App.log.debug('Creating empty current_defaults.FlatConfig')
  3012. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3013. json.dump({}, f)
  3014. f.close()
  3015. # create factory_defaults.FlatConfig file if there is none
  3016. try:
  3017. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3018. f.close()
  3019. except IOError:
  3020. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3021. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3022. json.dump({}, f)
  3023. f.close()
  3024. try:
  3025. f = open(current_data_path + '/recent.json')
  3026. f.close()
  3027. except IOError:
  3028. App.log.debug('Creating empty recent.json')
  3029. f = open(current_data_path + '/recent.json', 'w')
  3030. json.dump([], f)
  3031. f.close()
  3032. try:
  3033. fp = open(current_data_path + '/recent_projects.json')
  3034. fp.close()
  3035. except IOError:
  3036. App.log.debug('Creating empty recent_projects.json')
  3037. fp = open(current_data_path + '/recent_projects.json', 'w')
  3038. json.dump([], fp)
  3039. fp.close()
  3040. # save the current defaults to the new defaults file
  3041. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3042. else:
  3043. data[line_no] = 'portable=False\n'
  3044. with open(config_file, 'w') as f:
  3045. f.writelines(data)
  3046. def on_register_files(self, obj_type=None):
  3047. """
  3048. Called whenever there is a need to register file extensions with FlatCAM.
  3049. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3050. :param obj_type: the type of object to be register for.
  3051. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3052. :return: None
  3053. """
  3054. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3055. new_reg_path = 'Software\\Classes\\'
  3056. # find if the current user is admin
  3057. try:
  3058. is_admin = os.getuid() == 0
  3059. except AttributeError:
  3060. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3061. if is_admin is True:
  3062. root_path = winreg.HKEY_LOCAL_MACHINE
  3063. else:
  3064. root_path = winreg.HKEY_CURRENT_USER
  3065. # create the keys
  3066. def set_reg(name, root_pth, new_reg_path, value):
  3067. try:
  3068. winreg.CreateKey(root_pth, new_reg_path)
  3069. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3070. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3071. return True
  3072. except WindowsError:
  3073. return False
  3074. # delete key in registry
  3075. def delete_reg(root_pth, reg_path, key_to_del):
  3076. key_to_del_path = reg_path + key_to_del
  3077. try:
  3078. winreg.DeleteKey(root_pth, key_to_del_path)
  3079. return True
  3080. except WindowsError:
  3081. return False
  3082. if obj_type is None or obj_type == 'excellon':
  3083. exc_list = \
  3084. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3085. exc_list = [x for x in exc_list if x != '']
  3086. # register all keys in the Preferences window
  3087. for ext in exc_list:
  3088. new_k = new_reg_path + '.%s' % ext
  3089. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3090. # and unregister those that are no longer in the Preferences windows but are in the file
  3091. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3092. if ext not in exc_list:
  3093. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3094. # now write the updated extensions to the self.defaults
  3095. # new_ext = ''
  3096. # for ext in exc_list:
  3097. # new_ext = new_ext + ext + ', '
  3098. # self.defaults["fa_excellon"] = new_ext
  3099. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3100. if obj_type is None or obj_type == 'gcode':
  3101. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3102. gco_list = [x for x in gco_list if x != '']
  3103. # register all keys in the Preferences window
  3104. for ext in gco_list:
  3105. new_k = new_reg_path + '.%s' % ext
  3106. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3107. # and unregister those that are no longer in the Preferences windows but are in the file
  3108. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3109. if ext not in gco_list:
  3110. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3111. # now write the updated extensions to the self.defaults
  3112. # new_ext = ''
  3113. # for ext in gco_list:
  3114. # new_ext = new_ext + ext + ', '
  3115. # self.defaults["fa_gcode"] = new_ext
  3116. self.inform.emit('[success] %s' %
  3117. _("Selected GCode file extensions registered with FlatCAM."))
  3118. if obj_type is None or obj_type == 'gerber':
  3119. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3120. grb_list = [x for x in grb_list if x != '']
  3121. # register all keys in the Preferences window
  3122. for ext in grb_list:
  3123. new_k = new_reg_path + '.%s' % ext
  3124. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3125. # and unregister those that are no longer in the Preferences windows but are in the file
  3126. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3127. if ext not in grb_list:
  3128. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3129. # now write the updated extensions to the self.defaults
  3130. # new_ext = ''
  3131. # for ext in grb_list:
  3132. # new_ext = new_ext + ext + ', '
  3133. # self.defaults["fa_gerber"] = new_ext
  3134. self.inform.emit('[success] %s' %
  3135. _("Selected Gerber file extensions registered with FlatCAM."))
  3136. def add_extension(self, ext_type):
  3137. """
  3138. Add a file extension to the list for a specific object
  3139. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3140. :return:
  3141. """
  3142. if ext_type == 'excellon':
  3143. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3144. if new_ext == '':
  3145. return
  3146. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_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_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3152. if ext_type == 'gcode':
  3153. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3154. if new_ext == '':
  3155. return
  3156. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3157. if new_ext in old_val:
  3158. return
  3159. old_val.append(new_ext)
  3160. old_val.sort()
  3161. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3162. if ext_type == 'gerber':
  3163. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3164. if new_ext == '':
  3165. return
  3166. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3167. if new_ext in old_val:
  3168. return
  3169. old_val.append(new_ext)
  3170. old_val.sort()
  3171. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3172. if ext_type == 'keyword':
  3173. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3174. if new_kw == '':
  3175. return
  3176. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3177. if new_kw in old_val:
  3178. return
  3179. old_val.append(new_kw)
  3180. old_val.sort()
  3181. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3182. # update the self.myKeywords so the model is updated
  3183. self.autocomplete_kw_list = \
  3184. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3185. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3186. self.shell._edit.set_model_data(self.myKeywords)
  3187. def del_extension(self, ext_type):
  3188. """
  3189. Remove a file extension from the list for a specific object
  3190. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3191. :return:
  3192. """
  3193. if ext_type == 'excellon':
  3194. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3195. if new_ext == '':
  3196. return
  3197. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_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_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3203. if ext_type == 'gcode':
  3204. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3205. if new_ext == '':
  3206. return
  3207. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3208. if new_ext not in old_val:
  3209. return
  3210. old_val.remove(new_ext)
  3211. old_val.sort()
  3212. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3213. if ext_type == 'gerber':
  3214. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3215. if new_ext == '':
  3216. return
  3217. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3218. if new_ext not in old_val:
  3219. return
  3220. old_val.remove(new_ext)
  3221. old_val.sort()
  3222. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3223. if ext_type == 'keyword':
  3224. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3225. if new_kw == '':
  3226. return
  3227. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3228. if new_kw not in old_val:
  3229. return
  3230. old_val.remove(new_kw)
  3231. old_val.sort()
  3232. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3233. # update the self.myKeywords so the model is updated
  3234. self.autocomplete_kw_list = \
  3235. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3236. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3237. self.shell._edit.set_model_data(self.myKeywords)
  3238. def restore_extensions(self, ext_type):
  3239. """
  3240. Restore all file extensions associations with FlatCAM, for a specific object
  3241. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3242. :return:
  3243. """
  3244. if ext_type == 'excellon':
  3245. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3246. # for the ability to open Excellon files with .txt extension
  3247. new_exc_list = deepcopy(self.exc_list)
  3248. try:
  3249. new_exc_list.remove('txt')
  3250. except ValueError:
  3251. pass
  3252. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3253. if ext_type == 'gcode':
  3254. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3255. if ext_type == 'gerber':
  3256. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3257. if ext_type == 'keyword':
  3258. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3259. # update the self.myKeywords so the model is updated
  3260. self.autocomplete_kw_list = self.default_keywords
  3261. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3262. self.shell._edit.set_model_data(self.myKeywords)
  3263. def delete_all_extensions(self, ext_type):
  3264. """
  3265. Delete all file extensions associations with FlatCAM, for a specific object
  3266. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3267. :return:
  3268. """
  3269. if ext_type == 'excellon':
  3270. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3271. if ext_type == 'gcode':
  3272. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3273. if ext_type == 'gerber':
  3274. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3275. if ext_type == 'keyword':
  3276. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3277. # update the self.myKeywords so the model is updated
  3278. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3279. self.shell._edit.set_model_data(self.myKeywords)
  3280. def on_edit_join(self, name=None):
  3281. """
  3282. Callback for Edit->Join. Joins the selected geometry objects into
  3283. a new one.
  3284. :return: None
  3285. """
  3286. self.defaults.report_usage("on_edit_join()")
  3287. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3288. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3289. geo_type_set = set()
  3290. objs = self.collection.get_selected()
  3291. if len(objs) < 2:
  3292. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3293. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3294. return 'fail'
  3295. for obj in objs:
  3296. geo_type_set.add(obj.multigeo)
  3297. # if len(geo_type_list) == 1 means that all list elements are the same
  3298. if len(geo_type_set) != 1:
  3299. self.inform.emit('[ERROR] %s' %
  3300. _("Failed join. The Geometry objects are of different types.\n"
  3301. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3302. "convert from one to another and retry joining \n"
  3303. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3304. "the result may not be what was expected. \n"
  3305. "Check the generated GCODE."))
  3306. return
  3307. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3308. if True in geo_type_set:
  3309. def initialize(geo_obj, app):
  3310. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3311. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3312. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3313. for v in geo_obj.tools.values():
  3314. v['data']['name'] = obj_name_multi
  3315. self.new_object("geometry", obj_name_multi, initialize)
  3316. else:
  3317. def initialize(geo_obj, app):
  3318. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3319. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3320. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3321. for v in geo_obj.tools.values():
  3322. v['data']['name'] = obj_name_single
  3323. self.new_object("geometry", obj_name_single, initialize)
  3324. self.should_we_save = True
  3325. def on_edit_join_exc(self):
  3326. """
  3327. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3328. a new Excellon.
  3329. :return: None
  3330. """
  3331. self.defaults.report_usage("on_edit_join_exc()")
  3332. objs = self.collection.get_selected()
  3333. for obj in objs:
  3334. if not isinstance(obj, ExcellonObject):
  3335. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3336. return
  3337. if len(objs) < 2:
  3338. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3339. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3340. return 'fail'
  3341. def initialize(exc_obj, app):
  3342. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3343. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3344. self.new_object("excellon", 'Combo_Excellon', initialize)
  3345. self.should_we_save = True
  3346. def on_edit_join_grb(self):
  3347. """
  3348. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3349. a new Gerber object.
  3350. :return: None
  3351. """
  3352. self.defaults.report_usage("on_edit_join_grb()")
  3353. objs = self.collection.get_selected()
  3354. for obj in objs:
  3355. if not isinstance(obj, GerberObject):
  3356. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3357. return
  3358. if len(objs) < 2:
  3359. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3360. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3361. return 'fail'
  3362. def initialize(grb_obj, app):
  3363. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3364. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3365. self.new_object("gerber", 'Combo_Gerber', initialize)
  3366. self.should_we_save = True
  3367. def on_convert_singlegeo_to_multigeo(self):
  3368. """
  3369. Called for converting a Geometry object from single-geo to multi-geo.
  3370. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3371. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3372. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3373. the solid-geometry of that tool.
  3374. :return: None
  3375. """
  3376. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3377. obj = self.collection.get_active()
  3378. if obj is None:
  3379. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3380. return
  3381. if not isinstance(obj, GeometryObject):
  3382. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3383. return
  3384. obj.multigeo = True
  3385. for tooluid, dict_value in obj.tools.items():
  3386. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3387. if not isinstance(obj.solid_geometry, list):
  3388. obj.solid_geometry = [obj.solid_geometry]
  3389. # obj.solid_geometry[:] = []
  3390. obj.plot()
  3391. self.should_we_save = True
  3392. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3393. def on_convert_multigeo_to_singlegeo(self):
  3394. """
  3395. Called for converting a Geometry object from multi-geo to single-geo.
  3396. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3397. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3398. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3399. the solid-geometry of that tool.
  3400. :return: None
  3401. """
  3402. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3403. obj = self.collection.get_active()
  3404. if obj is None:
  3405. self.inform.emit('[ERROR_NOTCL] %s' %
  3406. _("Failed. Select a Geometry Object and try again."))
  3407. return
  3408. if not isinstance(obj, GeometryObject):
  3409. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3410. (_("Expected a GeometryObject, got"), type(obj)))
  3411. return
  3412. obj.multigeo = False
  3413. total_solid_geometry = []
  3414. for tooluid, dict_value in obj.tools.items():
  3415. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3416. # clear the original geometry
  3417. dict_value['solid_geometry'][:] = []
  3418. obj.solid_geometry = deepcopy(total_solid_geometry)
  3419. obj.plot()
  3420. self.should_we_save = True
  3421. self.inform.emit('[success] %s' %
  3422. _("A Geometry object was converted to SingleGeo type."))
  3423. def on_defaults_dict_change(self, field):
  3424. """
  3425. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3426. Edit -> Preferences tab window.
  3427. :param field: the key of the self.defaults dictionary that was changed.
  3428. :return: None
  3429. """
  3430. self.preferencesUiManager.defaults_write_form_field(field=field)
  3431. if field == "units":
  3432. self.set_screen_units(self.defaults['units'])
  3433. def set_screen_units(self, units):
  3434. """
  3435. Set the FlatCAM units on the status bar.
  3436. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3437. :return: None
  3438. """
  3439. self.ui.units_label.setText("[" + units.lower() + "]")
  3440. def on_toggle_units_click(self):
  3441. try:
  3442. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3443. except (TypeError, AttributeError):
  3444. pass
  3445. if self.defaults["units"] == 'MM':
  3446. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3447. else:
  3448. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3449. self.on_toggle_units(no_pref=True)
  3450. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3451. lambda: self.on_toggle_units(no_pref=False))
  3452. def on_toggle_units(self, no_pref=False):
  3453. """
  3454. Callback for the Units radio-button change in the Preferences tab.
  3455. Changes the application's default units adn for the project too.
  3456. If changing the project's units, the change propagates to all of
  3457. the objects in the project.
  3458. :return: None
  3459. """
  3460. self.defaults.report_usage("on_toggle_units")
  3461. if self.toggle_units_ignore:
  3462. return
  3463. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3464. # If option is the same, then ignore
  3465. if new_units == self.defaults["units"].upper():
  3466. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3467. return
  3468. # Options to scale
  3469. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3470. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3471. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3472. "gerber_editor_ma_high",
  3473. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3474. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3475. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3476. "excellon_feedrate_probe", "excellon_milling_dia",
  3477. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3478. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3479. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3480. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3481. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3482. "geometry_extracut_length", "geometry_z_pdepth",
  3483. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3484. 'cncjob_tooldia',
  3485. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3486. "tools_paintnewdia",
  3487. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3488. "tools_nccnewdia", "tools_ncc_offset_value",
  3489. "tools_2sided_drilldia",
  3490. "tools_film_boundary", "tools_film_scale_stroke",
  3491. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3492. "tools_cutout_depthperpass",
  3493. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3494. "tools_panelize_spacing_rows",
  3495. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3496. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3497. "tools_transform_buffer_dis",
  3498. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3499. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3500. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3501. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3502. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3503. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3504. "tools_cr_h2h_val", "tools_cr_dh_val",
  3505. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3506. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3507. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3508. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3509. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3510. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3511. "tools_copper_thieving_mask_clearance",
  3512. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3513. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3514. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3515. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3516. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3517. "tools_invert_margin",
  3518. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3519. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3520. def scale_defaults(sfactor):
  3521. for dim in dimensions:
  3522. if dim == 'gerber_editor_newdim':
  3523. if self.defaults["gerber_editor_newdim"] is None or self.defaults["gerber_editor_newdim"] == '':
  3524. continue
  3525. coordinates = self.defaults["gerber_editor_newdim"].split(",")
  3526. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3527. coords_xy[0] *= sfactor
  3528. coords_xy[1] *= sfactor
  3529. self.defaults['gerber_editor_newdim'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3530. self.decimals, coords_xy[1])
  3531. if dim == 'excellon_toolchangexy':
  3532. if self.defaults["excellon_toolchangexy"] is None or self.defaults["excellon_toolchangexy"] == '':
  3533. continue
  3534. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3535. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3536. coords_xy[0] *= sfactor
  3537. coords_xy[1] *= sfactor
  3538. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3539. self.decimals, coords_xy[1])
  3540. elif dim == 'geometry_toolchangexy':
  3541. if self.defaults["geometry_toolchangexy"] is None or self.defaults["geometry_toolchangexy"] == '':
  3542. continue
  3543. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3544. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3545. coords_xy[0] *= sfactor
  3546. coords_xy[1] *= sfactor
  3547. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3548. self.decimals, coords_xy[1])
  3549. elif dim == 'excellon_endxy':
  3550. if self.defaults["excellon_endxy"] is None or self.defaults["excellon_endxy"] == '':
  3551. continue
  3552. coordinates = self.defaults["excellon_endxy"].split(",")
  3553. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3554. end_coords_xy[0] *= sfactor
  3555. end_coords_xy[1] *= sfactor
  3556. self.defaults['excellon_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3557. self.decimals, end_coords_xy[1])
  3558. elif dim == 'geometry_endxy':
  3559. if self.defaults["geometry_endxy"] is None or self.defaults["geometry_endxy"] == '':
  3560. continue
  3561. coordinates = self.defaults["geometry_endxy"].split(",")
  3562. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3563. end_coords_xy[0] *= sfactor
  3564. end_coords_xy[1] *= sfactor
  3565. self.defaults['geometry_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3566. self.decimals, end_coords_xy[1])
  3567. elif dim == 'geometry_cnctooldia':
  3568. if self.defaults["geometry_cnctooldia"] is None or self.defaults["geometry_cnctooldia"] == '':
  3569. continue
  3570. if type(self.defaults["geometry_cnctooldia"]) is float:
  3571. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  3572. else:
  3573. try:
  3574. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3575. tools_diameters = [eval(a) for a in tools_string if a != '']
  3576. except Exception as e:
  3577. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3578. continue
  3579. self.defaults['geometry_cnctooldia'] = ''
  3580. for t in range(len(tools_diameters)):
  3581. tools_diameters[t] *= sfactor
  3582. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  3583. elif dim == 'tools_ncctools':
  3584. if self.defaults["tools_ncctools"] is None or self.defaults["tools_ncctools"] == '':
  3585. continue
  3586. if type(self.defaults["tools_ncctools"]) == float:
  3587. ncctools = [self.defaults["tools_ncctools"]]
  3588. else:
  3589. try:
  3590. tools_string = self.defaults["tools_ncctools"].split(",")
  3591. ncctools = [eval(a) for a in tools_string if a != '']
  3592. except Exception as e:
  3593. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3594. continue
  3595. self.defaults['tools_ncctools'] = ''
  3596. for t in range(len(ncctools)):
  3597. ncctools[t] *= sfactor
  3598. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  3599. elif dim == 'tools_solderpaste_tools':
  3600. if self.defaults["tools_solderpaste_tools"] is None or \
  3601. self.defaults["tools_solderpaste_tools"] == '':
  3602. continue
  3603. if type(self.defaults["tools_solderpaste_tools"]) == float:
  3604. sptools = [self.defaults["tools_solderpaste_tools"]]
  3605. else:
  3606. try:
  3607. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3608. sptools = [eval(a) for a in tools_string if a != '']
  3609. except Exception as e:
  3610. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3611. continue
  3612. self.defaults['tools_solderpaste_tools'] = ""
  3613. for t in range(len(sptools)):
  3614. sptools[t] *= sfactor
  3615. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  3616. elif dim == 'tools_solderpaste_xy_toolchange':
  3617. if self.defaults["tools_solderpaste_xy_toolchange"] is None or \
  3618. self.defaults["tools_solderpaste_xy_toolchange"] == '':
  3619. continue
  3620. try:
  3621. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3622. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3623. sp_coords[0] *= sfactor
  3624. sp_coords[1] *= sfactor
  3625. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  3626. self.decimals, sp_coords[1])
  3627. except Exception as e:
  3628. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3629. continue
  3630. elif dim == 'tools_cal_toolchange_xy':
  3631. if self.defaults["tools_cal_toolchange_xy"] is None or \
  3632. self.defaults["tools_cal_toolchange_xy"] == '':
  3633. continue
  3634. coordinates = self.defaults["tools_cal_toolchange_xy"].split(",")
  3635. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3636. end_coords_xy[0] *= sfactor
  3637. end_coords_xy[1] *= sfactor
  3638. self.defaults['tools_cal_toolchange_xy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3639. self.decimals, end_coords_xy[1])
  3640. elif dim == 'global_gridx' or dim == 'global_gridy':
  3641. if new_units == 'IN':
  3642. try:
  3643. val = float(self.defaults[dim]) * sfactor
  3644. except Exception as e:
  3645. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3646. continue
  3647. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3648. else:
  3649. try:
  3650. val = float(self.defaults[dim]) * sfactor
  3651. except Exception as e:
  3652. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3653. continue
  3654. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3655. else:
  3656. if self.defaults[dim]:
  3657. try:
  3658. val = float(self.defaults[dim]) * sfactor
  3659. except Exception as e:
  3660. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3661. continue
  3662. self.defaults[dim] = val
  3663. # The scaling factor depending on choice of units.
  3664. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3665. # Changing project units. Warn user.
  3666. msgbox = QtWidgets.QMessageBox()
  3667. msgbox.setWindowTitle(_("Toggle Units"))
  3668. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3669. msgbox.setText(_("Changing the units of the project\n"
  3670. "will scale all objects.\n\n"
  3671. "Do you want to continue?"))
  3672. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3673. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3674. msgbox.setDefaultButton(bt_ok)
  3675. msgbox.exec_()
  3676. response = msgbox.clickedButton()
  3677. if response == bt_ok:
  3678. if no_pref is False:
  3679. self.preferencesUiManager.defaults_read_form()
  3680. scale_defaults(factor)
  3681. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3682. self.defaults["units"] = new_units
  3683. # update the defaults from form, some may assume that the conversion is enough and it's not
  3684. self.on_options_app2project()
  3685. # update the objects
  3686. for obj in self.collection.get_list():
  3687. obj.convert_units(new_units)
  3688. # make that the properties stored in the object are also updated
  3689. self.object_changed.emit(obj)
  3690. # rebuild the object UI
  3691. obj.build_ui()
  3692. # change this only if the workspace is active
  3693. if self.defaults['global_workspace'] is True:
  3694. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3695. # adjust the grid values on the main toolbar
  3696. val_x = float(self.defaults['global_gridx']) * factor
  3697. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3698. current = self.collection.get_active()
  3699. if current is not None:
  3700. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3701. if not isinstance(current, GeometryObject):
  3702. current.to_form()
  3703. # replot all objects
  3704. self.plot_all()
  3705. # set the status labels to reflect the current FlatCAM units
  3706. self.set_screen_units(new_units)
  3707. # signal to the app that we changed the object properties and it shoud save the project
  3708. self.should_we_save = True
  3709. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3710. else:
  3711. # Undo toggling
  3712. self.toggle_units_ignore = True
  3713. if self.defaults['units'].upper() == 'MM':
  3714. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3715. else:
  3716. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3717. self.toggle_units_ignore = False
  3718. # store the grid values so they are not changed in the next step
  3719. val_x = float(self.defaults['global_gridx'])
  3720. val_y = float(self.defaults['global_gridy'])
  3721. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3722. self.preferencesUiManager.defaults_read_form()
  3723. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3724. # in self.defaults from the GUI elements but
  3725. # I don't want it for the grid values, so I update them here
  3726. self.defaults['global_gridx'] = val_x
  3727. self.defaults['global_gridy'] = val_y
  3728. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3729. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3730. def on_fullscreen(self, disable=False):
  3731. self.defaults.report_usage("on_fullscreen()")
  3732. flags = self.ui.windowFlags()
  3733. if self.toggle_fscreen is False and disable is False:
  3734. # self.ui.showFullScreen()
  3735. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3736. a = self.ui.geometry()
  3737. self.x_pos = a.x()
  3738. self.y_pos = a.y()
  3739. self.width = a.width()
  3740. self.height = a.height()
  3741. # set new geometry to full desktop rect
  3742. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3743. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3744. # everything else will not work without this hack. This happen in Windows.
  3745. # https://bugreports.qt.io/browse/QTBUG-41309
  3746. desktop = QtWidgets.QApplication.desktop()
  3747. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3748. rec = desktop.screenGeometry(screen)
  3749. x = rec.x() - 1
  3750. y = rec.y() - 1
  3751. h = rec.height() + 2
  3752. w = rec.width() + 2
  3753. self.ui.setGeometry(x, y, w, h)
  3754. self.ui.show()
  3755. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3756. tb.setVisible(False)
  3757. self.ui.splitter_left.setVisible(False)
  3758. self.toggle_fscreen = True
  3759. elif self.toggle_fscreen is True or disable is True:
  3760. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3761. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3762. self.ui.showNormal()
  3763. self.restore_toolbar_view()
  3764. self.ui.splitter_left.setVisible(True)
  3765. self.toggle_fscreen = False
  3766. def on_toggle_plotarea(self):
  3767. self.defaults.report_usage("on_toggle_plotarea()")
  3768. try:
  3769. name = self.ui.plot_tab_area.widget(0).objectName()
  3770. except AttributeError:
  3771. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3772. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3773. self.ui.plot_tab_area.protectTab(0)
  3774. return
  3775. if name != 'plotarea_tab':
  3776. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3777. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3778. self.ui.plot_tab_area.protectTab(0)
  3779. else:
  3780. self.ui.plot_tab_area.closeTab(0)
  3781. def on_toggle_notebook(self):
  3782. if self.ui.splitter.sizes()[0] == 0:
  3783. self.ui.splitter.setSizes([1, 1])
  3784. self.ui.menu_toggle_nb.setChecked(True)
  3785. else:
  3786. self.ui.splitter.setSizes([0, 1])
  3787. self.ui.menu_toggle_nb.setChecked(False)
  3788. def on_toggle_axis(self):
  3789. self.defaults.report_usage("on_toggle_axis()")
  3790. if self.toggle_axis is False:
  3791. if self.is_legacy is False:
  3792. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3793. parent=self.plotcanvas.view.scene)
  3794. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3795. parent=self.plotcanvas.view.scene)
  3796. else:
  3797. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3798. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3799. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3800. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3801. self.plotcanvas.canvas.draw()
  3802. self.toggle_axis = True
  3803. else:
  3804. if self.is_legacy is False:
  3805. self.plotcanvas.v_line.parent = None
  3806. self.plotcanvas.h_line.parent = None
  3807. else:
  3808. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3809. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3810. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3811. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3812. self.plotcanvas.canvas.draw()
  3813. self.toggle_axis = False
  3814. def on_toggle_grid(self):
  3815. self.defaults.report_usage("on_toggle_grid()")
  3816. self.ui.grid_snap_btn.trigger()
  3817. self.ui.on_grid_snap_triggered(state=True)
  3818. def on_toggle_grid_lines(self):
  3819. self.defaults.report_usage("on_toggle_grd_lines()")
  3820. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3821. if tt_settings.contains("theme"):
  3822. theme = tt_settings.value('theme', type=str)
  3823. else:
  3824. theme = 'white'
  3825. if self.toggle_grid_lines is False:
  3826. if self.is_legacy is False:
  3827. if theme == 'white':
  3828. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3829. else:
  3830. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3831. else:
  3832. self.plotcanvas.axes.grid(True)
  3833. try:
  3834. self.plotcanvas.canvas.draw()
  3835. except IndexError:
  3836. pass
  3837. pass
  3838. self.toggle_grid_lines = True
  3839. else:
  3840. if self.is_legacy is False:
  3841. if theme == 'white':
  3842. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3843. else:
  3844. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3845. else:
  3846. self.plotcanvas.axes.grid(False)
  3847. try:
  3848. self.plotcanvas.canvas.draw()
  3849. except IndexError:
  3850. pass
  3851. self.toggle_grid_lines = False
  3852. if self.is_legacy is False:
  3853. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3854. # - perhaps is a bug in VisPy implementation
  3855. if self.grid_status() is True:
  3856. self.app_cursor.enabled = False
  3857. self.app_cursor.enabled = True
  3858. else:
  3859. self.app_cursor.enabled = True
  3860. self.app_cursor.enabled = False
  3861. def on_update_exc_export(self, state):
  3862. """
  3863. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3864. if the update_excellon_cb checkbox is checked
  3865. :param state: state of the checkbox whose signals is tied to his slot
  3866. :return:
  3867. """
  3868. if state:
  3869. # first try to disconnect
  3870. try:
  3871. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3872. disconnect(self.on_excellon_format_changed)
  3873. except TypeError:
  3874. pass
  3875. try:
  3876. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3877. disconnect(self.on_excellon_format_changed)
  3878. except TypeError:
  3879. pass
  3880. try:
  3881. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3882. disconnect(self.on_excellon_format_changed)
  3883. except TypeError:
  3884. pass
  3885. try:
  3886. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3887. disconnect(self.on_excellon_format_changed)
  3888. except TypeError:
  3889. pass
  3890. try:
  3891. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3892. disconnect(self.on_excellon_zeros_changed)
  3893. except TypeError:
  3894. pass
  3895. try:
  3896. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3897. disconnect(self.on_excellon_zeros_changed)
  3898. except TypeError:
  3899. pass
  3900. # the connect them
  3901. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3902. self.on_excellon_format_changed)
  3903. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3904. self.on_excellon_format_changed)
  3905. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3906. self.on_excellon_format_changed)
  3907. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3908. self.on_excellon_format_changed)
  3909. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3910. self.on_excellon_zeros_changed)
  3911. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3912. self.on_excellon_units_changed)
  3913. else:
  3914. # disconnect the signals
  3915. try:
  3916. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3917. disconnect(self.on_excellon_format_changed)
  3918. except TypeError:
  3919. pass
  3920. try:
  3921. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3922. disconnect(self.on_excellon_format_changed)
  3923. except TypeError:
  3924. pass
  3925. try:
  3926. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3927. disconnect(self.on_excellon_format_changed)
  3928. except TypeError:
  3929. pass
  3930. try:
  3931. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3932. disconnect(self.on_excellon_format_changed)
  3933. except TypeError:
  3934. pass
  3935. try:
  3936. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3937. disconnect(self.on_excellon_zeros_changed)
  3938. except TypeError:
  3939. pass
  3940. try:
  3941. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3942. disconnect(self.on_excellon_zeros_changed)
  3943. except TypeError:
  3944. pass
  3945. def on_excellon_format_changed(self):
  3946. """
  3947. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3948. :return: None
  3949. """
  3950. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3951. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3952. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3953. )
  3954. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3955. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3956. )
  3957. else:
  3958. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3959. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3960. )
  3961. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3962. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3963. )
  3964. def on_excellon_zeros_changed(self):
  3965. """
  3966. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3967. :return: None
  3968. """
  3969. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3970. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3971. )
  3972. def on_excellon_units_changed(self):
  3973. """
  3974. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3975. :return: None
  3976. """
  3977. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3978. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3979. )
  3980. self.on_excellon_format_changed()
  3981. def on_film_color_entry(self):
  3982. self.defaults['tools_film_color'] = \
  3983. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3984. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3985. "background-color:%s;"
  3986. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3987. )
  3988. def on_film_color_button(self):
  3989. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3990. c_dialog = QtWidgets.QColorDialog()
  3991. film_color = c_dialog.getColor(initial=current_color)
  3992. if film_color.isValid() is False:
  3993. return
  3994. # if new color is different then mark that the Preferences are changed
  3995. if film_color != current_color:
  3996. self.preferencesUiManager.on_preferences_edited()
  3997. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3998. "background-color:%s;"
  3999. "border-color: dimgray" % str(film_color.name())
  4000. )
  4001. new_val_sel = str(film_color.name())
  4002. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  4003. self.defaults['tools_film_color'] = new_val_sel
  4004. def on_qrcode_fill_color_entry(self):
  4005. self.defaults['tools_qrcode_fill_color'] = \
  4006. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  4007. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4008. "background-color:%s;"
  4009. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  4010. )
  4011. def on_qrcode_fill_color_button(self):
  4012. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  4013. c_dialog = QtWidgets.QColorDialog()
  4014. fill_color = c_dialog.getColor(initial=current_color)
  4015. if fill_color.isValid() is False:
  4016. return
  4017. # if new color is different then mark that the Preferences are changed
  4018. if fill_color != current_color:
  4019. self.preferencesUiManager.on_preferences_edited()
  4020. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4021. "background-color:%s;"
  4022. "border-color: dimgray" % str(fill_color.name())
  4023. )
  4024. new_val_sel = str(fill_color.name())
  4025. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  4026. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  4027. def on_qrcode_back_color_entry(self):
  4028. self.defaults['tools_qrcode_back_color'] = \
  4029. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  4030. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4031. "background-color:%s;"
  4032. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  4033. )
  4034. def on_qrcode_back_color_button(self):
  4035. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  4036. c_dialog = QtWidgets.QColorDialog()
  4037. back_color = c_dialog.getColor(initial=current_color)
  4038. if back_color.isValid() is False:
  4039. return
  4040. # if new color is different then mark that the Preferences are changed
  4041. if back_color != current_color:
  4042. self.preferencesUiManager.on_preferences_edited()
  4043. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4044. "background-color:%s;"
  4045. "border-color: dimgray" % str(back_color.name())
  4046. )
  4047. new_val_sel = str(back_color.name())
  4048. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  4049. self.defaults['tools_qrcode_back_color'] = new_val_sel
  4050. def on_tab_rmb_click(self, checked):
  4051. self.ui.notebook.set_detachable(val=checked)
  4052. self.defaults["global_tabs_detachable"] = checked
  4053. self.ui.plot_tab_area.set_detachable(val=checked)
  4054. self.defaults["global_tabs_detachable"] = checked
  4055. def on_tab_setup_context_menu(self):
  4056. initial_checked = self.defaults["global_tabs_detachable"]
  4057. action_name = str(_("Detachable Tabs"))
  4058. action = QtWidgets.QAction(self)
  4059. action.setCheckable(True)
  4060. action.setText(action_name)
  4061. action.setChecked(initial_checked)
  4062. self.ui.notebook.tabBar.addAction(action)
  4063. self.ui.plot_tab_area.tabBar.addAction(action)
  4064. try:
  4065. action.triggered.disconnect()
  4066. except TypeError:
  4067. pass
  4068. action.triggered.connect(self.on_tab_rmb_click)
  4069. def on_deselect_all(self):
  4070. self.collection.set_all_inactive()
  4071. self.delete_selection_shape()
  4072. def on_workspace_modified(self):
  4073. # self.save_defaults(silent=True)
  4074. if self.is_legacy is True:
  4075. self.plotcanvas.delete_workspace()
  4076. self.preferencesUiManager.defaults_read_form()
  4077. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4078. def on_workspace(self):
  4079. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4080. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4081. else:
  4082. self.plotcanvas.delete_workspace()
  4083. self.preferencesUiManager.defaults_read_form()
  4084. # self.save_defaults(silent=True)
  4085. def on_workspace_toggle(self):
  4086. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4087. try:
  4088. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4089. except TypeError:
  4090. pass
  4091. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4092. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4093. self.on_workspace()
  4094. def on_cursor_type(self, val):
  4095. """
  4096. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4097. :return: None
  4098. """
  4099. self.app_cursor.enabled = False
  4100. if val == 'small':
  4101. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4102. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4103. self.app_cursor = self.plotcanvas.new_cursor()
  4104. else:
  4105. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4106. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4107. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4108. if self.ui.grid_snap_btn.isChecked():
  4109. self.app_cursor.enabled = True
  4110. else:
  4111. self.app_cursor.enabled = False
  4112. def on_tool_add_keypress(self):
  4113. # ## Current application units in Upper Case
  4114. self.units = self.defaults['units'].upper()
  4115. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4116. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4117. if notebook_widget_name == 'selected_tab':
  4118. if self.collection.get_active().kind == 'geometry':
  4119. # Tool add works for Geometry only if Advanced is True in Preferences
  4120. if self.defaults["global_app_level"] == 'a':
  4121. tool_add_popup = FCInputDialog(title="New Tool ...",
  4122. text='Enter a Tool Diameter:',
  4123. min=0.0000, max=99.9999, decimals=4)
  4124. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4125. val, ok = tool_add_popup.get_value()
  4126. if ok:
  4127. if float(val) == 0:
  4128. self.inform.emit('[WARNING_NOTCL] %s' %
  4129. _("Please enter a tool diameter with non-zero value, in Float format."))
  4130. return
  4131. self.collection.get_active().on_tool_add(dia=float(val))
  4132. else:
  4133. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4134. else:
  4135. msgbox = QtWidgets.QMessageBox()
  4136. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4137. "Go to Preferences -> General - Show Advanced Options."))
  4138. msgbox.setWindowTitle("Tool adding ...")
  4139. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4140. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4141. msgbox.setDefaultButton(bt_ok)
  4142. msgbox.exec_()
  4143. # work only if the notebook tab on focus is the Tools_Tab
  4144. if notebook_widget_name == 'tool_tab':
  4145. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4146. # and only if the tool is NCC Tool
  4147. if tool_widget == self.ncclear_tool.toolName:
  4148. self.ncclear_tool.on_add_tool_by_key()
  4149. # and only if the tool is Paint Area Tool
  4150. elif tool_widget == self.paint_tool.toolName:
  4151. self.paint_tool.on_add_tool_by_key()
  4152. # and only if the tool is Solder Paste Dispensing Tool
  4153. elif tool_widget == self.paste_tool.toolName:
  4154. self.paste_tool.on_add_tool_by_key()
  4155. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4156. # See description below.
  4157. def on_delete_keypress(self):
  4158. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4159. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4160. if notebook_widget_name == 'selected_tab':
  4161. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4162. self.collection.get_active().on_tool_delete()
  4163. # work only if the notebook tab on focus is the Tools_Tab
  4164. elif notebook_widget_name == 'tool_tab':
  4165. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4166. # and only if the tool is NCC Tool
  4167. if tool_widget == self.ncclear_tool.toolName:
  4168. self.ncclear_tool.on_tool_delete()
  4169. # and only if the tool is Paint Tool
  4170. elif tool_widget == self.paint_tool.toolName:
  4171. self.paint_tool.on_tool_delete()
  4172. # and only if the tool is Solder Paste Dispensing Tool
  4173. elif tool_widget == self.paste_tool.toolName:
  4174. self.paste_tool.on_tool_delete()
  4175. else:
  4176. self.on_delete()
  4177. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4178. # some screens you have to be careful where you hover with your mouse.
  4179. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4180. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4181. # Complicated, I know :)
  4182. def on_delete(self, force_deletion=False):
  4183. """
  4184. Delete the currently selected FlatCAMObjs.
  4185. :param force_deletion: used by Tcl command
  4186. :return: None
  4187. """
  4188. self.defaults.report_usage("on_delete()")
  4189. response = None
  4190. bt_ok = None
  4191. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4192. # a geometry object before we update it.
  4193. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4194. and self.grb_editor.editor_active is False:
  4195. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4196. msgbox = QtWidgets.QMessageBox()
  4197. msgbox.setWindowTitle(_("Delete objects"))
  4198. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4199. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4200. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4201. "the selected objects?"))
  4202. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4203. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4204. msgbox.setDefaultButton(bt_ok)
  4205. msgbox.exec_()
  4206. response = msgbox.clickedButton()
  4207. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4208. response = bt_ok
  4209. if response == bt_ok:
  4210. if self.collection.get_active():
  4211. self.log.debug("App.on_delete()")
  4212. for obj_active in self.collection.get_selected():
  4213. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4214. if obj_active.kind == 'gerber':
  4215. for el in obj_active.mark_shapes:
  4216. obj_active.mark_shapes[el].clear(update=True)
  4217. obj_active.mark_shapes[el].enabled = False
  4218. # obj_active.mark_shapes[el] = None
  4219. del el
  4220. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4221. if obj_active.kind == 'geometry':
  4222. obj_active.exclusion_shapes.clear(update=True)
  4223. obj_active.exclusion_shapes.enabled = False
  4224. del obj_active.exclusion_shapes
  4225. elif isinstance(obj_active, CNCJobObject):
  4226. try:
  4227. obj_active.text_col.enabled = False
  4228. del obj_active.text_col
  4229. obj_active.annotation.clear(update=True)
  4230. del obj_active.annotation
  4231. except AttributeError as e:
  4232. log.debug(
  4233. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4234. )
  4235. while self.collection.get_selected():
  4236. self.delete_first_selected()
  4237. self.inform.emit('%s...' % _("Object(s) deleted"))
  4238. # make sure that the selection shape is deleted, too
  4239. self.delete_selection_shape()
  4240. else:
  4241. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4242. else:
  4243. self.inform.emit(_("Save the work in Editor and try again ..."))
  4244. def delete_first_selected(self):
  4245. # Keep this for later
  4246. try:
  4247. sel_obj = self.collection.get_active()
  4248. name = sel_obj.options["name"]
  4249. isPlotted = sel_obj.options["plot"]
  4250. except AttributeError:
  4251. self.log.debug("Nothing selected for deletion")
  4252. return
  4253. if self.is_legacy is True:
  4254. # Remove plot only if the object was plotted otherwise delaxes will fail
  4255. if isPlotted:
  4256. try:
  4257. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4258. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4259. except Exception as e:
  4260. log.debug("App.delete_first_selected() --> %s" % str(e))
  4261. self.plotcanvas.auto_adjust_axes()
  4262. # Remove from dictionary
  4263. self.collection.delete_active()
  4264. # Clear form
  4265. self.setup_component_editor()
  4266. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4267. def on_set_origin(self):
  4268. """
  4269. Set the origin to the left mouse click position
  4270. :return: None
  4271. """
  4272. # display the message for the user
  4273. # and ask him to click on the desired position
  4274. self.defaults.report_usage("on_set_origin()")
  4275. def origin_replot():
  4276. def worker_task():
  4277. with self.proc_container.new('%s...' % _("Plotting")):
  4278. for obj in self.collection.get_list():
  4279. obj.plot()
  4280. self.plotcanvas.fit_view()
  4281. if self.is_legacy:
  4282. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4283. else:
  4284. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4285. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4286. self.inform.emit(_('Click to set the origin ...'))
  4287. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4288. # first disconnect it as it may have been used by something else
  4289. try:
  4290. self.replot_signal.disconnect()
  4291. except TypeError:
  4292. pass
  4293. self.replot_signal[list].connect(origin_replot)
  4294. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4295. """
  4296. :param event:
  4297. :param location:
  4298. :param noplot:
  4299. :param use_thread:
  4300. :return:
  4301. """
  4302. noplot_sig = noplot
  4303. def worker_task():
  4304. with self.proc_container.new(_("Setting Origin...")):
  4305. obj_list = self.collection.get_list()
  4306. for obj in obj_list:
  4307. obj.offset((x, y))
  4308. self.object_changed.emit(obj)
  4309. # Update the object bounding box options
  4310. a, b, c, d = obj.bounds()
  4311. obj.options['xmin'] = a
  4312. obj.options['ymin'] = b
  4313. obj.options['xmax'] = c
  4314. obj.options['ymax'] = d
  4315. self.inform.emit('[success] %s...' % _('Origin set'))
  4316. for obj in obj_list:
  4317. out_name = obj.options["name"]
  4318. if obj.kind == 'gerber':
  4319. obj.source_file = self.export_gerber(
  4320. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4321. elif obj.kind == 'excellon':
  4322. obj.source_file = self.export_excellon(
  4323. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4324. if noplot_sig is False:
  4325. self.replot_signal.emit([])
  4326. if location is not None:
  4327. if len(location) != 2:
  4328. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4329. return 'fail'
  4330. x, y = location
  4331. if use_thread is True:
  4332. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4333. else:
  4334. worker_task()
  4335. self.should_we_save = True
  4336. return
  4337. if event.button == 1:
  4338. if self.is_legacy is False:
  4339. event_pos = event.pos
  4340. else:
  4341. event_pos = (event.xdata, event.ydata)
  4342. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4343. if self.grid_status():
  4344. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4345. else:
  4346. pos = pos_canvas
  4347. x = 0 - pos[0]
  4348. y = 0 - pos[1]
  4349. if use_thread is True:
  4350. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4351. else:
  4352. worker_task()
  4353. self.should_we_save = True
  4354. def on_move2origin(self, use_thread=True):
  4355. """
  4356. Move selected objects to origin.
  4357. :param use_thread: Control if to use threaded operation. Boolean.
  4358. :return:
  4359. """
  4360. def worker_task():
  4361. with self.proc_container.new(_("Moving to Origin...")):
  4362. obj_list = self.collection.get_selected()
  4363. if not obj_list:
  4364. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4365. return
  4366. xminlist = []
  4367. yminlist = []
  4368. # first get a bounding box to fit all
  4369. for obj in obj_list:
  4370. xmin, ymin, xmax, ymax = obj.bounds()
  4371. xminlist.append(xmin)
  4372. yminlist.append(ymin)
  4373. # get the minimum x,y for all objects selected
  4374. x = min(xminlist)
  4375. y = min(yminlist)
  4376. for obj in obj_list:
  4377. obj.offset((-x, -y))
  4378. self.object_changed.emit(obj)
  4379. # Update the object bounding box options
  4380. a, b, c, d = obj.bounds()
  4381. obj.options['xmin'] = a
  4382. obj.options['ymin'] = b
  4383. obj.options['xmax'] = c
  4384. obj.options['ymax'] = d
  4385. for obj in obj_list:
  4386. obj.plot()
  4387. for obj in obj_list:
  4388. out_name = obj.options["name"]
  4389. if obj.kind == 'gerber':
  4390. obj.source_file = self.export_gerber(
  4391. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4392. elif obj.kind == 'excellon':
  4393. obj.source_file = self.export_excellon(
  4394. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4395. self.inform.emit('[success] %s...' % _('Origin set'))
  4396. if use_thread is True:
  4397. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4398. else:
  4399. worker_task()
  4400. self.should_we_save = True
  4401. def on_jump_to(self, custom_location=None, fit_center=True):
  4402. """
  4403. Jump to a location by setting the mouse cursor location.
  4404. :param custom_location: Jump to a specified point. (x, y) tuple.
  4405. :param fit_center: If to fit view. Boolean.
  4406. :return:
  4407. """
  4408. self.defaults.report_usage("on_jump_to()")
  4409. if not custom_location:
  4410. dia_box_location = None
  4411. try:
  4412. dia_box_location = eval(self.clipboard.text())
  4413. except Exception:
  4414. pass
  4415. if type(dia_box_location) == tuple:
  4416. dia_box_location = str(dia_box_location)
  4417. else:
  4418. dia_box_location = None
  4419. # dia_box = Dialog_box(title=_("Jump to ..."),
  4420. # label=_("Enter the coordinates in format X,Y:"),
  4421. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4422. # initial_text=dia_box_location)
  4423. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4424. label=_("Enter the coordinates in format X,Y:"),
  4425. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4426. initial_text=dia_box_location,
  4427. reference=self.defaults['global_jump_ref'])
  4428. if dia_box.ok is True:
  4429. try:
  4430. location = eval(dia_box.location)
  4431. if not isinstance(location, tuple):
  4432. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4433. return
  4434. if dia_box.reference == 'rel':
  4435. rel_x = self.mouse[0] + location[0]
  4436. rel_y = self.mouse[1] + location[1]
  4437. location = (rel_x, rel_y)
  4438. self.defaults['global_jump_ref'] = dia_box.reference
  4439. except Exception:
  4440. return
  4441. else:
  4442. return
  4443. else:
  4444. location = custom_location
  4445. self.jump_signal.emit(location)
  4446. if fit_center:
  4447. self.plotcanvas.fit_center(loc=location)
  4448. cursor = QtGui.QCursor()
  4449. if self.is_legacy is False:
  4450. # I don't know where those differences come from but they are constant for the current
  4451. # execution of the application and they are multiples of a value around 0.0263mm.
  4452. # In a random way sometimes they are more sometimes they are less
  4453. # if units == 'MM':
  4454. # cal_factor = 0.0263
  4455. # else:
  4456. # cal_factor = 0.0263 / 25.4
  4457. cal_location = (location[0], location[1])
  4458. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4459. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4460. j_pos = (
  4461. int(canvas_origin.x() + round(jump_loc[0])),
  4462. int(canvas_origin.y() + round(jump_loc[1]))
  4463. )
  4464. cursor.setPos(j_pos[0], j_pos[1])
  4465. else:
  4466. # find the canvas origin which is in the top left corner
  4467. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4468. # determine the coordinates for the lowest left point of the canvas
  4469. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4470. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4471. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4472. # canvas) and the point (width, height) is in the top-right location
  4473. loc = self.plotcanvas.axes.transData.transform_point(location)
  4474. j_pos = (
  4475. int(x0 + loc[0]),
  4476. int(y0 - loc[1])
  4477. )
  4478. cursor.setPos(j_pos[0], j_pos[1])
  4479. self.plotcanvas.mouse = [location[0], location[1]]
  4480. if self.defaults["global_cursor_color_enabled"] is True:
  4481. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4482. else:
  4483. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4484. if self.grid_status():
  4485. # Update cursor
  4486. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4487. symbol='++', edge_color=self.cursor_color_3D,
  4488. edge_width=self.defaults["global_cursor_width"],
  4489. size=self.defaults["global_cursor_size"])
  4490. # Set the position label
  4491. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4492. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4493. # Set the relative position label
  4494. dx = location[0] - float(self.rel_point1[0])
  4495. dy = location[1] - float(self.rel_point1[1])
  4496. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4497. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4498. self.inform.emit('[success] %s' % _("Done."))
  4499. return location
  4500. def on_locate(self, obj, fit_center=True):
  4501. """
  4502. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4503. :param obj: The object on which to locate certain points
  4504. :param fit_center: If to fit view. Boolean.
  4505. :return: A point location. (x, y) tuple.
  4506. """
  4507. self.defaults.report_usage("on_locate()")
  4508. if obj is None:
  4509. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4510. return 'fail'
  4511. class DialogBoxChoice(QtWidgets.QDialog):
  4512. def __init__(self, title=None, icon=None, choice='bl'):
  4513. """
  4514. :param title: string with the window title
  4515. """
  4516. super(DialogBoxChoice, self).__init__()
  4517. self.ok = False
  4518. self.setWindowIcon(icon)
  4519. self.setWindowTitle(str(title))
  4520. self.form = QtWidgets.QFormLayout(self)
  4521. self.ref_radio = RadioSet([
  4522. {"label": _("Bottom-Left"), "value": "bl"},
  4523. {"label": _("Top-Left"), "value": "tl"},
  4524. {"label": _("Bottom-Right"), "value": "br"},
  4525. {"label": _("Top-Right"), "value": "tr"},
  4526. {"label": _("Center"), "value": "c"}
  4527. ], orientation='vertical', stretch=False)
  4528. self.ref_radio.set_value(choice)
  4529. self.form.addRow(self.ref_radio)
  4530. self.button_box = QtWidgets.QDialogButtonBox(
  4531. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4532. Qt.Horizontal, parent=self)
  4533. self.form.addRow(self.button_box)
  4534. self.button_box.accepted.connect(self.accept)
  4535. self.button_box.rejected.connect(self.reject)
  4536. if self.exec_() == QtWidgets.QDialog.Accepted:
  4537. self.ok = True
  4538. self.location_point = self.ref_radio.get_value()
  4539. else:
  4540. self.ok = False
  4541. self.location_point = None
  4542. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4543. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4544. choice=self.defaults['global_locate_pt'])
  4545. if dia_box.ok is True:
  4546. try:
  4547. location_point = dia_box.location_point
  4548. self.defaults['global_locate_pt'] = dia_box.location_point
  4549. except Exception:
  4550. return
  4551. else:
  4552. return
  4553. loc_b = obj.bounds()
  4554. if location_point == 'bl':
  4555. location = (loc_b[0], loc_b[1])
  4556. elif location_point == 'tl':
  4557. location = (loc_b[0], loc_b[3])
  4558. elif location_point == 'br':
  4559. location = (loc_b[2], loc_b[1])
  4560. elif location_point == 'tr':
  4561. location = (loc_b[2], loc_b[3])
  4562. else:
  4563. # center
  4564. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4565. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4566. location = (cx, cy)
  4567. self.locate_signal.emit(location, location_point)
  4568. if fit_center:
  4569. self.plotcanvas.fit_center(loc=location)
  4570. cursor = QtGui.QCursor()
  4571. if self.is_legacy is False:
  4572. # I don't know where those differences come from but they are constant for the current
  4573. # execution of the application and they are multiples of a value around 0.0263mm.
  4574. # In a random way sometimes they are more sometimes they are less
  4575. # if units == 'MM':
  4576. # cal_factor = 0.0263
  4577. # else:
  4578. # cal_factor = 0.0263 / 25.4
  4579. cal_location = (location[0], location[1])
  4580. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4581. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4582. j_pos = (
  4583. int(canvas_origin.x() + round(jump_loc[0])),
  4584. int(canvas_origin.y() + round(jump_loc[1]))
  4585. )
  4586. cursor.setPos(j_pos[0], j_pos[1])
  4587. else:
  4588. # find the canvas origin which is in the top left corner
  4589. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4590. # determine the coordinates for the lowest left point of the canvas
  4591. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4592. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4593. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4594. # canvas) and the point (width, height) is in the top-right location
  4595. loc = self.plotcanvas.axes.transData.transform_point(location)
  4596. j_pos = (
  4597. int(x0 + loc[0]),
  4598. int(y0 - loc[1])
  4599. )
  4600. cursor.setPos(j_pos[0], j_pos[1])
  4601. self.plotcanvas.mouse = [location[0], location[1]]
  4602. if self.defaults["global_cursor_color_enabled"] is True:
  4603. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4604. else:
  4605. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4606. if self.grid_status():
  4607. # Update cursor
  4608. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4609. symbol='++', edge_color=self.cursor_color_3D,
  4610. edge_width=self.defaults["global_cursor_width"],
  4611. size=self.defaults["global_cursor_size"])
  4612. # Set the position label
  4613. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4614. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4615. # Set the relative position label
  4616. self.dx = location[0] - float(self.rel_point1[0])
  4617. self.dy = location[1] - float(self.rel_point1[1])
  4618. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4619. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4620. self.inform.emit('[success] %s' % _("Done."))
  4621. return location
  4622. def on_copy_command(self):
  4623. """
  4624. Will copy a selection of objects, creating new objects.
  4625. :return:
  4626. """
  4627. self.defaults.report_usage("on_copy_command()")
  4628. def initialize(obj_init, app):
  4629. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4630. try:
  4631. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4632. except AttributeError:
  4633. pass
  4634. try:
  4635. obj_init.apertures = deepcopy(obj.apertures)
  4636. except AttributeError:
  4637. pass
  4638. try:
  4639. if obj.tools:
  4640. obj_init.tools = deepcopy(obj.tools)
  4641. except Exception as err:
  4642. log.debug("App.on_copy_command() --> %s" % str(err))
  4643. try:
  4644. obj_init.source_file = deepcopy(obj.source_file)
  4645. except (AttributeError, TypeError):
  4646. pass
  4647. def initialize_excellon(obj_init, app):
  4648. obj_init.source_file = deepcopy(obj.source_file)
  4649. obj_init.tools = deepcopy(obj.tools)
  4650. # drills are offset, so they need to be deep copied
  4651. obj_init.drills = deepcopy(obj.drills)
  4652. # slots are offset, so they need to be deep copied
  4653. obj_init.slots = deepcopy(obj.slots)
  4654. obj_init.create_geometry()
  4655. def initialize_script(obj_init, app_obj):
  4656. obj_init.source_file = deepcopy(obj.source_file)
  4657. def initialize_document(obj_init, app_obj):
  4658. obj_init.source_file = deepcopy(obj.source_file)
  4659. for obj in self.collection.get_selected():
  4660. obj_name = obj.options["name"]
  4661. try:
  4662. if isinstance(obj, ExcellonObject):
  4663. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4664. elif isinstance(obj, GerberObject):
  4665. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4666. elif isinstance(obj, GeometryObject):
  4667. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4668. elif isinstance(obj, ScriptObject):
  4669. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4670. elif isinstance(obj, DocumentObject):
  4671. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4672. except Exception as e:
  4673. return "Operation failed: %s" % str(e)
  4674. def on_copy_object2(self, custom_name):
  4675. def initialize_geometry(obj_init, app):
  4676. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4677. try:
  4678. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4679. except AttributeError:
  4680. pass
  4681. try:
  4682. obj_init.apertures = deepcopy(obj.apertures)
  4683. except AttributeError:
  4684. pass
  4685. try:
  4686. if obj.tools:
  4687. obj_init.tools = deepcopy(obj.tools)
  4688. except Exception as ee:
  4689. log.debug("on_copy_object2() --> %s" % str(ee))
  4690. def initialize_gerber(obj_init, app):
  4691. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4692. obj_init.apertures = deepcopy(obj.apertures)
  4693. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4694. def initialize_excellon(obj_init, app):
  4695. obj_init.tools = deepcopy(obj.tools)
  4696. # drills are offset, so they need to be deep copied
  4697. obj_init.drills = deepcopy(obj.drills)
  4698. # slots are offset, so they need to be deep copied
  4699. obj_init.slots = deepcopy(obj.slots)
  4700. obj_init.create_geometry()
  4701. for obj in self.collection.get_selected():
  4702. obj_name = obj.options["name"]
  4703. try:
  4704. if isinstance(obj, ExcellonObject):
  4705. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4706. elif isinstance(obj, GerberObject):
  4707. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4708. elif isinstance(obj, GeometryObject):
  4709. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4710. except Exception as er:
  4711. return "Operation failed: %s" % str(er)
  4712. def on_rename_object(self, text):
  4713. """
  4714. Will rename an object.
  4715. :param text: New name for the object.
  4716. :return:
  4717. """
  4718. self.defaults.report_usage("on_rename_object()")
  4719. named_obj = self.collection.get_active()
  4720. for obj in named_obj:
  4721. if obj is list:
  4722. self.on_rename_object(text)
  4723. else:
  4724. try:
  4725. obj.options['name'] = text
  4726. except Exception as e:
  4727. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4728. def convert_any2geo(self):
  4729. """
  4730. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4731. :return:
  4732. """
  4733. self.defaults.report_usage("convert_any2geo()")
  4734. def initialize(obj_init, app):
  4735. obj_init.solid_geometry = obj.solid_geometry
  4736. try:
  4737. obj_init.follow_geometry = obj.follow_geometry
  4738. except AttributeError:
  4739. pass
  4740. try:
  4741. obj_init.apertures = obj.apertures
  4742. except AttributeError:
  4743. pass
  4744. try:
  4745. if obj.tools:
  4746. obj_init.tools = obj.tools
  4747. except AttributeError:
  4748. pass
  4749. def initialize_excellon(obj_init, app):
  4750. # objs = self.collection.get_selected()
  4751. # GeometryObject.merge(objs, obj)
  4752. solid_geo = []
  4753. for tool in obj.tools:
  4754. for geo in obj.tools[tool]['solid_geometry']:
  4755. solid_geo.append(geo)
  4756. obj_init.solid_geometry = deepcopy(solid_geo)
  4757. if not self.collection.get_selected():
  4758. log.warning("App.convert_any2geo --> No object selected")
  4759. self.inform.emit('[WARNING_NOTCL] %s' %
  4760. _("No object is selected. Select an object and try again."))
  4761. return
  4762. for obj in self.collection.get_selected():
  4763. obj_name = obj.options["name"]
  4764. try:
  4765. if isinstance(obj, ExcellonObject):
  4766. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4767. else:
  4768. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4769. except Exception as e:
  4770. return "Operation failed: %s" % str(e)
  4771. def convert_any2gerber(self):
  4772. """
  4773. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4774. :return:
  4775. """
  4776. self.defaults.report_usage("convert_any2gerber()")
  4777. def initialize_geometry(obj_init, app):
  4778. apertures = {}
  4779. apid = 0
  4780. apertures[str(apid)] = {}
  4781. apertures[str(apid)]['geometry'] = []
  4782. for obj_orig in obj.solid_geometry:
  4783. new_elem = {}
  4784. new_elem['solid'] = obj_orig
  4785. try:
  4786. new_elem['follow'] = obj_orig.exterior
  4787. except AttributeError:
  4788. pass
  4789. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4790. apertures[str(apid)]['size'] = 0.0
  4791. apertures[str(apid)]['type'] = 'C'
  4792. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4793. obj_init.apertures = deepcopy(apertures)
  4794. def initialize_excellon(obj_init, app):
  4795. apertures = {}
  4796. apid = 10
  4797. for tool in obj.tools:
  4798. apertures[str(apid)] = {}
  4799. apertures[str(apid)]['geometry'] = []
  4800. for geo in obj.tools[tool]['solid_geometry']:
  4801. new_el = {}
  4802. new_el['solid'] = geo
  4803. new_el['follow'] = geo.exterior
  4804. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4805. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4806. apertures[str(apid)]['type'] = 'C'
  4807. apid += 1
  4808. # create solid_geometry
  4809. solid_geometry = []
  4810. for apid in apertures:
  4811. for geo_el in apertures[apid]['geometry']:
  4812. solid_geometry.append(geo_el['solid'])
  4813. solid_geometry = MultiPolygon(solid_geometry)
  4814. solid_geometry = solid_geometry.buffer(0.0000001)
  4815. obj_init.solid_geometry = deepcopy(solid_geometry)
  4816. obj_init.apertures = deepcopy(apertures)
  4817. # clear the working objects (perhaps not necessary due of Python GC)
  4818. apertures.clear()
  4819. if not self.collection.get_selected():
  4820. log.warning("App.convert_any2gerber --> No object selected")
  4821. self.inform.emit('[WARNING_NOTCL] %s' %
  4822. _("No object is selected. Select an object and try again."))
  4823. return
  4824. for obj in self.collection.get_selected():
  4825. obj_name = obj.options["name"]
  4826. try:
  4827. if isinstance(obj, ExcellonObject):
  4828. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4829. elif isinstance(obj, GeometryObject):
  4830. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4831. else:
  4832. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4833. except Exception as e:
  4834. return "Operation failed: %s" % str(e)
  4835. def abort_all_tasks(self):
  4836. """
  4837. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4838. on the first possible occasion.
  4839. :return:
  4840. """
  4841. if self.abort_flag is False:
  4842. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4843. self.abort_flag = True
  4844. self.cleanup.emit()
  4845. def app_is_idle(self):
  4846. if self.abort_flag:
  4847. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4848. self.abort_flag = False
  4849. def on_selectall(self):
  4850. """
  4851. Will draw a selection box shape around the selected objects.
  4852. :return:
  4853. """
  4854. self.defaults.report_usage("on_selectall()")
  4855. # delete the possible selection box around a possible selected object
  4856. self.delete_selection_shape()
  4857. for name in self.collection.get_names():
  4858. self.collection.set_active(name)
  4859. curr_sel_obj = self.collection.get_by_name(name)
  4860. # create the selection box around the selected object
  4861. if self.defaults['global_selection_shape'] is True:
  4862. self.draw_selection_shape(curr_sel_obj)
  4863. def on_preferences(self):
  4864. """
  4865. Adds the Preferences in a Tab in Plot Area
  4866. :return:
  4867. """
  4868. # add the tab if it was closed
  4869. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4870. # delete the absolute and relative position and messages in the infobar
  4871. self.ui.position_label.setText("")
  4872. self.ui.rel_position_label.setText("")
  4873. # Switch plot_area to preferences page
  4874. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4875. # self.ui.show()
  4876. # detect changes in the preferences
  4877. for idx in range(self.ui.pref_tab_area.count()):
  4878. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4879. try:
  4880. try:
  4881. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4882. except (TypeError, AttributeError):
  4883. pass
  4884. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4885. except AttributeError:
  4886. pass
  4887. try:
  4888. try:
  4889. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4890. except (TypeError, AttributeError):
  4891. pass
  4892. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4893. except AttributeError:
  4894. pass
  4895. try:
  4896. try:
  4897. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4898. except (TypeError, AttributeError):
  4899. pass
  4900. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4901. except AttributeError:
  4902. pass
  4903. try:
  4904. try:
  4905. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4906. except (TypeError, AttributeError):
  4907. pass
  4908. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4909. except AttributeError:
  4910. pass
  4911. try:
  4912. try:
  4913. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4914. except (TypeError, AttributeError):
  4915. pass
  4916. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4917. except AttributeError:
  4918. pass
  4919. def on_tools_database(self, source='app'):
  4920. """
  4921. Adds the Tools Database in a Tab in Plot Area.
  4922. :return:
  4923. """
  4924. for idx in range(self.ui.plot_tab_area.count()):
  4925. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4926. # there can be only one instance of Tools Database at one time
  4927. return
  4928. if source == 'app':
  4929. self.tools_db_tab = ToolsDB2(
  4930. app=self,
  4931. parent=self.ui,
  4932. callback_on_edited=self.on_tools_db_edited,
  4933. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4934. )
  4935. elif source == 'ncc':
  4936. self.tools_db_tab = ToolsDB2(
  4937. app=self,
  4938. parent=self.ui,
  4939. callback_on_edited=self.on_tools_db_edited,
  4940. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4941. )
  4942. elif source == 'paint':
  4943. self.tools_db_tab = ToolsDB2(
  4944. app=self,
  4945. parent=self.ui,
  4946. callback_on_edited=self.on_tools_db_edited,
  4947. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4948. )
  4949. # add the tab if it was closed
  4950. try:
  4951. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4952. self.tools_db_tab.setObjectName("database_tab")
  4953. except Exception as e:
  4954. log.debug("App.on_tools_database() --> %s" % str(e))
  4955. return
  4956. # delete the absolute and relative position and messages in the infobar
  4957. self.ui.position_label.setText("")
  4958. self.ui.rel_position_label.setText("")
  4959. # Switch plot_area to preferences page
  4960. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4961. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4962. self.tools_db_tab.ui_connect()
  4963. def on_tools_db_edited(self):
  4964. """
  4965. Executed whenever a tool is edited in Tools Database.
  4966. Will color the text of the Tools Database tab to Red color.
  4967. :return:
  4968. """
  4969. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4970. for idx in range(self.ui.plot_tab_area.count()):
  4971. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4972. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4973. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4974. self.tools_db_changed_flag = True
  4975. def on_geometry_tool_add_from_db_executed(self, tool):
  4976. """
  4977. Here add the tool from DB in the selected geometry object.
  4978. :return:
  4979. """
  4980. tool_from_db = deepcopy(tool)
  4981. obj = self.collection.get_active()
  4982. if isinstance(obj, GeometryObject):
  4983. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4984. # close the tab and delete it
  4985. for idx in range(self.ui.plot_tab_area.count()):
  4986. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4987. wdg = self.ui.plot_tab_area.widget(idx)
  4988. wdg.deleteLater()
  4989. self.ui.plot_tab_area.removeTab(idx)
  4990. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4991. else:
  4992. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4993. def on_plot_area_tab_closed(self, tab_obj_name):
  4994. """
  4995. Executed whenever a QTab is closed in the Plot Area.
  4996. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4997. :return:
  4998. """
  4999. if tab_obj_name == "preferences_tab":
  5000. self.preferencesUiManager.on_close_preferences_tab()
  5001. elif tab_obj_name == "database_tab":
  5002. # disconnect the signals from the table widget in tab
  5003. self.tools_db_tab.ui_disconnect()
  5004. if self.tools_db_changed_flag is True:
  5005. msgbox = QtWidgets.QMessageBox()
  5006. msgbox.setText(_("One or more Tools are edited.\n"
  5007. "Do you want to update the Tools Database?"))
  5008. msgbox.setWindowTitle(_("Save Tools Database"))
  5009. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5010. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5011. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5012. msgbox.setDefaultButton(bt_yes)
  5013. msgbox.exec_()
  5014. response = msgbox.clickedButton()
  5015. if response == bt_yes:
  5016. self.tools_db_tab.on_save_tools_db()
  5017. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  5018. else:
  5019. self.tools_db_changed_flag = False
  5020. self.inform.emit('')
  5021. return
  5022. self.tools_db_tab.deleteLater()
  5023. elif tab_obj_name == "text_editor_tab":
  5024. self.toggle_codeeditor = False
  5025. elif tab_obj_name == "bookmarks_tab":
  5026. self.book_dialog_tab.rebuild_actions()
  5027. self.book_dialog_tab.deleteLater()
  5028. else:
  5029. return
  5030. # def on_plotarea_tab_closed(self, tab_idx):
  5031. # """
  5032. #
  5033. # :param tab_idx: Index of the Tab from the plotarea that was closed
  5034. # :return:
  5035. # """
  5036. # widget = self.ui.plot_tab_area.widget(tab_idx)
  5037. #
  5038. # if widget is not None:
  5039. # widget.deleteLater()
  5040. # self.ui.plot_tab_area.removeTab(tab_idx)
  5041. def on_flipy(self):
  5042. """
  5043. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  5044. :return:
  5045. """
  5046. self.defaults.report_usage("on_flipy()")
  5047. obj_list = self.collection.get_selected()
  5048. xminlist = []
  5049. yminlist = []
  5050. xmaxlist = []
  5051. ymaxlist = []
  5052. if not obj_list:
  5053. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  5054. else:
  5055. try:
  5056. # first get a bounding box to fit all
  5057. for obj in obj_list:
  5058. xmin, ymin, xmax, ymax = obj.bounds()
  5059. xminlist.append(xmin)
  5060. yminlist.append(ymin)
  5061. xmaxlist.append(xmax)
  5062. ymaxlist.append(ymax)
  5063. # get the minimum x,y and maximum x,y for all objects selected
  5064. xminimal = min(xminlist)
  5065. yminimal = min(yminlist)
  5066. xmaximal = max(xmaxlist)
  5067. ymaximal = max(ymaxlist)
  5068. px = 0.5 * (xminimal + xmaximal)
  5069. py = 0.5 * (yminimal + ymaximal)
  5070. # execute mirroring
  5071. for obj in obj_list:
  5072. obj.mirror('X', [px, py])
  5073. obj.plot()
  5074. self.object_changed.emit(obj)
  5075. self.inform.emit('[success] %s' %
  5076. _("Flip on Y axis done."))
  5077. except Exception as e:
  5078. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5079. return
  5080. def on_flipx(self):
  5081. """
  5082. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5083. :return:
  5084. """
  5085. self.defaults.report_usage("on_flipx()")
  5086. obj_list = self.collection.get_selected()
  5087. xminlist = []
  5088. yminlist = []
  5089. xmaxlist = []
  5090. ymaxlist = []
  5091. if not obj_list:
  5092. self.inform.emit('[WARNING_NOTCL] %s' %
  5093. _("No object selected to Flip on X axis."))
  5094. else:
  5095. try:
  5096. # first get a bounding box to fit all
  5097. for obj in obj_list:
  5098. xmin, ymin, xmax, ymax = obj.bounds()
  5099. xminlist.append(xmin)
  5100. yminlist.append(ymin)
  5101. xmaxlist.append(xmax)
  5102. ymaxlist.append(ymax)
  5103. # get the minimum x,y and maximum x,y for all objects selected
  5104. xminimal = min(xminlist)
  5105. yminimal = min(yminlist)
  5106. xmaximal = max(xmaxlist)
  5107. ymaximal = max(ymaxlist)
  5108. px = 0.5 * (xminimal + xmaximal)
  5109. py = 0.5 * (yminimal + ymaximal)
  5110. # execute mirroring
  5111. for obj in obj_list:
  5112. obj.mirror('Y', [px, py])
  5113. obj.plot()
  5114. self.object_changed.emit(obj)
  5115. self.inform.emit('[success] %s' %
  5116. _("Flip on X axis done."))
  5117. except Exception as e:
  5118. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5119. return
  5120. def on_rotate(self, silent=False, preset=None):
  5121. """
  5122. Executed when Options -> Rotate Selection menu entry is clicked.
  5123. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5124. :param preset: A value to be used as predefined angle for rotation.
  5125. :return:
  5126. """
  5127. self.defaults.report_usage("on_rotate()")
  5128. obj_list = self.collection.get_selected()
  5129. xminlist = []
  5130. yminlist = []
  5131. xmaxlist = []
  5132. ymaxlist = []
  5133. if not obj_list:
  5134. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5135. else:
  5136. if silent is False:
  5137. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5138. min=-360, max=360, decimals=4,
  5139. init_val=float(self.defaults['tools_transform_rotate']))
  5140. num, ok = rotatebox.get_value()
  5141. else:
  5142. num = preset
  5143. ok = True
  5144. if ok:
  5145. try:
  5146. # first get a bounding box to fit all
  5147. for obj in obj_list:
  5148. xmin, ymin, xmax, ymax = obj.bounds()
  5149. xminlist.append(xmin)
  5150. yminlist.append(ymin)
  5151. xmaxlist.append(xmax)
  5152. ymaxlist.append(ymax)
  5153. # get the minimum x,y and maximum x,y for all objects selected
  5154. xminimal = min(xminlist)
  5155. yminimal = min(yminlist)
  5156. xmaximal = max(xmaxlist)
  5157. ymaximal = max(ymaxlist)
  5158. px = 0.5 * (xminimal + xmaximal)
  5159. py = 0.5 * (yminimal + ymaximal)
  5160. for sel_obj in obj_list:
  5161. sel_obj.rotate(-float(num), point=(px, py))
  5162. sel_obj.plot()
  5163. self.object_changed.emit(sel_obj)
  5164. self.inform.emit('[success] %s' %
  5165. _("Rotation done."))
  5166. except Exception as e:
  5167. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5168. return
  5169. def on_skewx(self):
  5170. """
  5171. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5172. :return:
  5173. """
  5174. self.defaults.report_usage("on_skewx()")
  5175. obj_list = self.collection.get_selected()
  5176. xminlist = []
  5177. yminlist = []
  5178. if not obj_list:
  5179. self.inform.emit('[WARNING_NOTCL] %s' %
  5180. _("No object selected to Skew/Shear on X axis."))
  5181. else:
  5182. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5183. min=-360, max=360, decimals=4,
  5184. init_val=float(self.defaults['tools_transform_skew_x']))
  5185. num, ok = skewxbox.get_value()
  5186. if ok:
  5187. # first get a bounding box to fit all
  5188. for obj in obj_list:
  5189. xmin, ymin, xmax, ymax = obj.bounds()
  5190. xminlist.append(xmin)
  5191. yminlist.append(ymin)
  5192. # get the minimum x,y and maximum x,y for all objects selected
  5193. xminimal = min(xminlist)
  5194. yminimal = min(yminlist)
  5195. for obj in obj_list:
  5196. obj.skew(num, 0, point=(xminimal, yminimal))
  5197. obj.plot()
  5198. self.object_changed.emit(obj)
  5199. self.inform.emit('[success] %s' %
  5200. _("Skew on X axis done."))
  5201. def on_skewy(self):
  5202. """
  5203. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5204. :return:
  5205. """
  5206. self.defaults.report_usage("on_skewy()")
  5207. obj_list = self.collection.get_selected()
  5208. xminlist = []
  5209. yminlist = []
  5210. if not obj_list:
  5211. self.inform.emit('[WARNING_NOTCL] %s' %
  5212. _("No object selected to Skew/Shear on Y axis."))
  5213. else:
  5214. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5215. min=-360, max=360, decimals=4,
  5216. init_val=float(self.defaults['tools_transform_skew_y']))
  5217. num, ok = skewybox.get_value()
  5218. if ok:
  5219. # first get a bounding box to fit all
  5220. for obj in obj_list:
  5221. xmin, ymin, xmax, ymax = obj.bounds()
  5222. xminlist.append(xmin)
  5223. yminlist.append(ymin)
  5224. # get the minimum x,y and maximum x,y for all objects selected
  5225. xminimal = min(xminlist)
  5226. yminimal = min(yminlist)
  5227. for obj in obj_list:
  5228. obj.skew(0, num, point=(xminimal, yminimal))
  5229. obj.plot()
  5230. self.object_changed.emit(obj)
  5231. self.inform.emit('[success] %s' %
  5232. _("Skew on Y axis done."))
  5233. def on_plots_updated(self):
  5234. """
  5235. Callback used to report when the plots have changed.
  5236. Adjust axes and zooms to fit.
  5237. :return: None
  5238. """
  5239. if self.is_legacy is False:
  5240. self.plotcanvas.update()
  5241. else:
  5242. self.plotcanvas.auto_adjust_axes()
  5243. self.on_zoom_fit(None)
  5244. self.collection.update_view()
  5245. # self.inform.emit(_("Plots updated ..."))
  5246. def on_toolbar_replot(self):
  5247. """
  5248. Callback for toolbar button. Re-plots all objects.
  5249. :return: None
  5250. """
  5251. self.defaults.report_usage("on_toolbar_replot")
  5252. self.log.debug("on_toolbar_replot()")
  5253. try:
  5254. self.collection.get_active().read_form()
  5255. except AttributeError:
  5256. self.log.debug("on_toolbar_replot(): AttributeError")
  5257. pass
  5258. self.plot_all()
  5259. def on_row_activated(self, index):
  5260. if index.isValid():
  5261. if index.internalPointer().parent_item != self.collection.root_item:
  5262. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5263. self.collection.on_item_activated(index)
  5264. def on_row_selected(self, obj_name):
  5265. """
  5266. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5267. It mean we clicked outside of the items and deselected all
  5268. :param obj_name:
  5269. :return:
  5270. """
  5271. if obj_name == 'none':
  5272. for act in self.ui.menuobjects.actions():
  5273. act.setChecked(False)
  5274. return
  5275. # get the name of the selected objects and add them to a list
  5276. name_list = []
  5277. for obj in self.collection.get_selected():
  5278. name_list.append(obj.options['name'])
  5279. # set all actions as unchecked but the ones selected make them checked
  5280. for act in self.ui.menuobjects.actions():
  5281. act.setChecked(False)
  5282. if act.text() in name_list:
  5283. act.setChecked(True)
  5284. def on_collection_updated(self, obj, state, old_name):
  5285. """
  5286. Create a menu from the object loaded in the collection.
  5287. :param obj: object that was changed (added, deleted, renamed)
  5288. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5289. :param old_name: the old name of the object before the action that triggered this slot happened
  5290. :return: None
  5291. """
  5292. icon_files = {
  5293. "gerber": self.resource_location + "/flatcam_icon16.png",
  5294. "excellon": self.resource_location + "/drill16.png",
  5295. "cncjob": self.resource_location + "/cnc16.png",
  5296. "geometry": self.resource_location + "/geometry16.png",
  5297. "script": self.resource_location + "/script_new16.png",
  5298. "document": self.resource_location + "/notes16_1.png"
  5299. }
  5300. if state == 'append':
  5301. for act in self.ui.menuobjects.actions():
  5302. try:
  5303. act.triggered.disconnect()
  5304. except TypeError:
  5305. pass
  5306. self.ui.menuobjects.clear()
  5307. gerber_list = []
  5308. exc_list = []
  5309. cncjob_list = []
  5310. geo_list = []
  5311. script_list = []
  5312. doc_list = []
  5313. for name in self.collection.get_names():
  5314. obj_named = self.collection.get_by_name(name)
  5315. if obj_named.kind == 'gerber':
  5316. gerber_list.append(name)
  5317. elif obj_named.kind == 'excellon':
  5318. exc_list.append(name)
  5319. elif obj_named.kind == 'cncjob':
  5320. cncjob_list.append(name)
  5321. elif obj_named.kind == 'geometry':
  5322. geo_list.append(name)
  5323. elif obj_named.kind == 'script':
  5324. script_list.append(name)
  5325. elif obj_named.kind == 'document':
  5326. doc_list.append(name)
  5327. def add_act(o_name):
  5328. obj_for_icon = self.collection.get_by_name(o_name)
  5329. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5330. add_action.setCheckable(True)
  5331. add_action.setText(o_name)
  5332. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5333. add_action.triggered.connect(
  5334. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5335. self.collection.set_inactive(o_name))
  5336. self.ui.menuobjects.addAction(add_action)
  5337. for name in gerber_list:
  5338. add_act(name)
  5339. self.ui.menuobjects.addSeparator()
  5340. for name in exc_list:
  5341. add_act(name)
  5342. self.ui.menuobjects.addSeparator()
  5343. for name in cncjob_list:
  5344. add_act(name)
  5345. self.ui.menuobjects.addSeparator()
  5346. for name in geo_list:
  5347. add_act(name)
  5348. self.ui.menuobjects.addSeparator()
  5349. for name in script_list:
  5350. add_act(name)
  5351. self.ui.menuobjects.addSeparator()
  5352. for name in doc_list:
  5353. add_act(name)
  5354. self.ui.menuobjects.addSeparator()
  5355. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5356. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5357. _('Select All')
  5358. )
  5359. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5360. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5361. _('Deselect All')
  5362. )
  5363. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5364. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5365. elif state == 'delete':
  5366. for act in self.ui.menuobjects.actions():
  5367. if act.text() == obj.options['name']:
  5368. try:
  5369. act.triggered.disconnect()
  5370. except TypeError:
  5371. pass
  5372. self.ui.menuobjects.removeAction(act)
  5373. break
  5374. elif state == 'rename':
  5375. for act in self.ui.menuobjects.actions():
  5376. if act.text() == old_name:
  5377. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5378. add_action.setText(obj.options['name'])
  5379. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5380. add_action.triggered.connect(
  5381. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5382. self.collection.set_inactive(obj.options['name']))
  5383. self.ui.menuobjects.insertAction(act, add_action)
  5384. try:
  5385. act.triggered.disconnect()
  5386. except TypeError:
  5387. pass
  5388. self.ui.menuobjects.removeAction(act)
  5389. break
  5390. elif state == 'delete_all':
  5391. for act in self.ui.menuobjects.actions():
  5392. try:
  5393. act.triggered.disconnect()
  5394. except TypeError:
  5395. pass
  5396. self.ui.menuobjects.clear()
  5397. self.ui.menuobjects.addSeparator()
  5398. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5399. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5400. _('Select All')
  5401. )
  5402. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5403. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5404. _('Deselect All')
  5405. )
  5406. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5407. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5408. def on_objects_selection(self, on_off):
  5409. obj_list = self.collection.get_names()
  5410. if on_off is True:
  5411. self.collection.set_all_active()
  5412. for act in self.ui.menuobjects.actions():
  5413. try:
  5414. act.setChecked(True)
  5415. except Exception:
  5416. pass
  5417. if obj_list:
  5418. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5419. else:
  5420. self.collection.set_all_inactive()
  5421. for act in self.ui.menuobjects.actions():
  5422. try:
  5423. act.setChecked(False)
  5424. except Exception:
  5425. pass
  5426. if obj_list:
  5427. self.inform.emit('%s' % _("Objects selection is cleared."))
  5428. else:
  5429. self.inform.emit('')
  5430. def grid_status(self):
  5431. if self.ui.grid_snap_btn.isChecked():
  5432. return True
  5433. else:
  5434. return False
  5435. def populate_cmenu_grids(self):
  5436. units = self.defaults['units'].lower()
  5437. # for act in self.ui.cmenu_gridmenu.actions():
  5438. # act.triggered.disconnect()
  5439. self.ui.cmenu_gridmenu.clear()
  5440. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5441. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5442. _("Grid On/Off"))
  5443. grid_toggle.setCheckable(True)
  5444. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5445. self.ui.cmenu_gridmenu.addSeparator()
  5446. for grid in sorted_list:
  5447. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5448. "%s" % str(grid))
  5449. action.triggered.connect(self.set_grid)
  5450. self.ui.cmenu_gridmenu.addSeparator()
  5451. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5452. _("Add"))
  5453. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5454. _("Delete"))
  5455. grid_add.triggered.connect(self.on_grid_add)
  5456. grid_delete.triggered.connect(self.on_grid_delete)
  5457. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5458. def set_grid(self):
  5459. menu_action = self.sender()
  5460. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5461. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5462. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5463. def on_grid_add(self):
  5464. # ## Current application units in lower Case
  5465. units = self.defaults['units'].lower()
  5466. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5467. text=_('Enter a Grid Value:'),
  5468. min=0.0000, max=99.9999, decimals=4)
  5469. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5470. val, ok = grid_add_popup.get_value()
  5471. if ok:
  5472. if float(val) == 0:
  5473. self.inform.emit('[WARNING_NOTCL] %s' %
  5474. _("Please enter a grid value with non-zero value, in Float format."))
  5475. return
  5476. else:
  5477. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5478. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5479. self.inform.emit('[success] %s...' %
  5480. _("New Grid added"))
  5481. else:
  5482. self.inform.emit('[WARNING_NOTCL] %s...' %
  5483. _("Grid already exists"))
  5484. else:
  5485. self.inform.emit('[WARNING_NOTCL] %s...' %
  5486. _("Adding New Grid cancelled"))
  5487. def on_grid_delete(self):
  5488. # ## Current application units in lower Case
  5489. units = self.defaults['units'].lower()
  5490. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5491. text='Enter a Grid Value:',
  5492. min=0.0000, max=99.9999, decimals=4)
  5493. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5494. val, ok = grid_del_popup.get_value()
  5495. if ok:
  5496. if float(val) == 0:
  5497. self.inform.emit('[WARNING_NOTCL] %s' %
  5498. _("Please enter a grid value with non-zero value, in Float format."))
  5499. return
  5500. else:
  5501. try:
  5502. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5503. except ValueError:
  5504. self.inform.emit('[ERROR_NOTCL]%s...' %
  5505. _(" Grid Value does not exist"))
  5506. return
  5507. self.inform.emit('[success] %s...' %
  5508. _("Grid Value deleted"))
  5509. else:
  5510. self.inform.emit('[WARNING_NOTCL] %s...' %
  5511. _("Delete Grid value cancelled"))
  5512. def on_shortcut_list(self):
  5513. self.defaults.report_usage("on_shortcut_list()")
  5514. # add the tab if it was closed
  5515. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5516. # delete the absolute and relative position and messages in the infobar
  5517. self.ui.position_label.setText("")
  5518. self.ui.rel_position_label.setText("")
  5519. # Switch plot_area to preferences page
  5520. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5521. # self.ui.show()
  5522. def on_select_tab(self, name):
  5523. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5524. if self.ui.splitter.sizes()[0] == 0:
  5525. self.ui.splitter.setSizes([1, 1])
  5526. else:
  5527. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5528. self.ui.splitter.setSizes([0, 1])
  5529. if name == 'project':
  5530. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5531. elif name == 'selected':
  5532. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5533. elif name == 'tool':
  5534. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5535. def on_copy_name(self):
  5536. self.defaults.report_usage("on_copy_name()")
  5537. obj = self.collection.get_active()
  5538. try:
  5539. name = obj.options["name"]
  5540. except AttributeError:
  5541. log.debug("on_copy_name() --> No object selected to copy it's name")
  5542. self.inform.emit('[WARNING_NOTCL]%s' %
  5543. _(" No object selected to copy it's name"))
  5544. return
  5545. self.clipboard.setText(name)
  5546. self.inform.emit(_("Name copied on clipboard ..."))
  5547. def on_mouse_click_over_plot(self, event):
  5548. """
  5549. Default actions are:
  5550. :param event: Contains information about the event, like which button
  5551. was clicked, the pixel coordinates and the axes coordinates.
  5552. :return: None
  5553. """
  5554. self.pos = []
  5555. if self.is_legacy is False:
  5556. event_pos = event.pos
  5557. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5558. # # Set the mouse button for panning
  5559. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5560. else:
  5561. event_pos = (event.xdata, event.ydata)
  5562. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5563. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5564. # So it can receive key presses
  5565. self.plotcanvas.native.setFocus()
  5566. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5567. if self.grid_status():
  5568. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5569. else:
  5570. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5571. try:
  5572. if event.button == 1:
  5573. # Reset here the relative coordinates so there is a new reference on the click position
  5574. if self.rel_point1 is None:
  5575. self.rel_point1 = self.pos
  5576. else:
  5577. self.rel_point2 = copy(self.rel_point1)
  5578. self.rel_point1 = self.pos
  5579. self.on_mouse_move_over_plot(event, origin_click=True)
  5580. except Exception as e:
  5581. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5582. def on_mouse_double_click_over_plot(self, event):
  5583. if event.button == 1:
  5584. self.doubleclick = True
  5585. def on_mouse_move_over_plot(self, event, origin_click=None):
  5586. """
  5587. Callback for the mouse motion event over the plot.
  5588. :param event: Contains information about the event.
  5589. :param origin_click
  5590. :return: None
  5591. """
  5592. if self.is_legacy is False:
  5593. event_pos = event.pos
  5594. if self.defaults["global_pan_button"] == '2':
  5595. pan_button = 2
  5596. else:
  5597. pan_button = 3
  5598. self.event_is_dragging = event.is_dragging
  5599. else:
  5600. event_pos = (event.xdata, event.ydata)
  5601. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5602. if self.defaults["global_pan_button"] == '2':
  5603. pan_button = 3
  5604. else:
  5605. pan_button = 2
  5606. self.event_is_dragging = self.plotcanvas.is_dragging
  5607. # So it can receive key presses but not when the Tcl Shell is active
  5608. if not self.ui.shell_dock.isVisible():
  5609. if not self.plotcanvas.native.hasFocus():
  5610. self.plotcanvas.native.setFocus()
  5611. self.pos_jump = event_pos
  5612. self.ui.popMenu.mouse_is_panning = False
  5613. if origin_click is None:
  5614. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5615. if event.button == pan_button and self.event_is_dragging == 1:
  5616. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5617. if self.ui.popMenu.popup_active:
  5618. self.ui.popMenu.popup_active = False
  5619. return
  5620. self.ui.popMenu.mouse_is_panning = True
  5621. return
  5622. if self.rel_point1 is not None:
  5623. try: # May fail in case mouse not within axes
  5624. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5625. if self.grid_status():
  5626. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5627. # Update cursor
  5628. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5629. symbol='++', edge_color=self.cursor_color_3D,
  5630. edge_width=self.defaults["global_cursor_width"],
  5631. size=self.defaults["global_cursor_size"])
  5632. else:
  5633. pos = (pos_canvas[0], pos_canvas[1])
  5634. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5635. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5636. self.dx = pos[0] - float(self.rel_point1[0])
  5637. self.dy = pos[1] - float(self.rel_point1[1])
  5638. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5639. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5640. self.mouse = [pos[0], pos[1]]
  5641. # if the mouse is moved and the LMB is clicked then the action is a selection
  5642. if self.event_is_dragging == 1 and event.button == 1:
  5643. self.delete_selection_shape()
  5644. if self.dx < 0:
  5645. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5646. face_color=self.defaults['global_alt_sel_fill'])
  5647. self.selection_type = False
  5648. elif self.dx >= 0:
  5649. self.draw_moving_selection_shape(self.pos, pos)
  5650. self.selection_type = True
  5651. else:
  5652. self.selection_type = None
  5653. else:
  5654. self.selection_type = None
  5655. # hover effect - enabled in Preferences -> General -> GUI Settings
  5656. if self.defaults['global_hover']:
  5657. for obj in self.collection.get_list():
  5658. try:
  5659. # select the object(s) only if it is enabled (plotted)
  5660. if obj.options['plot']:
  5661. if obj not in self.collection.get_selected():
  5662. poly_obj = Polygon(
  5663. [(obj.options['xmin'], obj.options['ymin']),
  5664. (obj.options['xmax'], obj.options['ymin']),
  5665. (obj.options['xmax'], obj.options['ymax']),
  5666. (obj.options['xmin'], obj.options['ymax'])]
  5667. )
  5668. if Point(pos).within(poly_obj):
  5669. if obj.isHovering is False:
  5670. obj.isHovering = True
  5671. obj.notHovering = True
  5672. # create the selection box around the selected object
  5673. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5674. else:
  5675. if obj.notHovering is True:
  5676. obj.notHovering = False
  5677. obj.isHovering = False
  5678. self.delete_hover_shape()
  5679. except Exception:
  5680. # the Exception here will happen if we try to select on screen and we have an
  5681. # newly (and empty) just created Geometry or Excellon object that do not have the
  5682. # xmin, xmax, ymin, ymax options.
  5683. # In this case poly_obj creation (see above) will fail
  5684. pass
  5685. except Exception:
  5686. self.ui.position_label.setText("")
  5687. self.ui.rel_position_label.setText("")
  5688. self.mouse = None
  5689. def on_mouse_click_release_over_plot(self, event):
  5690. """
  5691. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5692. and has been registered in ''self.__init__()''.
  5693. :param event: contains information about the event.
  5694. :return:
  5695. """
  5696. if self.is_legacy is False:
  5697. event_pos = event.pos
  5698. right_button = 2
  5699. else:
  5700. event_pos = (event.xdata, event.ydata)
  5701. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5702. right_button = 3
  5703. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5704. if self.grid_status():
  5705. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5706. else:
  5707. pos = (pos_canvas[0], pos_canvas[1])
  5708. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5709. # canvas menu
  5710. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5711. self.ui.popMenu.mouse_is_panning = False
  5712. self.cursor = QtGui.QCursor()
  5713. self.populate_cmenu_grids()
  5714. self.ui.popMenu.popup(self.cursor.pos())
  5715. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5716. # selection and then select a type of selection ("enclosing" or "touching")
  5717. if event.button == 1: # left click
  5718. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5719. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5720. if modifiers == QtCore.Qt.ShiftModifier:
  5721. # do not auto open the Project Tab
  5722. self.click_noproject = True
  5723. self.clipboard.setText(
  5724. self.defaults["global_point_clipboard_format"] %
  5725. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5726. )
  5727. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5728. return
  5729. if self.doubleclick is True:
  5730. self.doubleclick = False
  5731. if self.collection.get_selected():
  5732. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5733. if self.ui.splitter.sizes()[0] == 0:
  5734. self.ui.splitter.setSizes([1, 1])
  5735. try:
  5736. # delete the selection shape(S) as it may be in the way
  5737. self.delete_selection_shape()
  5738. self.delete_hover_shape()
  5739. except Exception as e:
  5740. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5741. return
  5742. else:
  5743. # WORKAROUND for LEGACY MODE
  5744. if self.is_legacy is True:
  5745. # if there is no move on canvas then we have no dragging selection
  5746. if self.dx == 0 or self.dy == 0:
  5747. self.selection_type = None
  5748. if self.selection_type is not None:
  5749. try:
  5750. self.selection_area_handler(self.pos, pos, self.selection_type)
  5751. self.selection_type = None
  5752. except Exception as e:
  5753. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5754. return
  5755. else:
  5756. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5757. if key_modifier == QtCore.Qt.ShiftModifier:
  5758. mod_key = 'Shift'
  5759. elif key_modifier == QtCore.Qt.ControlModifier:
  5760. mod_key = 'Control'
  5761. else:
  5762. mod_key = None
  5763. try:
  5764. if self.command_active is None:
  5765. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5766. # deselect, and if it's not selected then it will be selected
  5767. # If there is no active command (self.command_active is None) then we check if we clicked
  5768. # on a object by checking the bounding limits against mouse click position
  5769. if mod_key == self.defaults["global_mselect_key"]:
  5770. self.select_objects(key='multisel')
  5771. else:
  5772. # If there is no active command (self.command_active is None) then we check if
  5773. # we clicked on a object by checking the bounding limits against mouse click position
  5774. self.select_objects()
  5775. self.delete_hover_shape()
  5776. except Exception as e:
  5777. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5778. return
  5779. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5780. """
  5781. :param start_pos: mouse position when the selection LMB click was done
  5782. :param end_pos: mouse position when the left mouse button is released
  5783. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5784. :return:
  5785. """
  5786. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5787. # delete previous selection shape
  5788. self.delete_selection_shape()
  5789. # make all objects inactive
  5790. self.collection.set_all_inactive()
  5791. for obj in self.collection.get_list():
  5792. try:
  5793. # select the object(s) only if it is enabled (plotted)
  5794. if obj.options['plot']:
  5795. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5796. (obj.options['xmax'], obj.options['ymin']),
  5797. (obj.options['xmax'], obj.options['ymax']),
  5798. (obj.options['xmin'], obj.options['ymax'])])
  5799. if sel_type is True:
  5800. if poly_obj.within(poly_selection):
  5801. # create the selection box around the selected object
  5802. if self.defaults['global_selection_shape'] is True:
  5803. self.draw_selection_shape(obj)
  5804. self.collection.set_active(obj.options['name'])
  5805. else:
  5806. if poly_selection.intersects(poly_obj):
  5807. # create the selection box around the selected object
  5808. if self.defaults['global_selection_shape'] is True:
  5809. self.draw_selection_shape(obj)
  5810. self.collection.set_active(obj.options['name'])
  5811. obj.selection_shape_drawn = True
  5812. except Exception as e:
  5813. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5814. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5815. # In this case poly_obj creation (see above) will fail
  5816. log.debug("App.selection_area_handler() --> %s" % str(e))
  5817. def select_objects(self, key=None):
  5818. """
  5819. Will select objects clicked on canvas
  5820. :param key: for future use in cumulative selection
  5821. :return:
  5822. """
  5823. # list where we store the overlapped objects under our mouse left click position
  5824. if key is None:
  5825. self.objects_under_the_click_list = []
  5826. # Populate the list with the overlapped objects on the click position
  5827. curr_x, curr_y = self.pos
  5828. for obj in self.all_objects_list:
  5829. # ScriptObject and DocumentObject objects can't be selected
  5830. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5831. continue
  5832. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5833. continue
  5834. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5835. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5836. if obj.options['name'] not in self.objects_under_the_click_list:
  5837. if obj.options['plot']:
  5838. # add objects to the objects_under_the_click list only if the object is plotted
  5839. # (active and not disabled)
  5840. self.objects_under_the_click_list.append(obj.options['name'])
  5841. try:
  5842. if self.objects_under_the_click_list:
  5843. curr_sel_obj = self.collection.get_active()
  5844. # case when there is only an object under the click and we toggle it
  5845. if len(self.objects_under_the_click_list) == 1:
  5846. if curr_sel_obj is None:
  5847. self.collection.set_active(self.objects_under_the_click_list[0])
  5848. curr_sel_obj = self.collection.get_active()
  5849. # create the selection box around the selected object
  5850. if self.defaults['global_selection_shape'] is True:
  5851. self.draw_selection_shape(curr_sel_obj)
  5852. curr_sel_obj.selection_shape_drawn = True
  5853. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5854. self.on_objects_selection(False)
  5855. self.delete_selection_shape()
  5856. curr_sel_obj.selection_shape_drawn = False
  5857. self.collection.set_active(self.objects_under_the_click_list[0])
  5858. curr_sel_obj = self.collection.get_active()
  5859. # create the selection box around the selected object
  5860. if self.defaults['global_selection_shape'] is True:
  5861. self.draw_selection_shape(curr_sel_obj)
  5862. curr_sel_obj.selection_shape_drawn = True
  5863. self.selected_message(curr_sel_obj=curr_sel_obj)
  5864. elif curr_sel_obj.selection_shape_drawn is False:
  5865. if self.defaults['global_selection_shape'] is True:
  5866. self.draw_selection_shape(curr_sel_obj)
  5867. curr_sel_obj.selection_shape_drawn = True
  5868. else:
  5869. self.on_objects_selection(False)
  5870. self.delete_selection_shape()
  5871. if self.call_source != 'app':
  5872. self.call_source = 'app'
  5873. self.selected_message(curr_sel_obj=curr_sel_obj)
  5874. else:
  5875. # If there is no selected object
  5876. # make active the first element of the overlapped objects list
  5877. if self.collection.get_active() is None:
  5878. self.collection.set_active(self.objects_under_the_click_list[0])
  5879. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5880. name_sel_obj = self.collection.get_active().options['name']
  5881. # In case that there is a selected object but it is not in the overlapped object list
  5882. # make that object inactive and activate the first element in the overlapped object list
  5883. if name_sel_obj not in self.objects_under_the_click_list:
  5884. self.collection.set_inactive(name_sel_obj)
  5885. name_sel_obj = self.objects_under_the_click_list[0]
  5886. self.collection.set_active(name_sel_obj)
  5887. else:
  5888. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5889. self.collection.set_all_inactive()
  5890. self.collection.set_active(
  5891. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5892. curr_sel_obj = self.collection.get_active()
  5893. # delete the possible selection box around a possible selected object
  5894. self.delete_selection_shape()
  5895. curr_sel_obj.selection_shape_drawn = False
  5896. # create the selection box around the selected object
  5897. if self.defaults['global_selection_shape'] is True:
  5898. self.draw_selection_shape(curr_sel_obj)
  5899. curr_sel_obj.selection_shape_drawn = True
  5900. self.selected_message(curr_sel_obj=curr_sel_obj)
  5901. else:
  5902. # deselect everything
  5903. self.on_objects_selection(False)
  5904. # delete the possible selection box around a possible selected object
  5905. self.delete_selection_shape()
  5906. for o in self.collection.get_list():
  5907. o.selection_shape_drawn = False
  5908. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5909. # only when working on App
  5910. if self.call_source == 'app':
  5911. if self.click_noproject is False:
  5912. # if the Tool Tab is in focus don't change focus to Project Tab
  5913. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5914. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5915. else:
  5916. # restore auto open the Project Tab
  5917. self.click_noproject = False
  5918. # delete any text in the status bar, implicitly the last object name that was selected
  5919. # self.inform.emit("")
  5920. else:
  5921. self.call_source = 'app'
  5922. except Exception as e:
  5923. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5924. def selected_message(self, curr_sel_obj):
  5925. if curr_sel_obj:
  5926. if curr_sel_obj.kind == 'gerber':
  5927. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5928. color='green',
  5929. name=str(curr_sel_obj.options['name']),
  5930. tx=_("selected"))
  5931. )
  5932. elif curr_sel_obj.kind == 'excellon':
  5933. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5934. color='brown',
  5935. name=str(curr_sel_obj.options['name']),
  5936. tx=_("selected"))
  5937. )
  5938. elif curr_sel_obj.kind == 'cncjob':
  5939. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5940. color='blue',
  5941. name=str(curr_sel_obj.options['name']),
  5942. tx=_("selected"))
  5943. )
  5944. elif curr_sel_obj.kind == 'geometry':
  5945. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5946. color='red',
  5947. name=str(curr_sel_obj.options['name']),
  5948. tx=_("selected"))
  5949. )
  5950. def delete_hover_shape(self):
  5951. self.hover_shapes.clear()
  5952. self.hover_shapes.redraw()
  5953. def draw_hover_shape(self, sel_obj, color=None):
  5954. """
  5955. :param sel_obj: The object for which the hover shape must be drawn
  5956. :param color: The color of the hover shape
  5957. :return: None
  5958. """
  5959. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5960. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5961. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5962. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5963. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5964. if self.defaults['units'].upper() == 'MM':
  5965. hover_rect = hover_rect.buffer(-0.1)
  5966. hover_rect = hover_rect.buffer(0.2)
  5967. else:
  5968. hover_rect = hover_rect.buffer(-0.00393)
  5969. hover_rect = hover_rect.buffer(0.00787)
  5970. # if color:
  5971. # face = Color(color)
  5972. # face.alpha = 0.2
  5973. # outline = Color(color, alpha=0.8)
  5974. # else:
  5975. # face = Color(self.defaults['global_sel_fill'])
  5976. # face.alpha = 0.2
  5977. # outline = self.defaults['global_sel_line']
  5978. if color:
  5979. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5980. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5981. else:
  5982. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5983. outline = self.defaults['global_sel_line']
  5984. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5985. if self.is_legacy is True:
  5986. self.hover_shapes.redraw()
  5987. def delete_selection_shape(self):
  5988. self.move_tool.sel_shapes.clear()
  5989. self.move_tool.sel_shapes.redraw()
  5990. def draw_selection_shape(self, sel_obj, color=None):
  5991. """
  5992. Will draw a selection shape around the selected object.
  5993. :param sel_obj: The object for which the selection shape must be drawn
  5994. :param color: The color for the selection shape.
  5995. :return: None
  5996. """
  5997. if sel_obj is None:
  5998. return
  5999. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6000. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6001. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6002. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6003. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6004. if self.defaults['units'].upper() == 'MM':
  6005. sel_rect = sel_rect.buffer(-0.1)
  6006. sel_rect = sel_rect.buffer(0.2)
  6007. else:
  6008. sel_rect = sel_rect.buffer(-0.00393)
  6009. sel_rect = sel_rect.buffer(0.00787)
  6010. if color:
  6011. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6012. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6013. else:
  6014. if self.is_legacy is False:
  6015. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6016. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  6017. else:
  6018. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  6019. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  6020. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6021. color=outline,
  6022. face_color=face,
  6023. update=True,
  6024. layer=0,
  6025. tolerance=None))
  6026. if self.is_legacy is True:
  6027. self.move_tool.sel_shapes.redraw()
  6028. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6029. """
  6030. Will draw a selection shape when dragging mouse on canvas.
  6031. :param old_coords: Old coordinates
  6032. :param coords: New coordinates
  6033. :param kwargs: Keyword arguments
  6034. :return:
  6035. """
  6036. if 'color' in kwargs:
  6037. color = kwargs['color']
  6038. else:
  6039. color = self.defaults['global_sel_line']
  6040. if 'face_color' in kwargs:
  6041. face_color = kwargs['face_color']
  6042. else:
  6043. face_color = self.defaults['global_sel_fill']
  6044. if 'face_alpha' in kwargs:
  6045. face_alpha = kwargs['face_alpha']
  6046. else:
  6047. face_alpha = 0.3
  6048. x0, y0 = old_coords
  6049. x1, y1 = coords
  6050. pt1 = (x0, y0)
  6051. pt2 = (x1, y0)
  6052. pt3 = (x1, y1)
  6053. pt4 = (x0, y1)
  6054. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6055. # color_t = Color(face_color)
  6056. # color_t.alpha = face_alpha
  6057. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  6058. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6059. layer=0, tolerance=None)
  6060. if self.is_legacy is True:
  6061. self.move_tool.sel_shapes.redraw()
  6062. def on_file_new_click(self):
  6063. """
  6064. Callback for menu item File -> New.
  6065. Executed on clicking the Menu -> File -> New Project
  6066. :return:
  6067. """
  6068. if self.collection.get_list() and self.should_we_save:
  6069. msgbox = QtWidgets.QMessageBox()
  6070. # msgbox.setText("<B>Save changes ...</B>")
  6071. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6072. "Creating a New project will delete them.\n"
  6073. "Do you want to Save the project?"))
  6074. msgbox.setWindowTitle(_("Save changes"))
  6075. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6076. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6077. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6078. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6079. msgbox.setDefaultButton(bt_yes)
  6080. msgbox.exec_()
  6081. response = msgbox.clickedButton()
  6082. if response == bt_yes:
  6083. self.on_file_saveprojectas()
  6084. elif response == bt_cancel:
  6085. return
  6086. elif response == bt_no:
  6087. self.on_file_new()
  6088. else:
  6089. self.on_file_new()
  6090. self.inform.emit('[success] %s...' % _("New Project created"))
  6091. def on_file_new(self, cli=None):
  6092. """
  6093. Returns the application to its startup state. This method is thread-safe.
  6094. :param cli: Boolean. If True this method was run from command line
  6095. :return: None
  6096. """
  6097. self.defaults.report_usage("on_file_new")
  6098. # Remove everything from memory
  6099. App.log.debug("on_file_new()")
  6100. # close any editor that might be open
  6101. if self.call_source != 'app':
  6102. self.editor2object(cleanup=True)
  6103. # ## EDITOR section
  6104. self.geo_editor = FlatCAMGeoEditor(self)
  6105. self.exc_editor = FlatCAMExcEditor(self)
  6106. self.grb_editor = FlatCAMGrbEditor(self)
  6107. # Clear pool
  6108. self.clear_pool()
  6109. for obj in self.collection.get_list():
  6110. # delete shapes left drawn from mark shape_collections, if any
  6111. if isinstance(obj, GerberObject):
  6112. try:
  6113. for el in obj.mark_shapes:
  6114. obj.mark_shapes[el].clear(update=True)
  6115. obj.mark_shapes[el].enabled = False
  6116. del el
  6117. except AttributeError:
  6118. pass
  6119. # also delete annotation shapes, if any
  6120. elif isinstance(obj, CNCJobObject):
  6121. try:
  6122. obj.text_col.enabled = False
  6123. del obj.text_col
  6124. obj.annotation.clear(update=True)
  6125. del obj.annotation
  6126. except AttributeError:
  6127. pass
  6128. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6129. self.shell.init_tcl()
  6130. # delete any selection shape on canvas
  6131. self.delete_selection_shape()
  6132. # delete all FlatCAM objects
  6133. self.collection.delete_all()
  6134. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  6135. self.setup_component_editor()
  6136. # Clear project filename
  6137. self.project_filename = None
  6138. # Load the application defaults
  6139. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6140. # Re-fresh project options
  6141. self.on_options_app2project()
  6142. # Init FlatCAMTools
  6143. self.init_tools()
  6144. # Try to close all tabs in the PlotArea but only if the GUI is active (CLI is None)
  6145. if cli is None:
  6146. # we need to go in reverse because once we remove a tab then the index changes
  6147. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  6148. # and so on. Therefore the deletion should be done in reverse
  6149. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  6150. for index in range(wdg_count, -1, -1):
  6151. try:
  6152. self.ui.plot_tab_area.closeTab(index)
  6153. except Exception as e:
  6154. log.debug("App.on_file_new() --> %s" % str(e))
  6155. # # And then add again the Plot Area
  6156. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  6157. self.ui.plot_tab_area.protectTab(0)
  6158. # take the focus of the Notebook on Project Tab.
  6159. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6160. self.set_ui_title(name=_("New Project - Not saved"))
  6161. def obj_properties(self):
  6162. """
  6163. Will launch the object Properties Tool
  6164. :return:
  6165. """
  6166. self.defaults.report_usage("obj_properties()")
  6167. self.properties_tool.run(toggle=False)
  6168. def on_project_context_save(self):
  6169. """
  6170. Wrapper, will save the object function of it's type
  6171. :return:
  6172. """
  6173. obj = self.collection.get_active()
  6174. if type(obj) == GeometryObject:
  6175. self.on_file_exportdxf()
  6176. elif type(obj) == ExcellonObject:
  6177. self.on_file_saveexcellon()
  6178. elif type(obj) == CNCJobObject:
  6179. obj.on_exportgcode_button_click()
  6180. elif type(obj) == GerberObject:
  6181. self.on_file_savegerber()
  6182. elif type(obj) == ScriptObject:
  6183. self.on_file_savescript()
  6184. elif type(obj) == DocumentObject:
  6185. self.on_file_savedocument()
  6186. def obj_move(self):
  6187. """
  6188. Callback for the Move menu entry in various Context Menu's.
  6189. :return:
  6190. """
  6191. self.defaults.report_usage("obj_move()")
  6192. self.move_tool.run(toggle=False)
  6193. def on_fileopengerber(self, signal, name=None):
  6194. """
  6195. File menu callback for opening a Gerber.
  6196. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6197. :param name:
  6198. :return: None
  6199. """
  6200. self.defaults.report_usage("on_fileopengerber")
  6201. App.log.debug("on_fileopengerber()")
  6202. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6203. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6204. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6205. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6206. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6207. "*.mil);;" \
  6208. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6209. "Allegro Files (*.art);;" \
  6210. "Mentor Files (*.pho *.gdo);;" \
  6211. "All Files (*.*)"
  6212. if name is None:
  6213. try:
  6214. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6215. directory=self.get_last_folder(),
  6216. filter=_filter_)
  6217. except TypeError:
  6218. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6219. filenames = [str(filename) for filename in filenames]
  6220. else:
  6221. filenames = [name]
  6222. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6223. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6224. _("Opening Gerber file.")),
  6225. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6226. color=QtGui.QColor("gray"))
  6227. if len(filenames) == 0:
  6228. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6229. else:
  6230. for filename in filenames:
  6231. if filename != '':
  6232. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6233. def on_fileopenexcellon(self, signal, name=None):
  6234. """
  6235. File menu callback for opening an Excellon file.
  6236. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6237. :param name:
  6238. :return: None
  6239. """
  6240. self.defaults.report_usage("on_fileopenexcellon")
  6241. App.log.debug("on_fileopenexcellon()")
  6242. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6243. "All Files (*.*)"
  6244. if name is None:
  6245. try:
  6246. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6247. directory=self.get_last_folder(),
  6248. filter=_filter_)
  6249. except TypeError:
  6250. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6251. filenames = [str(filename) for filename in filenames]
  6252. else:
  6253. filenames = [str(name)]
  6254. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6255. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6256. _("Opening Excellon file.")),
  6257. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6258. color=QtGui.QColor("gray"))
  6259. if len(filenames) == 0:
  6260. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6261. else:
  6262. for filename in filenames:
  6263. if filename != '':
  6264. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6265. def on_fileopengcode(self, signal, name=None):
  6266. """
  6267. File menu call back for opening gcode.
  6268. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6269. :param name:
  6270. :return:
  6271. """
  6272. self.defaults.report_usage("on_fileopengcode")
  6273. App.log.debug("on_fileopengcode()")
  6274. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6275. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6276. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6277. "All Files (*.*)"
  6278. if name is None:
  6279. try:
  6280. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6281. directory=self.get_last_folder(),
  6282. filter=_filter_)
  6283. except TypeError:
  6284. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6285. filenames = [str(filename) for filename in filenames]
  6286. else:
  6287. filenames = [name]
  6288. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6289. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6290. _("Opening G-Code file.")),
  6291. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6292. color=QtGui.QColor("gray"))
  6293. if len(filenames) == 0:
  6294. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6295. else:
  6296. for filename in filenames:
  6297. if filename != '':
  6298. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6299. def on_file_openproject(self, signal):
  6300. """
  6301. File menu callback for opening a project.
  6302. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6303. :return: None
  6304. """
  6305. self.defaults.report_usage("on_file_openproject")
  6306. App.log.debug("on_file_openproject()")
  6307. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6308. try:
  6309. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6310. directory=self.get_last_folder(), filter=_filter_)
  6311. except TypeError:
  6312. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6313. # The Qt methods above will return a QString which can cause problems later.
  6314. # So far json.dump() will fail to serialize it.
  6315. # TODO: Improve the serialization methods and remove this fix.
  6316. filename = str(filename)
  6317. if filename == "":
  6318. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6319. else:
  6320. # self.worker_task.emit({'fcn': self.open_project,
  6321. # 'params': [filename]})
  6322. # The above was failing because open_project() is not
  6323. # thread safe. The new_project()
  6324. self.open_project(filename)
  6325. def on_fileopenhpgl2(self, signal, name=None):
  6326. """
  6327. File menu callback for opening a HPGL2.
  6328. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6329. :param name:
  6330. :return: None
  6331. """
  6332. self.defaults.report_usage("on_fileopenhpgl2")
  6333. App.log.debug("on_fileopenhpgl2()")
  6334. _filter_ = "HPGL2 Files (*.plt);;" \
  6335. "All Files (*.*)"
  6336. if name is None:
  6337. try:
  6338. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6339. directory=self.get_last_folder(),
  6340. filter=_filter_)
  6341. except TypeError:
  6342. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6343. filenames = [str(filename) for filename in filenames]
  6344. else:
  6345. filenames = [name]
  6346. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6347. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6348. _("Opening HPGL2 file.")),
  6349. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6350. color=QtGui.QColor("gray"))
  6351. if len(filenames) == 0:
  6352. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6353. else:
  6354. for filename in filenames:
  6355. if filename != '':
  6356. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6357. def on_file_openconfig(self, signal):
  6358. """
  6359. File menu callback for opening a config file.
  6360. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6361. :return: None
  6362. """
  6363. self.defaults.report_usage("on_file_openconfig")
  6364. App.log.debug("on_file_openconfig()")
  6365. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6366. try:
  6367. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6368. directory=self.data_path, filter=_filter_)
  6369. except TypeError:
  6370. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6371. filter=_filter_)
  6372. if filename == "":
  6373. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6374. else:
  6375. self.open_config_file(filename)
  6376. def on_file_exportsvg(self):
  6377. """
  6378. Callback for menu item File->Export SVG.
  6379. :return: None
  6380. """
  6381. self.defaults.report_usage("on_file_exportsvg")
  6382. App.log.debug("on_file_exportsvg()")
  6383. obj = self.collection.get_active()
  6384. if obj is None:
  6385. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6386. msg = _("Please Select a Geometry object to export")
  6387. msgbox = QtWidgets.QMessageBox()
  6388. msgbox.setInformativeText(msg)
  6389. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6390. msgbox.setDefaultButton(bt_ok)
  6391. msgbox.exec_()
  6392. return
  6393. # Check for more compatible types and add as required
  6394. if (not isinstance(obj, GeometryObject)
  6395. and not isinstance(obj, GerberObject)
  6396. and not isinstance(obj, CNCJobObject)
  6397. and not isinstance(obj, ExcellonObject)):
  6398. msg = '[ERROR_NOTCL] %s' % \
  6399. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6400. msgbox = QtWidgets.QMessageBox()
  6401. msgbox.setInformativeText(msg)
  6402. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6403. msgbox.setDefaultButton(bt_ok)
  6404. msgbox.exec_()
  6405. return
  6406. name = obj.options["name"]
  6407. _filter = "SVG File (*.svg);;All Files (*.*)"
  6408. try:
  6409. filename, _f = FCFileSaveDialog.get_saved_filename(
  6410. caption=_("Export SVG"),
  6411. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6412. filter=_filter)
  6413. except TypeError:
  6414. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6415. filename = str(filename)
  6416. if filename == "":
  6417. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6418. return
  6419. else:
  6420. self.export_svg(name, filename)
  6421. if self.defaults["global_open_style"] is False:
  6422. self.file_opened.emit("SVG", filename)
  6423. self.file_saved.emit("SVG", filename)
  6424. def on_file_exportpng(self):
  6425. self.defaults.report_usage("on_file_exportpng")
  6426. App.log.debug("on_file_exportpng()")
  6427. self.date = str(datetime.today()).rpartition('.')[0]
  6428. self.date = ''.join(c for c in self.date if c not in ':-')
  6429. self.date = self.date.replace(' ', '_')
  6430. if self.is_legacy is False:
  6431. image = _screenshot()
  6432. data = np.asarray(image)
  6433. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6434. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6435. return
  6436. filter_ = "PNG File (*.png);;All Files (*.*)"
  6437. try:
  6438. filename, _f = FCFileSaveDialog.get_saved_filename(
  6439. caption=_("Export PNG Image"),
  6440. directory=self.get_last_save_folder() + '/png_' + self.date,
  6441. filter=filter_)
  6442. except TypeError:
  6443. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6444. filename = str(filename)
  6445. if filename == "":
  6446. self.inform.emit(_("Cancelled."))
  6447. return
  6448. else:
  6449. if self.is_legacy is False:
  6450. write_png(filename, data)
  6451. else:
  6452. self.plotcanvas.figure.savefig(filename)
  6453. if self.defaults["global_open_style"] is False:
  6454. self.file_opened.emit("png", filename)
  6455. self.file_saved.emit("png", filename)
  6456. def on_file_savegerber(self):
  6457. """
  6458. Callback for menu item in Project context menu.
  6459. :return: None
  6460. """
  6461. self.defaults.report_usage("on_file_savegerber")
  6462. App.log.debug("on_file_savegerber()")
  6463. obj = self.collection.get_active()
  6464. if obj is None:
  6465. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6466. return
  6467. # Check for more compatible types and add as required
  6468. if not isinstance(obj, GerberObject):
  6469. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6470. return
  6471. name = self.collection.get_active().options["name"]
  6472. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6473. try:
  6474. filename, _f = FCFileSaveDialog.get_saved_filename(
  6475. caption="Save Gerber source file",
  6476. directory=self.get_last_save_folder() + '/' + name,
  6477. filter=_filter)
  6478. except TypeError:
  6479. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6480. filename = str(filename)
  6481. if filename == "":
  6482. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6483. return
  6484. else:
  6485. self.save_source_file(name, filename)
  6486. if self.defaults["global_open_style"] is False:
  6487. self.file_opened.emit("Gerber", filename)
  6488. self.file_saved.emit("Gerber", filename)
  6489. def on_file_savescript(self):
  6490. """
  6491. Callback for menu item in Project context menu.
  6492. :return: None
  6493. """
  6494. self.defaults.report_usage("on_file_savescript")
  6495. App.log.debug("on_file_savescript()")
  6496. obj = self.collection.get_active()
  6497. if obj is None:
  6498. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6499. return
  6500. # Check for more compatible types and add as required
  6501. if not isinstance(obj, ScriptObject):
  6502. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6503. return
  6504. name = self.collection.get_active().options["name"]
  6505. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6506. try:
  6507. filename, _f = FCFileSaveDialog.get_saved_filename(
  6508. caption="Save Script source file",
  6509. directory=self.get_last_save_folder() + '/' + name,
  6510. filter=_filter)
  6511. except TypeError:
  6512. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6513. filename = str(filename)
  6514. if filename == "":
  6515. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6516. return
  6517. else:
  6518. self.save_source_file(name, filename)
  6519. if self.defaults["global_open_style"] is False:
  6520. self.file_opened.emit("Script", filename)
  6521. self.file_saved.emit("Script", filename)
  6522. def on_file_savedocument(self):
  6523. """
  6524. Callback for menu item in Project context menu.
  6525. :return: None
  6526. """
  6527. self.defaults.report_usage("on_file_savedocument")
  6528. App.log.debug("on_file_savedocument()")
  6529. obj = self.collection.get_active()
  6530. if obj is None:
  6531. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6532. return
  6533. # Check for more compatible types and add as required
  6534. if not isinstance(obj, ScriptObject):
  6535. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6536. return
  6537. name = self.collection.get_active().options["name"]
  6538. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6539. try:
  6540. filename, _f = FCFileSaveDialog.get_saved_filename(
  6541. caption="Save Document source file",
  6542. directory=self.get_last_save_folder() + '/' + name,
  6543. filter=_filter)
  6544. except TypeError:
  6545. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6546. filename = str(filename)
  6547. if filename == "":
  6548. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6549. return
  6550. else:
  6551. self.save_source_file(name, filename)
  6552. if self.defaults["global_open_style"] is False:
  6553. self.file_opened.emit("Document", filename)
  6554. self.file_saved.emit("Document", filename)
  6555. def on_file_saveexcellon(self):
  6556. """
  6557. Callback for menu item in project context menu.
  6558. :return: None
  6559. """
  6560. self.defaults.report_usage("on_file_saveexcellon")
  6561. App.log.debug("on_file_saveexcellon()")
  6562. obj = self.collection.get_active()
  6563. if obj is None:
  6564. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6565. return
  6566. # Check for more compatible types and add as required
  6567. if not isinstance(obj, ExcellonObject):
  6568. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6569. return
  6570. name = self.collection.get_active().options["name"]
  6571. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6572. try:
  6573. filename, _f = FCFileSaveDialog.get_saved_filename(
  6574. caption=_("Save Excellon source file"),
  6575. directory=self.get_last_save_folder() + '/' + name,
  6576. filter=_filter)
  6577. except TypeError:
  6578. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6579. filename = str(filename)
  6580. if filename == "":
  6581. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6582. return
  6583. else:
  6584. self.save_source_file(name, filename)
  6585. if self.defaults["global_open_style"] is False:
  6586. self.file_opened.emit("Excellon", filename)
  6587. self.file_saved.emit("Excellon", filename)
  6588. def on_file_exportexcellon(self):
  6589. """
  6590. Callback for menu item File->Export->Excellon.
  6591. :return: None
  6592. """
  6593. self.defaults.report_usage("on_file_exportexcellon")
  6594. App.log.debug("on_file_exportexcellon()")
  6595. obj = self.collection.get_active()
  6596. if obj is None:
  6597. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6598. return
  6599. # Check for more compatible types and add as required
  6600. if not isinstance(obj, ExcellonObject):
  6601. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6602. return
  6603. name = self.collection.get_active().options["name"]
  6604. _filter = self.defaults["excellon_save_filters"]
  6605. try:
  6606. filename, _f = FCFileSaveDialog.get_saved_filename(
  6607. caption=_("Export Excellon"),
  6608. directory=self.get_last_save_folder() + '/' + name,
  6609. filter=_filter)
  6610. except TypeError:
  6611. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6612. filename = str(filename)
  6613. if filename == "":
  6614. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6615. return
  6616. else:
  6617. used_extension = filename.rpartition('.')[2]
  6618. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6619. self.export_excellon(name, filename)
  6620. if self.defaults["global_open_style"] is False:
  6621. self.file_opened.emit("Excellon", filename)
  6622. self.file_saved.emit("Excellon", filename)
  6623. def on_file_exportgerber(self):
  6624. """
  6625. Callback for menu item File->Export->Gerber.
  6626. :return: None
  6627. """
  6628. self.defaults.report_usage("on_file_exportgerber")
  6629. App.log.debug("on_file_exportgerber()")
  6630. obj = self.collection.get_active()
  6631. if obj is None:
  6632. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6633. return
  6634. # Check for more compatible types and add as required
  6635. if not isinstance(obj, GerberObject):
  6636. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6637. return
  6638. name = self.collection.get_active().options["name"]
  6639. _filter_ = self.defaults['gerber_save_filters']
  6640. try:
  6641. filename, _f = FCFileSaveDialog.get_saved_filename(
  6642. caption=_("Export Gerber"),
  6643. directory=self.get_last_save_folder() + '/' + name,
  6644. filter=_filter_)
  6645. except TypeError:
  6646. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6647. filename = str(filename)
  6648. if filename == "":
  6649. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6650. return
  6651. else:
  6652. used_extension = filename.rpartition('.')[2]
  6653. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6654. self.export_gerber(name, filename)
  6655. if self.defaults["global_open_style"] is False:
  6656. self.file_opened.emit("Gerber", filename)
  6657. self.file_saved.emit("Gerber", filename)
  6658. def on_file_exportdxf(self):
  6659. """
  6660. Callback for menu item File->Export DXF.
  6661. :return: None
  6662. """
  6663. self.defaults.report_usage("on_file_exportdxf")
  6664. App.log.debug("on_file_exportdxf()")
  6665. obj = self.collection.get_active()
  6666. if obj is None:
  6667. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6668. msg = _("Please Select a Geometry object to export")
  6669. msgbox = QtWidgets.QMessageBox()
  6670. msgbox.setInformativeText(msg)
  6671. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6672. msgbox.setDefaultButton(bt_ok)
  6673. msgbox.exec_()
  6674. return
  6675. # Check for more compatible types and add as required
  6676. if not isinstance(obj, GeometryObject):
  6677. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6678. msgbox = QtWidgets.QMessageBox()
  6679. msgbox.setInformativeText(msg)
  6680. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6681. msgbox.setDefaultButton(bt_ok)
  6682. msgbox.exec_()
  6683. return
  6684. name = self.collection.get_active().options["name"]
  6685. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6686. try:
  6687. filename, _f = FCFileSaveDialog.get_saved_filename(
  6688. caption=_("Export DXF"),
  6689. directory=self.get_last_save_folder() + '/' + name,
  6690. filter=_filter_)
  6691. except TypeError:
  6692. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6693. filename = str(filename)
  6694. if filename == "":
  6695. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6696. return
  6697. else:
  6698. self.export_dxf(name, filename)
  6699. if self.defaults["global_open_style"] is False:
  6700. self.file_opened.emit("DXF", filename)
  6701. self.file_saved.emit("DXF", filename)
  6702. def on_file_importsvg(self, type_of_obj):
  6703. """
  6704. Callback for menu item File->Import SVG.
  6705. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6706. :type type_of_obj: str
  6707. :return: None
  6708. """
  6709. self.defaults.report_usage("on_file_importsvg")
  6710. App.log.debug("on_file_importsvg()")
  6711. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6712. try:
  6713. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6714. directory=self.get_last_folder(), filter=_filter_)
  6715. except TypeError:
  6716. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6717. filter=_filter_)
  6718. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6719. type_of_obj = "geometry"
  6720. filenames = [str(filename) for filename in filenames]
  6721. if len(filenames) == 0:
  6722. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6723. else:
  6724. for filename in filenames:
  6725. if filename != '':
  6726. self.worker_task.emit({'fcn': self.import_svg,
  6727. 'params': [filename, type_of_obj]})
  6728. def on_file_importdxf(self, type_of_obj):
  6729. """
  6730. Callback for menu item File->Import DXF.
  6731. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6732. :type type_of_obj: str
  6733. :return: None
  6734. """
  6735. self.defaults.report_usage("on_file_importdxf")
  6736. App.log.debug("on_file_importdxf()")
  6737. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6738. try:
  6739. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6740. directory=self.get_last_folder(),
  6741. filter=_filter_)
  6742. except TypeError:
  6743. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6744. filter=_filter_)
  6745. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6746. type_of_obj = "geometry"
  6747. filenames = [str(filename) for filename in filenames]
  6748. if len(filenames) == 0:
  6749. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6750. else:
  6751. for filename in filenames:
  6752. if filename != '':
  6753. self.worker_task.emit({'fcn': self.import_dxf,
  6754. 'params': [filename, type_of_obj]})
  6755. # ###############################################################################################################
  6756. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6757. # ###############################################################################################################
  6758. def init_code_editor(self, name):
  6759. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6760. # add the tab if it was closed
  6761. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6762. self.text_editor_tab.setObjectName('text_editor_tab')
  6763. # delete the absolute and relative position and messages in the infobar
  6764. self.ui.position_label.setText("")
  6765. self.ui.rel_position_label.setText("")
  6766. # first clear previous text in text editor (if any)
  6767. self.text_editor_tab.code_editor.clear()
  6768. self.text_editor_tab.code_editor.setReadOnly(False)
  6769. self.toggle_codeeditor = True
  6770. self.text_editor_tab.code_editor.completer_enable = False
  6771. self.text_editor_tab.buttonRun.hide()
  6772. # make sure to keep a reference to the code editor
  6773. self.reference_code_editor = self.text_editor_tab.code_editor
  6774. # Switch plot_area to CNCJob tab
  6775. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6776. def on_view_source(self):
  6777. """
  6778. Called when the user wants to see the source file of the selected object
  6779. :return:
  6780. """
  6781. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6782. self.proc_container.view.set_busy(_("Loading..."))
  6783. try:
  6784. obj = self.collection.get_active()
  6785. except Exception as e:
  6786. log.debug("App.on_view_source() --> %s" % str(e))
  6787. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6788. return 'fail'
  6789. if obj is None:
  6790. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6791. return 'fail'
  6792. flt = "All Files (*.*)"
  6793. if obj.kind == 'gerber':
  6794. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6795. elif obj.kind == 'excellon':
  6796. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6797. elif obj.kind == 'cncjob':
  6798. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6799. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6800. # add the tab if it was closed
  6801. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6802. self.source_editor_tab.setObjectName('source_editor_tab')
  6803. # delete the absolute and relative position and messages in the infobar
  6804. self.ui.position_label.setText("")
  6805. self.ui.rel_position_label.setText("")
  6806. # first clear previous text in text editor (if any)
  6807. self.source_editor_tab.code_editor.clear()
  6808. self.source_editor_tab.code_editor.setReadOnly(False)
  6809. self.source_editor_tab.code_editor.completer_enable = False
  6810. self.source_editor_tab.buttonRun.hide()
  6811. # Switch plot_area to CNCJob tab
  6812. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6813. try:
  6814. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6815. except TypeError:
  6816. pass
  6817. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6818. try:
  6819. self.source_editor_tab.buttonSave.clicked.disconnect()
  6820. except TypeError:
  6821. pass
  6822. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6823. # then append the text from GCode to the text editor
  6824. if obj.kind == 'cncjob':
  6825. try:
  6826. file = obj.export_gcode(
  6827. preamble=self.defaults["cncjob_prepend"],
  6828. postamble=self.defaults["cncjob_append"],
  6829. to_file=True)
  6830. if file == 'fail':
  6831. return 'fail'
  6832. except AttributeError:
  6833. self.inform.emit('[WARNING_NOTCL] %s' %
  6834. _("There is no selected object for which to see it's source file code."))
  6835. return 'fail'
  6836. else:
  6837. try:
  6838. file = StringIO(obj.source_file)
  6839. except (AttributeError, TypeError):
  6840. self.inform.emit('[WARNING_NOTCL] %s' %
  6841. _("There is no selected object for which to see it's source file code."))
  6842. return 'fail'
  6843. self.source_editor_tab.t_frame.hide()
  6844. try:
  6845. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6846. # for line in file:
  6847. # QtWidgets.QApplication.processEvents()
  6848. # proc_line = str(line).strip('\n')
  6849. # self.source_editor_tab.code_editor.append(proc_line)
  6850. except Exception as e:
  6851. log.debug('App.on_view_source() -->%s' % str(e))
  6852. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6853. return
  6854. self.source_editor_tab.handleTextChanged()
  6855. self.source_editor_tab.t_frame.show()
  6856. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6857. self.proc_container.view.set_idle()
  6858. # self.ui.show()
  6859. def on_toggle_code_editor(self):
  6860. self.defaults.report_usage("on_toggle_code_editor()")
  6861. if self.toggle_codeeditor is False:
  6862. self.init_code_editor(name=_("Code Editor"))
  6863. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6864. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6865. self.text_editor_tab.buttonSave.clicked.disconnect()
  6866. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6867. else:
  6868. for idx in range(self.ui.plot_tab_area.count()):
  6869. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6870. self.ui.plot_tab_area.closeTab(idx)
  6871. break
  6872. self.toggle_codeeditor = False
  6873. def on_code_editor_close(self):
  6874. self.toggle_codeeditor = False
  6875. def goto_text_line(self):
  6876. """
  6877. Will scroll a text to the specified text line.
  6878. :return: None
  6879. """
  6880. dia_box = Dialog_box(title=_("Go to Line ..."),
  6881. label=_("Line:"),
  6882. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6883. initial_text='')
  6884. try:
  6885. line = int(dia_box.location) - 1
  6886. except (ValueError, TypeError):
  6887. line = 0
  6888. if dia_box.ok:
  6889. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6890. # at the top of the window
  6891. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6892. # get the document() of the TextEditor
  6893. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6894. # create a Text Cursor based on the searched line
  6895. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6896. # set cursor of the code editor with the cursor at the searcehd line
  6897. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6898. def on_filenewscript(self, silent=False):
  6899. """
  6900. Will create a new script file and open it in the Code Editor
  6901. :param silent: if True will not display status messages
  6902. :param name: if specified will be the name of the new script
  6903. :param text: pass a source file to the newly created script to be loaded in it
  6904. :return: None
  6905. """
  6906. if silent is False:
  6907. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6908. # delete the absolute and relative position and messages in the infobar
  6909. self.ui.position_label.setText("")
  6910. self.ui.rel_position_label.setText("")
  6911. self.new_script_object()
  6912. # script_text = script_obj.source_file
  6913. #
  6914. # self.proc_container.view.set_busy(_("Loading..."))
  6915. # script_obj.script_editor_tab.t_frame.hide()
  6916. #
  6917. # script_obj.script_editor_tab.t_frame.show()
  6918. # self.proc_container.view.set_idle()
  6919. def on_fileopenscript(self, name=None, silent=False):
  6920. """
  6921. Will open a Tcl script file into the Code Editor
  6922. :param silent: if True will not display status messages
  6923. :param name: name of a Tcl script file to open
  6924. :return: None
  6925. """
  6926. self.defaults.report_usage("on_fileopenscript")
  6927. App.log.debug("on_fileopenscript()")
  6928. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6929. "All Files (*.*)"
  6930. if name:
  6931. filenames = [name]
  6932. else:
  6933. try:
  6934. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6935. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6936. except TypeError:
  6937. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6938. if len(filenames) == 0:
  6939. if silent is False:
  6940. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6941. else:
  6942. for filename in filenames:
  6943. if filename != '':
  6944. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6945. def on_fileopenscript_example(self, name=None, silent=False):
  6946. """
  6947. Will open a Tcl script file into the Code Editor
  6948. :param silent: if True will not display status messages
  6949. :param name: name of a Tcl script file to open
  6950. :return:
  6951. """
  6952. self.defaults.report_usage("on_fileopenscript_example")
  6953. log.debug("on_fileopenscript_example()")
  6954. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6955. "All Files (*.*)"
  6956. # test if the app was frozen and choose the path for the configuration file
  6957. if getattr(sys, "frozen", False) is True:
  6958. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6959. else:
  6960. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6961. if name:
  6962. filenames = [name]
  6963. else:
  6964. try:
  6965. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6966. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6967. except TypeError:
  6968. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6969. if len(filenames) == 0:
  6970. if silent is False:
  6971. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6972. else:
  6973. for filename in filenames:
  6974. if filename != '':
  6975. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6976. def on_filerunscript(self, name=None, silent=False):
  6977. """
  6978. File menu callback for loading and running a TCL script.
  6979. :param silent: if True will not display status messages
  6980. :param name: name of a Tcl script file to be run by FlatCAM
  6981. :return: None
  6982. """
  6983. self.defaults.report_usage("on_filerunscript")
  6984. App.log.debug("on_file_runscript()")
  6985. if name:
  6986. filename = name
  6987. if self.cmd_line_headless != 1:
  6988. self.splash.showMessage('%s: %ssec\n%s' %
  6989. (_("Canvas initialization started.\n"
  6990. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6991. _("Executing ScriptObject file.")
  6992. ),
  6993. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6994. color=QtGui.QColor("gray"))
  6995. else:
  6996. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6997. "All Files (*.*)"
  6998. try:
  6999. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7000. directory=self.get_last_folder(), filter=_filter_)
  7001. except TypeError:
  7002. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7003. # The Qt methods above will return a QString which can cause problems later.
  7004. # So far json.dump() will fail to serialize it.
  7005. filename = str(filename)
  7006. if filename == "":
  7007. if silent is False:
  7008. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7009. else:
  7010. if self.cmd_line_headless != 1:
  7011. if self.ui.shell_dock.isHidden():
  7012. self.ui.shell_dock.show()
  7013. try:
  7014. with open(filename, "r") as tcl_script:
  7015. cmd_line_shellfile_content = tcl_script.read()
  7016. if self.cmd_line_headless != 1:
  7017. self.shell.exec_command(cmd_line_shellfile_content)
  7018. else:
  7019. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7020. if silent is False:
  7021. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7022. except Exception as e:
  7023. log.debug("App.on_filerunscript() -> %s" % str(e))
  7024. sys.exit(2)
  7025. def on_file_saveproject(self, silent=False):
  7026. """
  7027. Callback for menu item File->Save Project. Saves the project to
  7028. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7029. if set to None. The project is saved by calling ``self.save_project()``.
  7030. :param silent: if True will not display status messages
  7031. :return: None
  7032. """
  7033. self.defaults.report_usage("on_file_saveproject")
  7034. if self.project_filename is None:
  7035. self.on_file_saveprojectas()
  7036. else:
  7037. self.worker_task.emit({'fcn': self.save_project,
  7038. 'params': [self.project_filename, silent]})
  7039. if self.defaults["global_open_style"] is False:
  7040. self.file_opened.emit("project", self.project_filename)
  7041. self.file_saved.emit("project", self.project_filename)
  7042. self.set_ui_title(name=self.project_filename)
  7043. self.should_we_save = False
  7044. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7045. """
  7046. Callback for menu item File->Save Project As... Opens a file
  7047. chooser and saves the project to the given file via
  7048. ``self.save_project()``.
  7049. :param make_copy if to be create a copy of the project; boolean
  7050. :param use_thread: if to be run in a separate thread; boolean
  7051. :param quit_action: if to be followed by quiting the application; boolean
  7052. :return: None
  7053. """
  7054. self.defaults.report_usage("on_file_saveprojectas")
  7055. self.date = str(datetime.today()).rpartition('.')[0]
  7056. self.date = ''.join(c for c in self.date if c not in ':-')
  7057. self.date = self.date.replace(' ', '_')
  7058. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7059. try:
  7060. filename, _f = FCFileSaveDialog.get_saved_filename(
  7061. caption=_("Save Project As ..."),
  7062. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  7063. proj=_("Project")),
  7064. filter=filter_
  7065. )
  7066. except TypeError:
  7067. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  7068. filename = str(filename)
  7069. if filename == '':
  7070. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7071. return
  7072. if use_thread is True:
  7073. self.worker_task.emit({'fcn': self.save_project,
  7074. 'params': [filename, quit_action]})
  7075. else:
  7076. self.save_project(filename, quit_action)
  7077. # self.save_project(filename)
  7078. if self.defaults["global_open_style"] is False:
  7079. self.file_opened.emit("project", filename)
  7080. self.file_saved.emit("project", filename)
  7081. if not make_copy:
  7082. self.project_filename = filename
  7083. self.set_ui_title(name=self.project_filename)
  7084. self.should_we_save = False
  7085. def on_file_save_objects_pdf(self, use_thread=True):
  7086. self.date = str(datetime.today()).rpartition('.')[0]
  7087. self.date = ''.join(c for c in self.date if c not in ':-')
  7088. self.date = self.date.replace(' ', '_')
  7089. try:
  7090. obj_selection = self.collection.get_selected()
  7091. if len(obj_selection) == 1:
  7092. obj_name = str(obj_selection[0].options['name'])
  7093. else:
  7094. obj_name = _("FlatCAM objects print")
  7095. except AttributeError as err:
  7096. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7097. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7098. return
  7099. if not obj_selection:
  7100. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7101. return
  7102. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7103. try:
  7104. filename, _f = FCFileSaveDialog.get_saved_filename(
  7105. caption=_("Save Object as PDF ..."),
  7106. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7107. obj_name=obj_name,
  7108. date=self.date),
  7109. filter=filter_
  7110. )
  7111. except TypeError:
  7112. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7113. filename = str(filename)
  7114. if filename == '':
  7115. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7116. return
  7117. if use_thread is True:
  7118. self.proc_container.new(_("Printing PDF ... Please wait."))
  7119. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7120. else:
  7121. self.save_pdf(filename, obj_selection)
  7122. # self.save_project(filename)
  7123. if self.defaults["global_open_style"] is False:
  7124. self.file_opened.emit("pdf", filename)
  7125. self.file_saved.emit("pdf", filename)
  7126. def save_pdf(self, file_name, obj_selection):
  7127. p_size = self.defaults['global_workspaceT']
  7128. orientation = self.defaults['global_workspace_orientation']
  7129. color = 'black'
  7130. transparency_level = 1.0
  7131. self.pagesize = {}
  7132. self.pagesize.update(
  7133. {
  7134. 'Bounds': None,
  7135. 'A0': (841 * mm, 1189 * mm),
  7136. 'A1': (594 * mm, 841 * mm),
  7137. 'A2': (420 * mm, 594 * mm),
  7138. 'A3': (297 * mm, 420 * mm),
  7139. 'A4': (210 * mm, 297 * mm),
  7140. 'A5': (148 * mm, 210 * mm),
  7141. 'A6': (105 * mm, 148 * mm),
  7142. 'A7': (74 * mm, 105 * mm),
  7143. 'A8': (52 * mm, 74 * mm),
  7144. 'A9': (37 * mm, 52 * mm),
  7145. 'A10': (26 * mm, 37 * mm),
  7146. 'B0': (1000 * mm, 1414 * mm),
  7147. 'B1': (707 * mm, 1000 * mm),
  7148. 'B2': (500 * mm, 707 * mm),
  7149. 'B3': (353 * mm, 500 * mm),
  7150. 'B4': (250 * mm, 353 * mm),
  7151. 'B5': (176 * mm, 250 * mm),
  7152. 'B6': (125 * mm, 176 * mm),
  7153. 'B7': (88 * mm, 125 * mm),
  7154. 'B8': (62 * mm, 88 * mm),
  7155. 'B9': (44 * mm, 62 * mm),
  7156. 'B10': (31 * mm, 44 * mm),
  7157. 'C0': (917 * mm, 1297 * mm),
  7158. 'C1': (648 * mm, 917 * mm),
  7159. 'C2': (458 * mm, 648 * mm),
  7160. 'C3': (324 * mm, 458 * mm),
  7161. 'C4': (229 * mm, 324 * mm),
  7162. 'C5': (162 * mm, 229 * mm),
  7163. 'C6': (114 * mm, 162 * mm),
  7164. 'C7': (81 * mm, 114 * mm),
  7165. 'C8': (57 * mm, 81 * mm),
  7166. 'C9': (40 * mm, 57 * mm),
  7167. 'C10': (28 * mm, 40 * mm),
  7168. # American paper sizes
  7169. 'LETTER': (8.5 * inch, 11 * inch),
  7170. 'LEGAL': (8.5 * inch, 14 * inch),
  7171. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7172. # From https://en.wikipedia.org/wiki/Paper_size
  7173. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7174. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7175. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7176. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7177. 'LEDGER': (17 * inch, 11 * inch),
  7178. }
  7179. )
  7180. exported_svg = []
  7181. for obj in obj_selection:
  7182. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7183. scale_factor_x=None, scale_factor_y=None,
  7184. skew_factor_x=None, skew_factor_y=None,
  7185. mirror=None)
  7186. if obj.kind.lower() == 'gerber':
  7187. # color = self.defaults["gerber_plot_fill"][:-2]
  7188. color = obj.fill_color[:-2]
  7189. elif obj.kind.lower() == 'excellon':
  7190. color = '#C40000'
  7191. elif obj.kind.lower() == 'geometry':
  7192. color = self.defaults["global_draw_color"]
  7193. # Change the attributes of the exported SVG
  7194. # We don't need stroke-width
  7195. # We set opacity to maximum
  7196. # We set the colour to WHITE
  7197. root = ET.fromstring(svg_obj)
  7198. for child in root:
  7199. child.set('fill', str(color))
  7200. child.set('opacity', str(transparency_level))
  7201. child.set('stroke', str(color))
  7202. exported_svg.append(ET.tostring(root))
  7203. xmin = Inf
  7204. ymin = Inf
  7205. xmax = -Inf
  7206. ymax = -Inf
  7207. for obj in obj_selection:
  7208. try:
  7209. gxmin, gymin, gxmax, gymax = obj.bounds()
  7210. xmin = min([xmin, gxmin])
  7211. ymin = min([ymin, gymin])
  7212. xmax = max([xmax, gxmax])
  7213. ymax = max([ymax, gymax])
  7214. except Exception as e:
  7215. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7216. # Determine bounding area for svg export
  7217. bounds = [xmin, ymin, xmax, ymax]
  7218. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7219. # This contain the measure units
  7220. uom = obj_selection[0].units.lower()
  7221. # Define a boundary around SVG of about 1.0mm (~39mils)
  7222. if uom in "mm":
  7223. boundary = 1.0
  7224. else:
  7225. boundary = 0.0393701
  7226. # Convert everything to strings for use in the xml doc
  7227. svgwidth = str(size[0] + (2 * boundary))
  7228. svgheight = str(size[1] + (2 * boundary))
  7229. minx = str(bounds[0] - boundary)
  7230. miny = str(bounds[1] + boundary + size[1])
  7231. # Add a SVG Header and footer to the svg output from shapely
  7232. # The transform flips the Y Axis so that everything renders
  7233. # properly within svg apps such as inkscape
  7234. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7235. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7236. svg_header += 'width="' + svgwidth + uom + '" '
  7237. svg_header += 'height="' + svgheight + uom + '" '
  7238. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7239. svg_header += '>'
  7240. svg_header += '<g transform="scale(1,-1)">'
  7241. svg_footer = '</g> </svg>'
  7242. svg_elem = str(svg_header)
  7243. for svg_item in exported_svg:
  7244. svg_elem += str(svg_item)
  7245. svg_elem += str(svg_footer)
  7246. # Parse the xml through a xml parser just to add line feeds
  7247. # and to make it look more pretty for the output
  7248. doc = parse_xml_string(svg_elem)
  7249. doc_final = doc.toprettyxml()
  7250. try:
  7251. if self.defaults['units'].upper() == 'IN':
  7252. unit = inch
  7253. else:
  7254. unit = mm
  7255. doc_final = StringIO(doc_final)
  7256. drawing = svg2rlg(doc_final)
  7257. if p_size == 'Bounds':
  7258. renderPDF.drawToFile(drawing, file_name)
  7259. else:
  7260. if orientation == 'p':
  7261. page_size = portrait(self.pagesize[p_size])
  7262. else:
  7263. page_size = landscape(self.pagesize[p_size])
  7264. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7265. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7266. renderPDF.draw(drawing, my_canvas, 0, 0)
  7267. my_canvas.save()
  7268. except Exception as e:
  7269. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7270. return 'fail'
  7271. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7272. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7273. """
  7274. Exports a Geometry Object to an SVG file.
  7275. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7276. :param filename: Path to the SVG file to save to.
  7277. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7278. :return:
  7279. """
  7280. self.defaults.report_usage("export_svg()")
  7281. if filename is None:
  7282. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7283. is not None else self.defaults["global_last_folder"]
  7284. self.log.debug("export_svg()")
  7285. try:
  7286. obj = self.collection.get_by_name(str(obj_name))
  7287. except Exception:
  7288. # TODO: The return behavior has not been established... should raise exception?
  7289. return "Could not retrieve object: %s" % obj_name
  7290. with self.proc_container.new(_("Exporting SVG")) as proc:
  7291. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7292. # Determine bounding area for svg export
  7293. bounds = obj.bounds()
  7294. size = obj.size()
  7295. # Convert everything to strings for use in the xml doc
  7296. svgwidth = str(size[0])
  7297. svgheight = str(size[1])
  7298. minx = str(bounds[0])
  7299. miny = str(bounds[1] - size[1])
  7300. uom = obj.units.lower()
  7301. # Add a SVG Header and footer to the svg output from shapely
  7302. # The transform flips the Y Axis so that everything renders
  7303. # properly within svg apps such as inkscape
  7304. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7305. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7306. svg_header += 'width="' + svgwidth + uom + '" '
  7307. svg_header += 'height="' + svgheight + uom + '" '
  7308. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7309. svg_header += '<g transform="scale(1,-1)">'
  7310. svg_footer = '</g> </svg>'
  7311. svg_elem = svg_header + exported_svg + svg_footer
  7312. # Parse the xml through a xml parser just to add line feeds
  7313. # and to make it look more pretty for the output
  7314. svgcode = parse_xml_string(svg_elem)
  7315. svgcode = svgcode.toprettyxml()
  7316. try:
  7317. with open(filename, 'w') as fp:
  7318. fp.write(svgcode)
  7319. except PermissionError:
  7320. self.inform.emit('[WARNING] %s' %
  7321. _("Permission denied, saving not possible.\n"
  7322. "Most likely another app is holding the file open and not accessible."))
  7323. return 'fail'
  7324. if self.defaults["global_open_style"] is False:
  7325. self.file_opened.emit("SVG", filename)
  7326. self.file_saved.emit("SVG", filename)
  7327. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7328. def save_source_file(self, obj_name, filename, use_thread=True):
  7329. """
  7330. Exports a FlatCAM Object to an Gerber/Excellon file.
  7331. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7332. :param filename: Path to the Gerber file to save to.
  7333. :param use_thread: if to be run in a separate thread
  7334. :return:
  7335. """
  7336. self.defaults.report_usage("save source file()")
  7337. if filename is None:
  7338. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7339. is not None else self.defaults["global_last_folder"]
  7340. self.log.debug("save source file()")
  7341. obj = self.collection.get_by_name(obj_name)
  7342. file_string = StringIO(obj.source_file)
  7343. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7344. if file_string.getvalue() == '':
  7345. self.inform.emit('[ERROR_NOTCL] %s' %
  7346. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7347. return 'fail'
  7348. try:
  7349. with open(filename, 'w') as file:
  7350. file.writelines('G04*\n')
  7351. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7352. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7353. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7354. file.writelines('G04 Created on : %s*\n' % time_string)
  7355. for line in file_string:
  7356. file.writelines(line)
  7357. except PermissionError:
  7358. self.inform.emit('[WARNING] %s' %
  7359. _("Permission denied, saving not possible.\n"
  7360. "Most likely another app is holding the file open and not accessible."))
  7361. return 'fail'
  7362. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7363. """
  7364. Exports a Excellon Object to an Excellon file.
  7365. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7366. :param filename: Path to the Excellon file to save to.
  7367. :param local_use:
  7368. :param use_thread: if to be run in a separate thread
  7369. :return:
  7370. """
  7371. self.defaults.report_usage("export_excellon()")
  7372. if filename is None:
  7373. if self.defaults["global_last_save_folder"]:
  7374. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7375. else:
  7376. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7377. self.log.debug("export_excellon()")
  7378. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7379. self.defaults["excellon_exp_decimals"]
  7380. )
  7381. if local_use is None:
  7382. try:
  7383. obj = self.collection.get_by_name(str(obj_name))
  7384. except Exception:
  7385. return "Could not retrieve object: %s" % obj_name
  7386. else:
  7387. obj = local_use
  7388. if not isinstance(obj, ExcellonObject):
  7389. self.inform.emit('[ERROR_NOTCL] %s' %
  7390. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7391. return
  7392. # updated units
  7393. eunits = self.defaults["excellon_exp_units"]
  7394. ewhole = self.defaults["excellon_exp_integer"]
  7395. efract = self.defaults["excellon_exp_decimals"]
  7396. ezeros = self.defaults["excellon_exp_zeros"]
  7397. eformat = self.defaults["excellon_exp_format"]
  7398. slot_type = self.defaults["excellon_exp_slot_type"]
  7399. fc_units = self.defaults['units'].upper()
  7400. if fc_units == 'MM':
  7401. factor = 1 if eunits == 'METRIC' else 0.03937
  7402. else:
  7403. factor = 25.4 if eunits == 'METRIC' else 1
  7404. def make_excellon():
  7405. try:
  7406. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7407. header = 'M48\n'
  7408. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7409. (str(self.version), str(self.version_date))
  7410. header += ';Filename: %s' % str(obj_name) + '\n'
  7411. header += ';Created on : %s' % time_str + '\n'
  7412. if eformat == 'dec':
  7413. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7414. header += eunits + '\n'
  7415. for tool in obj.tools:
  7416. if eunits == 'METRIC':
  7417. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7418. tool=str(tool),
  7419. dec=2)
  7420. else:
  7421. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7422. tool=str(tool),
  7423. dec=4)
  7424. else:
  7425. if ezeros == 'LZ':
  7426. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7427. form='ndec', e_zeros='LZ', factor=factor,
  7428. slot_type=slot_type)
  7429. header += '%s,%s\n' % (eunits, 'LZ')
  7430. header += format_exc
  7431. for tool in obj.tools:
  7432. if eunits == 'METRIC':
  7433. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7434. tool=str(tool),
  7435. dec=2)
  7436. else:
  7437. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7438. tool=str(tool),
  7439. dec=4)
  7440. else:
  7441. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7442. form='ndec', e_zeros='TZ', factor=factor,
  7443. slot_type=slot_type)
  7444. header += '%s,%s\n' % (eunits, 'TZ')
  7445. header += format_exc
  7446. for tool in obj.tools:
  7447. if eunits == 'METRIC':
  7448. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7449. tool=str(tool),
  7450. dec=2)
  7451. else:
  7452. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7453. tool=str(tool),
  7454. dec=4)
  7455. header += '%\n'
  7456. footer = 'M30\n'
  7457. exported_excellon = header
  7458. exported_excellon += excellon_code
  7459. exported_excellon += footer
  7460. if local_use is None:
  7461. try:
  7462. with open(filename, 'w') as fp:
  7463. fp.write(exported_excellon)
  7464. except PermissionError:
  7465. self.inform.emit('[WARNING] %s' %
  7466. _("Permission denied, saving not possible.\n"
  7467. "Most likely another app is holding the file open and not accessible."))
  7468. return 'fail'
  7469. if self.defaults["global_open_style"] is False:
  7470. self.file_opened.emit("Excellon", filename)
  7471. self.file_saved.emit("Excellon", filename)
  7472. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7473. else:
  7474. return exported_excellon
  7475. except Exception as e:
  7476. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7477. return 'fail'
  7478. if use_thread is True:
  7479. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7480. def job_thread_exc(app_obj):
  7481. ret = make_excellon()
  7482. if ret == 'fail':
  7483. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7484. return
  7485. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7486. else:
  7487. eret = make_excellon()
  7488. if eret == 'fail':
  7489. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7490. return 'fail'
  7491. if local_use is not None:
  7492. return eret
  7493. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7494. """
  7495. Exports a Gerber Object to an Gerber file.
  7496. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7497. :param filename: Path to the Gerber file to save to.
  7498. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7499. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7500. :param use_thread: if to be run in a separate thread
  7501. :return:
  7502. """
  7503. self.defaults.report_usage("export_gerber()")
  7504. if filename is None:
  7505. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7506. is not None else self.defaults["global_last_folder"]
  7507. self.log.debug("export_gerber()")
  7508. if local_use is None:
  7509. try:
  7510. obj = self.collection.get_by_name(str(obj_name))
  7511. except Exception:
  7512. return "Could not retrieve object: %s" % obj_name
  7513. else:
  7514. obj = local_use
  7515. # updated units
  7516. gunits = self.defaults["gerber_exp_units"]
  7517. gwhole = self.defaults["gerber_exp_integer"]
  7518. gfract = self.defaults["gerber_exp_decimals"]
  7519. gzeros = self.defaults["gerber_exp_zeros"]
  7520. fc_units = self.defaults['units'].upper()
  7521. if fc_units == 'MM':
  7522. factor = 1 if gunits == 'MM' else 0.03937
  7523. else:
  7524. factor = 25.4 if gunits == 'MM' else 1
  7525. def make_gerber():
  7526. try:
  7527. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7528. header = 'G04*\n'
  7529. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7530. (str(self.version), str(self.version_date))
  7531. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7532. header += 'G04 Created on : %s*' % time_str + '\n'
  7533. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7534. header += "%MO{units}*%\n".format(units=gunits)
  7535. for apid in obj.apertures:
  7536. if obj.apertures[apid]['type'] == 'C':
  7537. header += "%ADD{apid}{type},{size}*%\n".format(
  7538. apid=str(apid),
  7539. type='C',
  7540. size=(factor * obj.apertures[apid]['size'])
  7541. )
  7542. elif obj.apertures[apid]['type'] == 'R':
  7543. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7544. apid=str(apid),
  7545. type='R',
  7546. width=(factor * obj.apertures[apid]['width']),
  7547. height=(factor * obj.apertures[apid]['height'])
  7548. )
  7549. elif obj.apertures[apid]['type'] == 'O':
  7550. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7551. apid=str(apid),
  7552. type='O',
  7553. width=(factor * obj.apertures[apid]['width']),
  7554. height=(factor * obj.apertures[apid]['height'])
  7555. )
  7556. header += '\n'
  7557. # obsolete units but some software may need it
  7558. if gunits == 'IN':
  7559. header += 'G70*\n'
  7560. else:
  7561. header += 'G71*\n'
  7562. # Absolute Mode
  7563. header += 'G90*\n'
  7564. header += 'G01*\n'
  7565. # positive polarity
  7566. header += '%LPD*%\n'
  7567. footer = 'M02*\n'
  7568. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7569. exported_gerber = header
  7570. exported_gerber += gerber_code
  7571. exported_gerber += footer
  7572. if local_use is None:
  7573. try:
  7574. with open(filename, 'w') as fp:
  7575. fp.write(exported_gerber)
  7576. except PermissionError:
  7577. self.inform.emit('[WARNING] %s' %
  7578. _("Permission denied, saving not possible.\n"
  7579. "Most likely another app is holding the file open and not accessible."))
  7580. return 'fail'
  7581. if self.defaults["global_open_style"] is False:
  7582. self.file_opened.emit("Gerber", filename)
  7583. self.file_saved.emit("Gerber", filename)
  7584. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7585. else:
  7586. return exported_gerber
  7587. except Exception as e:
  7588. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7589. return 'fail'
  7590. if use_thread is True:
  7591. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7592. def job_thread_grb(app_obj):
  7593. ret = make_gerber()
  7594. if ret == 'fail':
  7595. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7596. return
  7597. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7598. else:
  7599. gret = make_gerber()
  7600. if gret == 'fail':
  7601. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7602. return 'fail'
  7603. if local_use is not None:
  7604. return gret
  7605. def export_dxf(self, obj_name, filename, use_thread=True):
  7606. """
  7607. Exports a Geometry Object to an DXF file.
  7608. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7609. :param filename: Path to the DXF file to save to.
  7610. :param use_thread: if to be run in a separate thread
  7611. :return:
  7612. """
  7613. self.defaults.report_usage("export_dxf()")
  7614. if filename is None:
  7615. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7616. is not None else self.defaults["global_last_folder"]
  7617. self.log.debug("export_dxf()")
  7618. try:
  7619. obj = self.collection.get_by_name(str(obj_name))
  7620. except Exception:
  7621. # TODO: The return behavior has not been established... should raise exception?
  7622. return "Could not retrieve object: %s" % obj_name
  7623. def make_dxf():
  7624. try:
  7625. dxf_code = obj.export_dxf()
  7626. dxf_code.saveas(filename)
  7627. if self.defaults["global_open_style"] is False:
  7628. self.file_opened.emit("DXF", filename)
  7629. self.file_saved.emit("DXF", filename)
  7630. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7631. except Exception:
  7632. return 'fail'
  7633. if use_thread is True:
  7634. with self.proc_container.new(_("Exporting DXF")) as proc:
  7635. def job_thread_exc(app_obj):
  7636. ret_dxf_val = make_dxf()
  7637. if ret_dxf_val == 'fail':
  7638. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7639. return
  7640. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7641. else:
  7642. ret = make_dxf()
  7643. if ret == 'fail':
  7644. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7645. return
  7646. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7647. """
  7648. Adds a new Geometry Object to the projects and populates
  7649. it with shapes extracted from the SVG file.
  7650. :param plot: If True then the resulting object will be plotted on canvas
  7651. :param filename: Path to the SVG file.
  7652. :param geo_type: Type of FlatCAM object that will be created from SVG
  7653. :param outname: The name given to the resulting FlatCAM object
  7654. :return:
  7655. """
  7656. self.defaults.report_usage("import_svg()")
  7657. log.debug("App.import_svg()")
  7658. obj_type = ""
  7659. if geo_type is None or geo_type == "geometry":
  7660. obj_type = "geometry"
  7661. elif geo_type == "gerber":
  7662. obj_type = "gerber"
  7663. else:
  7664. self.inform.emit('[ERROR_NOTCL] %s' %
  7665. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7666. return
  7667. units = self.defaults['units'].upper()
  7668. def obj_init(geo_obj, app_obj):
  7669. geo_obj.import_svg(filename, obj_type, units=units)
  7670. geo_obj.multigeo = False
  7671. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7672. with self.proc_container.new(_("Importing SVG")) as proc:
  7673. # Object name
  7674. name = outname or filename.split('/')[-1].split('\\')[-1]
  7675. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7676. if ret == 'fail':
  7677. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7678. return 'fail'
  7679. # Register recent file
  7680. self.file_opened.emit("svg", filename)
  7681. # GUI feedback
  7682. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7683. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7684. """
  7685. Adds a new Geometry Object to the projects and populates
  7686. it with shapes extracted from the DXF file.
  7687. :param filename: Path to the DXF file.
  7688. :param geo_type: Type of FlatCAM object that will be created from DXF
  7689. :param outname: Name for the imported Geometry
  7690. :param plot: If True then the resulting object will be plotted on canvas
  7691. :return:
  7692. """
  7693. self.defaults.report_usage("import_dxf()")
  7694. obj_type = ""
  7695. if geo_type is None or geo_type == "geometry":
  7696. obj_type = "geometry"
  7697. elif geo_type == "gerber":
  7698. obj_type = geo_type
  7699. else:
  7700. self.inform.emit('[ERROR_NOTCL] %s' %
  7701. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7702. return
  7703. units = self.defaults['units'].upper()
  7704. def obj_init(geo_obj, app_obj):
  7705. geo_obj.import_dxf(filename, obj_type, units=units)
  7706. geo_obj.multigeo = False
  7707. with self.proc_container.new(_("Importing DXF")):
  7708. # Object name
  7709. name = outname or filename.split('/')[-1].split('\\')[-1]
  7710. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7711. if ret == 'fail':
  7712. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7713. return 'fail'
  7714. # Register recent file
  7715. self.file_opened.emit("dxf", filename)
  7716. # GUI feedback
  7717. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7718. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7719. """
  7720. Opens a Gerber file, parses it and creates a new object for
  7721. it in the program. Thread-safe.
  7722. :param outname: Name of the resulting object. None causes the
  7723. name to be that of the file. Str.
  7724. :param filename: Gerber file filename
  7725. :type filename: str
  7726. :param plot: boolean, to plot or not the resulting object
  7727. :param from_tcl: True if run from Tcl Shell
  7728. :return: None
  7729. """
  7730. # How the object should be initialized
  7731. def obj_init(gerber_obj, app_obj):
  7732. assert isinstance(gerber_obj, GerberObject), \
  7733. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7734. # Opening the file happens here
  7735. try:
  7736. gerber_obj.parse_file(filename)
  7737. except IOError:
  7738. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7739. return "fail"
  7740. except ParseError as err:
  7741. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7742. app_obj.log.error(str(err))
  7743. return "fail"
  7744. except Exception as e:
  7745. log.debug("App.open_gerber() --> %s" % str(e))
  7746. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7747. msg += traceback.format_exc()
  7748. app_obj.inform.emit(msg)
  7749. return "fail"
  7750. if gerber_obj.is_empty():
  7751. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7752. _("Object is not Gerber file or empty. Aborting object creation."))
  7753. return "fail"
  7754. App.log.debug("open_gerber()")
  7755. with self.proc_container.new(_("Opening Gerber")):
  7756. # Object name
  7757. name = outname or filename.split('/')[-1].split('\\')[-1]
  7758. # # ## Object creation # ##
  7759. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7760. if ret_val == 'fail':
  7761. if from_tcl:
  7762. filename = self.defaults['global_tcl_path'] + '/' + name
  7763. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7764. if ret_val == 'fail':
  7765. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7766. return 'fail'
  7767. # Register recent file
  7768. self.file_opened.emit("gerber", filename)
  7769. # GUI feedback
  7770. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7771. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7772. """
  7773. Opens an Excellon file, parses it and creates a new object for
  7774. it in the program. Thread-safe.
  7775. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7776. :param filename: Excellon file filename
  7777. :type filename: str
  7778. :param plot: boolean, to plot or not the resulting object
  7779. :param from_tcl: True if run from Tcl Shell
  7780. :return: None
  7781. """
  7782. App.log.debug("open_excellon()")
  7783. # How the object should be initialized
  7784. def obj_init(excellon_obj, app_obj):
  7785. try:
  7786. ret = excellon_obj.parse_file(filename=filename)
  7787. if ret == "fail":
  7788. log.debug("Excellon parsing failed.")
  7789. self.inform.emit('[ERROR_NOTCL] %s' %
  7790. _("This is not Excellon file."))
  7791. return "fail"
  7792. except IOError:
  7793. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7794. (_("Cannot open file"), filename))
  7795. log.debug("Could not open Excellon object.")
  7796. return "fail"
  7797. except Exception:
  7798. msg = '[ERROR_NOTCL] %s' % \
  7799. _("An internal error has occurred. See shell.\n")
  7800. msg += traceback.format_exc()
  7801. app_obj.inform.emit(msg)
  7802. return "fail"
  7803. ret = excellon_obj.create_geometry()
  7804. if ret == 'fail':
  7805. log.debug("Could not create geometry for Excellon object.")
  7806. return "fail"
  7807. for tool in excellon_obj.tools:
  7808. if excellon_obj.tools[tool]['solid_geometry']:
  7809. return
  7810. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7811. return "fail"
  7812. with self.proc_container.new(_("Opening Excellon.")):
  7813. # Object name
  7814. name = outname or filename.split('/')[-1].split('\\')[-1]
  7815. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7816. if ret_val == 'fail':
  7817. if from_tcl:
  7818. filename = self.defaults['global_tcl_path'] + '/' + name
  7819. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7820. if ret_val == 'fail':
  7821. self.inform.emit('[ERROR_NOTCL] %s' %
  7822. _('Open Excellon file failed. Probable not an Excellon file.'))
  7823. return
  7824. # Register recent file
  7825. self.file_opened.emit("excellon", filename)
  7826. # GUI feedback
  7827. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7828. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7829. """
  7830. Opens a G-gcode file, parses it and creates a new object for
  7831. it in the program. Thread-safe.
  7832. :param filename: G-code file filename
  7833. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7834. :param force_parsing:
  7835. :param plot: If True plot the object on canvas
  7836. :param from_tcl: True if run from Tcl Shell
  7837. :return: None
  7838. """
  7839. App.log.debug("open_gcode()")
  7840. # How the object should be initialized
  7841. def obj_init(job_obj, app_obj_):
  7842. """
  7843. :param job_obj: the resulting object
  7844. :type app_obj_: App
  7845. """
  7846. assert isinstance(app_obj_, App), \
  7847. "Initializer expected App, got %s" % type(app_obj_)
  7848. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7849. try:
  7850. f = open(filename)
  7851. gcode = f.read()
  7852. f.close()
  7853. except IOError:
  7854. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7855. return "fail"
  7856. job_obj.gcode = gcode
  7857. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7858. if gcode_ret == "fail":
  7859. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7860. return "fail"
  7861. job_obj.create_geometry()
  7862. with self.proc_container.new(_("Opening G-Code.")):
  7863. # Object name
  7864. name = outname or filename.split('/')[-1].split('\\')[-1]
  7865. # New object creation and file processing
  7866. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7867. if ret_val == 'fail':
  7868. if from_tcl:
  7869. filename = self.defaults['global_tcl_path'] + '/' + name
  7870. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7871. if ret_val == 'fail':
  7872. self.inform.emit('[ERROR_NOTCL] %s' %
  7873. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7874. "Try to load it from File menu.\n "
  7875. "Attempting to create a FlatCAM CNCJob Object from "
  7876. "G-Code file failed during processing"))
  7877. return "fail"
  7878. # Register recent file
  7879. self.file_opened.emit("cncjob", filename)
  7880. # GUI feedback
  7881. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7882. def open_hpgl2(self, filename, outname=None):
  7883. """
  7884. Opens a HPGL2 file, parses it and creates a new object for
  7885. it in the program. Thread-safe.
  7886. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7887. :param filename: HPGL2 file filename
  7888. :return: None
  7889. """
  7890. filename = filename
  7891. # How the object should be initialized
  7892. def obj_init(geo_obj, app_obj):
  7893. assert isinstance(geo_obj, GeometryObject), \
  7894. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7895. # Opening the file happens here
  7896. obj = HPGL2(self)
  7897. try:
  7898. HPGL2.parse_file(obj, filename)
  7899. except IOError:
  7900. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7901. return "fail"
  7902. except ParseError as err:
  7903. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7904. app_obj.log.error(str(err))
  7905. return "fail"
  7906. except Exception as e:
  7907. log.debug("App.open_hpgl2() --> %s" % str(e))
  7908. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7909. msg += traceback.format_exc()
  7910. app_obj.inform.emit(msg)
  7911. return "fail"
  7912. geo_obj.multigeo = True
  7913. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7914. geo_obj.tools = deepcopy(obj.tools)
  7915. geo_obj.source_file = deepcopy(obj.source_file)
  7916. del obj
  7917. if not geo_obj.solid_geometry:
  7918. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7919. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7920. return "fail"
  7921. App.log.debug("open_hpgl2()")
  7922. with self.proc_container.new(_("Opening HPGL2")):
  7923. # Object name
  7924. name = outname or filename.split('/')[-1].split('\\')[-1]
  7925. # # ## Object creation # ##
  7926. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7927. if ret == 'fail':
  7928. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7929. return 'fail'
  7930. # Register recent file
  7931. self.file_opened.emit("geometry", filename)
  7932. # GUI feedback
  7933. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7934. def open_script(self, filename, outname=None, silent=False):
  7935. """
  7936. Opens a Script file, parses it and creates a new object for
  7937. it in the program. Thread-safe.
  7938. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7939. :param filename: Script file filename
  7940. :param silent: If True there will be no messages printed to StatusBar
  7941. :return: None
  7942. """
  7943. def obj_init(script_obj, app_obj):
  7944. assert isinstance(script_obj, ScriptObject), \
  7945. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7946. if silent is False:
  7947. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7948. try:
  7949. script_obj.parse_file(filename)
  7950. except IOError:
  7951. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7952. return "fail"
  7953. except ParseError as err:
  7954. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7955. app_obj.log.error(str(err))
  7956. return "fail"
  7957. except Exception as e:
  7958. log.debug("App.open_script() -> %s" % str(e))
  7959. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7960. msg += traceback.format_exc()
  7961. app_obj.inform.emit(msg)
  7962. return "fail"
  7963. App.log.debug("open_script()")
  7964. with self.proc_container.new(_("Opening TCL Script...")):
  7965. # Object name
  7966. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7967. # Object creation
  7968. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7969. if ret_val == 'fail':
  7970. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7971. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7972. if ret_val == 'fail':
  7973. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7974. return 'fail'
  7975. # Register recent file
  7976. self.file_opened.emit("script", filename)
  7977. # GUI feedback
  7978. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7979. def open_config_file(self, filename, run_from_arg=None):
  7980. """
  7981. Loads a config file from the specified file.
  7982. :param filename: Name of the file from which to load.
  7983. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7984. :return: None
  7985. """
  7986. App.log.debug("Opening config file: " + filename)
  7987. if run_from_arg:
  7988. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7989. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7990. _("Opening FlatCAM Config file.")),
  7991. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7992. color=QtGui.QColor("gray"))
  7993. # # add the tab if it was closed
  7994. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7995. # # first clear previous text in text editor (if any)
  7996. # self.ui.text_editor_tab.code_editor.clear()
  7997. #
  7998. # # Switch plot_area to CNCJob tab
  7999. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8000. # close the Code editor if already open
  8001. if self.toggle_codeeditor:
  8002. self.on_toggle_code_editor()
  8003. self.on_toggle_code_editor()
  8004. try:
  8005. if filename:
  8006. f = QtCore.QFile(filename)
  8007. if f.open(QtCore.QIODevice.ReadOnly):
  8008. stream = QtCore.QTextStream(f)
  8009. code_edited = stream.readAll()
  8010. self.text_editor_tab.code_editor.setPlainText(code_edited)
  8011. f.close()
  8012. except IOError:
  8013. App.log.error("Failed to open config file: %s" % filename)
  8014. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8015. (_("Failed to open config file"), filename))
  8016. return
  8017. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  8018. """
  8019. Loads a project from the specified file.
  8020. 1) Loads and parses file
  8021. 2) Registers the file as recently opened.
  8022. 3) Calls on_file_new()
  8023. 4) Updates options
  8024. 5) Calls new_object() with the object's from_dict() as init method.
  8025. 6) Calls plot_all() if plot=True
  8026. :param filename: Name of the file from which to load.
  8027. :param run_from_arg: True if run for arguments
  8028. :param plot: If True plot all objects in the project
  8029. :param cli: Run from command line
  8030. :param from_tcl: True if run from Tcl Sehll
  8031. :return: None
  8032. """
  8033. App.log.debug("Opening project: " + filename)
  8034. # block autosaving while a project is loaded
  8035. self.block_autosave = True
  8036. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8037. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8038. if cli is None:
  8039. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8040. if run_from_arg:
  8041. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8042. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8043. _("Opening FlatCAM Project file.")),
  8044. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8045. color=QtGui.QColor("gray"))
  8046. # Open and parse an uncompressed Project file
  8047. try:
  8048. f = open(filename, 'r')
  8049. except IOError:
  8050. if from_tcl:
  8051. name = filename.split('/')[-1].split('\\')[-1]
  8052. filename = self.defaults['global_tcl_path'] + '/' + name
  8053. try:
  8054. f = open(filename, 'r')
  8055. except IOError:
  8056. log.error("Failed to open project file: %s" % filename)
  8057. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8058. return
  8059. else:
  8060. log.error("Failed to open project file: %s" % filename)
  8061. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8062. return
  8063. try:
  8064. d = json.load(f, object_hook=dict2obj)
  8065. except Exception as e:
  8066. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8067. (filename, str(e)))
  8068. f.close()
  8069. # Open and parse a compressed Project file
  8070. try:
  8071. with lzma.open(filename) as f:
  8072. file_content = f.read().decode('utf-8')
  8073. d = json.loads(file_content, object_hook=dict2obj)
  8074. except Exception as e:
  8075. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8076. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8077. return
  8078. # Clear the current project
  8079. # # NOT THREAD SAFE # ##
  8080. if run_from_arg is True:
  8081. pass
  8082. elif cli is True:
  8083. self.delete_selection_shape()
  8084. else:
  8085. self.on_file_new()
  8086. # Project options
  8087. self.options.update(d['options'])
  8088. self.project_filename = filename
  8089. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8090. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8091. if cli is None:
  8092. self.set_screen_units(self.options["units"])
  8093. # Re create objects
  8094. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8095. for obj in d['objs']:
  8096. try:
  8097. def obj_init(obj_inst, app_inst):
  8098. obj_inst.from_dict(obj)
  8099. App.log.debug("Recreating from opened project an %s object: %s" %
  8100. (obj['kind'].capitalize(), obj['options']['name']))
  8101. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8102. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8103. if cli is None:
  8104. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8105. obj['kind'].upper(),
  8106. obj['options']['name']
  8107. )
  8108. )
  8109. self.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8110. except Exception as e:
  8111. print('App.open_project() --> ' + str(e))
  8112. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8113. self.should_we_save = False
  8114. self.file_opened.emit("project", filename)
  8115. # restore autosaving after a project was loaded
  8116. self.block_autosave = False
  8117. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8118. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8119. if cli is None:
  8120. self.set_ui_title(name=self.project_filename)
  8121. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8122. def plot_all(self, fit_view=True, use_thread=True):
  8123. """
  8124. Re-generates all plots from all objects.
  8125. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8126. :param use_thread: if True will use threading for plotting the objects
  8127. :return: None
  8128. """
  8129. self.log.debug("Plot_all()")
  8130. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8131. for plot_obj in self.collection.get_list():
  8132. def worker_task(obj):
  8133. with self.proc_container.new("Plotting"):
  8134. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8135. if fit_view is True:
  8136. self.object_plotted.emit(obj)
  8137. if use_thread is True:
  8138. # Send to worker
  8139. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8140. else:
  8141. worker_task(plot_obj)
  8142. def register_folder(self, filename):
  8143. """
  8144. Register the last folder used by the app to open something
  8145. :param filename: the last folder is extracted from the filename
  8146. :return: None
  8147. """
  8148. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8149. def register_save_folder(self, filename):
  8150. """
  8151. Register the last folder used by the app to save something
  8152. :param filename: the last folder is extracted from the filename
  8153. :return: None
  8154. """
  8155. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8156. # def set_progress_bar(self, percentage, text=""):
  8157. # """
  8158. # Set a progress bar to a value (percentage)
  8159. #
  8160. # :param percentage: Value set to the progressbar
  8161. # :param text: Not used
  8162. # :return: None
  8163. # """
  8164. # self.ui.progress_bar.setValue(int(percentage))
  8165. def setup_recent_items(self):
  8166. """
  8167. Setup a dictionary with the recent files accessed, organized by type
  8168. :return:
  8169. """
  8170. icons = {
  8171. "gerber": self.resource_location + "/flatcam_icon16.png",
  8172. "excellon": self.resource_location + "/drill16.png",
  8173. 'geometry': self.resource_location + "/geometry16.png",
  8174. "cncjob": self.resource_location + "/cnc16.png",
  8175. "script": self.resource_location + "/script_new24.png",
  8176. "document": self.resource_location + "/notes16_1.png",
  8177. "project": self.resource_location + "/project16.png",
  8178. "svg": self.resource_location + "/geometry16.png",
  8179. "dxf": self.resource_location + "/dxf16.png",
  8180. "pdf": self.resource_location + "/pdf32.png",
  8181. "image": self.resource_location + "/image16.png"
  8182. }
  8183. try:
  8184. image_opener = self.image_tool.import_image
  8185. except AttributeError:
  8186. image_opener = None
  8187. openers = {
  8188. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8189. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8190. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8191. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8192. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8193. "document": None,
  8194. 'project': self.open_project,
  8195. 'svg': self.import_svg,
  8196. 'dxf': self.import_dxf,
  8197. 'image': image_opener,
  8198. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8199. }
  8200. # Open recent file for files
  8201. try:
  8202. f = open(self.data_path + '/recent.json')
  8203. except IOError:
  8204. App.log.error("Failed to load recent item list.")
  8205. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8206. return
  8207. try:
  8208. self.recent = json.load(f)
  8209. except json.errors.JSONDecodeError:
  8210. App.log.error("Failed to parse recent item list.")
  8211. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8212. f.close()
  8213. return
  8214. f.close()
  8215. # Open recent file for projects
  8216. try:
  8217. fp = open(self.data_path + '/recent_projects.json')
  8218. except IOError:
  8219. App.log.error("Failed to load recent project item list.")
  8220. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8221. return
  8222. try:
  8223. self.recent_projects = json.load(fp)
  8224. except json.errors.JSONDecodeError:
  8225. App.log.error("Failed to parse recent project item list.")
  8226. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8227. fp.close()
  8228. return
  8229. fp.close()
  8230. # Closure needed to create callbacks in a loop.
  8231. # Otherwise late binding occurs.
  8232. def make_callback(func, fname):
  8233. def opener():
  8234. func(fname)
  8235. return opener
  8236. def reset_recent_files():
  8237. # Reset menu
  8238. self.ui.recent.clear()
  8239. self.recent = []
  8240. try:
  8241. ff = open(self.data_path + '/recent.json', 'w')
  8242. except IOError:
  8243. App.log.error("Failed to open recent items file for writing.")
  8244. return
  8245. json.dump(self.recent, ff)
  8246. def reset_recent_projects():
  8247. # Reset menu
  8248. self.ui.recent_projects.clear()
  8249. self.recent_projects = []
  8250. try:
  8251. frp = open(self.data_path + '/recent_projects.json', 'w')
  8252. except IOError:
  8253. App.log.error("Failed to open recent projects items file for writing.")
  8254. return
  8255. json.dump(self.recent, frp)
  8256. # Reset menu
  8257. self.ui.recent.clear()
  8258. self.ui.recent_projects.clear()
  8259. # Create menu items for projects
  8260. for recent in self.recent_projects:
  8261. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8262. if recent['kind'] == 'project':
  8263. try:
  8264. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8265. # Attach callback
  8266. o = make_callback(openers[recent["kind"]], recent['filename'])
  8267. action.triggered.connect(o)
  8268. self.ui.recent_projects.addAction(action)
  8269. except KeyError:
  8270. App.log.error("Unsupported file type: %s" % recent["kind"])
  8271. # Last action in Recent Files menu is one that Clear the content
  8272. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8273. (_("Clear Recent projects")), self)
  8274. clear_action_proj.triggered.connect(reset_recent_projects)
  8275. self.ui.recent_projects.addSeparator()
  8276. self.ui.recent_projects.addAction(clear_action_proj)
  8277. # Create menu items for files
  8278. for recent in self.recent:
  8279. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8280. if recent['kind'] != 'project':
  8281. try:
  8282. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8283. # Attach callback
  8284. o = make_callback(openers[recent["kind"]], recent['filename'])
  8285. action.triggered.connect(o)
  8286. self.ui.recent.addAction(action)
  8287. except KeyError:
  8288. App.log.error("Unsupported file type: %s" % recent["kind"])
  8289. # Last action in Recent Files menu is one that Clear the content
  8290. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8291. (_("Clear Recent files")), self)
  8292. clear_action.triggered.connect(reset_recent_files)
  8293. self.ui.recent.addSeparator()
  8294. self.ui.recent.addAction(clear_action)
  8295. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8296. # self.ui.menufilerecent.set_submenu(recent_menu)
  8297. # recent_menu.show_all()
  8298. # self.ui.recent.show()
  8299. self.log.debug("Recent items list has been populated.")
  8300. def setup_component_editor(self):
  8301. """
  8302. Default text for the Selected tab when is not taken by the Object UI.
  8303. :return:
  8304. """
  8305. # label = QtWidgets.QLabel("Choose an item from Project")
  8306. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8307. sel_title = QtWidgets.QTextEdit(
  8308. _('<b>Shortcut Key List</b>'))
  8309. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8310. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8311. f_settings = QSettings("Open Source", "FlatCAM")
  8312. if f_settings.contains("notebook_font_size"):
  8313. fsize = f_settings.value('notebook_font_size', type=int)
  8314. else:
  8315. fsize = 12
  8316. tsize = fsize + int(fsize / 2)
  8317. # selected_text = (_('''
  8318. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8319. # </p>
  8320. #
  8321. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8322. # The normal flow when working in FlatCAM is the following:</span></p>
  8323. #
  8324. # <ol>
  8325. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8326. # file into
  8327. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8328. # even dragging and dropping the files on the GUI.<br />
  8329. # <br />
  8330. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8331. # drop of the
  8332. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8333. # &nbsp;</li>
  8334. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8335. # and then
  8336. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8337. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8338. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8339. # <br />
  8340. # If the selection of the object is done on the canvas by single click instead, and the
  8341. # <strong>SELECTED TAB</strong>
  8342. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8343. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8344. # it even if it was out of focus.<br />
  8345. # <br />
  8346. # You can change the parameters in this screen and the flow direction is like this:<br />
  8347. # <br />
  8348. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8349. # <strong> Geometry Object
  8350. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8351. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8352. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8353. # </ol>
  8354. #
  8355. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8356. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8357. # <strong>F3</strong>.</span></p>
  8358. #
  8359. # ''').format(fsize=fsize, tsize=tsize))
  8360. selected_text = '''
  8361. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8362. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8363. {s1}</span></p>
  8364. <ol>
  8365. <li><span style="font-size:{fsize}px">{s2}<br />
  8366. <br />
  8367. {s3}</span><br />
  8368. &nbsp;</li>
  8369. <li><span style="font-size:{fsize}px">{s4}<br />
  8370. &nbsp;</li>
  8371. <br />
  8372. <li><span style="font-size:{fsize}px">{s5}<br />
  8373. &nbsp;</li>
  8374. <br />
  8375. <li><span style="font-size:{fsize}px">{s6}<br />
  8376. <br />
  8377. {s7}</span></li>
  8378. </ol>
  8379. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8380. '''.format(
  8381. title=_("Selected Tab - Choose an Item from Project Tab"),
  8382. subtitle=_("Details"),
  8383. s1=_("The normal flow when working in FlatCAM is the following:"),
  8384. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8385. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8386. "files on the GUI."),
  8387. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8388. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8389. "actions offered within the app."),
  8390. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8391. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8392. "SELECTED TAB will be updated with the object properties according to its kind: "
  8393. "Gerber, Excellon, Geometry or CNCJob object."),
  8394. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8395. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8396. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8397. "the SELECTED TAB and populate it even if it was out of focus."),
  8398. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8399. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8400. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8401. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8402. "(again, done in SELECTED TAB) --> Save GCode."),
  8403. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8404. "or through its own key shortcut: <b>F3</b>."),
  8405. tsize=tsize,
  8406. fsize=fsize
  8407. )
  8408. sel_title.setText(selected_text)
  8409. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8410. self.ui.selected_scroll_area.setWidget(sel_title)
  8411. def setup_obj_classes(self):
  8412. """
  8413. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8414. class.
  8415. :return: None
  8416. """
  8417. FlatCAMObj.app = self
  8418. ObjectCollection.app = self
  8419. Gerber.app = self
  8420. Excellon.app = self
  8421. Geometry.app = self
  8422. CNCjob.app = self
  8423. FCProcess.app = self
  8424. FCProcessContainer.app = self
  8425. OptionsGroupUI.app = self
  8426. def version_check(self):
  8427. """
  8428. Checks for the latest version of the program. Alerts the
  8429. user if theirs is outdated. This method is meant to be run
  8430. in a separate thread.
  8431. :return: None
  8432. """
  8433. self.log.debug("version_check()")
  8434. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8435. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8436. App.version_url,
  8437. str(self.defaults['global_serial']),
  8438. str(self.version),
  8439. str(self.os),
  8440. urllib.parse.urlencode(self.defaults["global_stats"])
  8441. )
  8442. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8443. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8444. # urllib.parse.urlencode(self.defaults["global_stats"])
  8445. else:
  8446. # no_stats dict; just so it won't break things on website
  8447. no_ststs_dict = {}
  8448. no_ststs_dict["global_ststs"] = {}
  8449. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8450. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8451. App.log.debug("Checking for updates @ %s" % full_url)
  8452. # ## Get the data
  8453. try:
  8454. f = urllib.request.urlopen(full_url)
  8455. except Exception:
  8456. # App.log.warning("Failed checking for latest version. Could not connect.")
  8457. self.log.warning("Failed checking for latest version. Could not connect.")
  8458. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8459. return
  8460. try:
  8461. data = json.load(f)
  8462. except Exception as e:
  8463. App.log.error("Could not parse information about latest version.")
  8464. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8465. App.log.debug("json.load(): %s" % str(e))
  8466. f.close()
  8467. return
  8468. f.close()
  8469. # ## Latest version?
  8470. if self.version >= data["version"]:
  8471. App.log.debug("FlatCAM is up to date!")
  8472. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8473. return
  8474. App.log.debug("Newer version available.")
  8475. self.message.emit(
  8476. _("Newer Version Available"),
  8477. '%s<br><br>><b>%s</b><br>%s' % (
  8478. _("There is a newer version of FlatCAM available for download:"),
  8479. str(data["name"]),
  8480. str(data["message"])
  8481. ),
  8482. _("info")
  8483. )
  8484. def on_plotcanvas_setup(self, container=None):
  8485. """
  8486. This is doing the setup for the plot area (canvas).
  8487. :param container: QT Widget where to install the canvas
  8488. :return: None
  8489. """
  8490. if container:
  8491. plot_container = container
  8492. else:
  8493. plot_container = self.ui.right_layout
  8494. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8495. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8496. self.is_legacy = True
  8497. self.defaults["global_graphic_engine"] = "2D"
  8498. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8499. else:
  8500. try:
  8501. self.plotcanvas = PlotCanvas(plot_container, self)
  8502. except Exception as er:
  8503. msg_txt = traceback.format_exc()
  8504. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8505. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8506. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8507. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8508. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8509. msg += msg_txt
  8510. self.inform.emit(msg)
  8511. return 'fail'
  8512. # So it can receive key presses
  8513. self.plotcanvas.native.setFocus()
  8514. if self.is_legacy is False:
  8515. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8516. # Set the mouse button for panning
  8517. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8518. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8519. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8520. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8521. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8522. # Keys over plot enabled
  8523. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8524. if self.defaults['global_cursor_type'] == 'small':
  8525. self.app_cursor = self.plotcanvas.new_cursor()
  8526. else:
  8527. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8528. if self.ui.grid_snap_btn.isChecked():
  8529. self.app_cursor.enabled = True
  8530. else:
  8531. self.app_cursor.enabled = False
  8532. if self.is_legacy is False:
  8533. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8534. else:
  8535. # will use the default Matplotlib axes
  8536. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8537. def on_zoom_fit(self, event):
  8538. """
  8539. Callback for zoom-fit request. This can be either from the corresponding
  8540. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8541. with axes limits from the geometry bounds of all objects.
  8542. :param event: Ignored.
  8543. :return: None
  8544. """
  8545. if self.is_legacy is False:
  8546. self.plotcanvas.fit_view()
  8547. else:
  8548. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8549. width = xmax - xmin
  8550. height = ymax - ymin
  8551. xmin -= 0.05 * width
  8552. xmax += 0.05 * width
  8553. ymin -= 0.05 * height
  8554. ymax += 0.05 * height
  8555. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8556. def on_zoom_in(self):
  8557. """
  8558. Callback for zoom-in request.
  8559. :return:
  8560. """
  8561. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8562. def on_zoom_out(self):
  8563. """
  8564. Callback for zoom-out request.
  8565. :return:
  8566. """
  8567. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8568. def disable_all_plots(self):
  8569. self.defaults.report_usage("disable_all_plots()")
  8570. self.disable_plots(self.collection.get_list())
  8571. self.inform.emit('[success] %s' %
  8572. _("All plots disabled."))
  8573. def disable_other_plots(self):
  8574. self.defaults.report_usage("disable_other_plots()")
  8575. self.disable_plots(self.collection.get_non_selected())
  8576. self.inform.emit('[success] %s' %
  8577. _("All non selected plots disabled."))
  8578. def enable_all_plots(self):
  8579. self.defaults.report_usage("enable_all_plots()")
  8580. self.enable_plots(self.collection.get_list())
  8581. self.inform.emit('[success] %s' %
  8582. _("All plots enabled."))
  8583. def on_enable_sel_plots(self):
  8584. log.debug("App.on_enable_sel_plot()")
  8585. object_list = self.collection.get_selected()
  8586. self.enable_plots(objects=object_list)
  8587. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8588. def on_disable_sel_plots(self):
  8589. log.debug("App.on_disable_sel_plot()")
  8590. # self.inform.emit(_("Disabling plots ..."))
  8591. object_list = self.collection.get_selected()
  8592. self.disable_plots(objects=object_list)
  8593. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8594. def enable_plots(self, objects):
  8595. """
  8596. Enable plots
  8597. :param objects: list of Objects to be enabled
  8598. :return:
  8599. """
  8600. log.debug("Enabling plots ...")
  8601. # self.inform.emit(_("Working ..."))
  8602. for obj in objects:
  8603. if obj.options['plot'] is False:
  8604. obj.options.set_change_callback(lambda x: None)
  8605. obj.options['plot'] = True
  8606. try:
  8607. # only the Gerber obj has on_plot_cb_click() method
  8608. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8609. # disable this cb while disconnected,
  8610. # in case the operation takes time the user is not allowed to change it
  8611. obj.ui.plot_cb.setDisabled(True)
  8612. except AttributeError:
  8613. pass
  8614. obj.set_form_item("plot")
  8615. try:
  8616. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8617. obj.ui.plot_cb.setDisabled(False)
  8618. except AttributeError:
  8619. pass
  8620. obj.options.set_change_callback(obj.on_options_change)
  8621. def worker_task(objs):
  8622. with self.proc_container.new(_("Enabling plots ...")):
  8623. for plot_obj in objs:
  8624. # obj.options['plot'] = True
  8625. if isinstance(plot_obj, CNCJobObject):
  8626. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8627. else:
  8628. plot_obj.plot(visible=True)
  8629. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8630. # self.plots_updated.emit()
  8631. def disable_plots(self, objects):
  8632. """
  8633. Disables plots
  8634. :param objects: list of Objects to be disabled
  8635. :return:
  8636. """
  8637. # if no objects selected then do nothing
  8638. if not self.collection.get_selected():
  8639. return
  8640. log.debug("Disabling plots ...")
  8641. # self.inform.emit(_("Working ..."))
  8642. for obj in objects:
  8643. if obj.options['plot'] is True:
  8644. obj.options.set_change_callback(lambda x: None)
  8645. obj.options['plot'] = False
  8646. try:
  8647. # only the Gerber obj has on_plot_cb_click() method
  8648. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8649. obj.ui.plot_cb.setDisabled(True)
  8650. except AttributeError:
  8651. pass
  8652. obj.set_form_item("plot")
  8653. try:
  8654. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8655. obj.ui.plot_cb.setDisabled(False)
  8656. except AttributeError:
  8657. pass
  8658. obj.options.set_change_callback(obj.on_options_change)
  8659. try:
  8660. self.delete_selection_shape()
  8661. except Exception as e:
  8662. log.debug("App.disable_plots() --> %s" % str(e))
  8663. # self.plots_updated.emit()
  8664. def worker_task(objs):
  8665. with self.proc_container.new(_("Disabling plots ...")):
  8666. for plot_obj in objs:
  8667. # obj.options['plot'] = True
  8668. if isinstance(plot_obj, CNCJobObject):
  8669. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8670. else:
  8671. plot_obj.plot(visible=False)
  8672. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8673. def toggle_plots(self, objects):
  8674. """
  8675. Toggle plots visibility
  8676. :param objects: list of Objects for which to be toggled the visibility
  8677. :return: None
  8678. """
  8679. # if no objects selected then do nothing
  8680. if not self.collection.get_selected():
  8681. return
  8682. log.debug("Toggling plots ...")
  8683. self.inform.emit(_("Working ..."))
  8684. for obj in objects:
  8685. if obj.options['plot'] is False:
  8686. obj.options['plot'] = True
  8687. else:
  8688. obj.options['plot'] = False
  8689. self.plots_updated.emit()
  8690. def clear_plots(self):
  8691. """
  8692. Clear the plots
  8693. :return: None
  8694. """
  8695. objects = self.collection.get_list()
  8696. for obj in objects:
  8697. obj.clear(obj == objects[-1])
  8698. # Clear pool to free memory
  8699. self.clear_pool()
  8700. def on_set_color_action_triggered(self):
  8701. """
  8702. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8703. :return:
  8704. """
  8705. new_color = self.defaults['gerber_plot_fill']
  8706. clicked_action = self.sender()
  8707. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8708. act_name = clicked_action.text()
  8709. sel_obj_list = self.collection.get_selected()
  8710. if not sel_obj_list:
  8711. return
  8712. # a default value, I just chose this one
  8713. alpha_level = 'BF'
  8714. for sel_obj in sel_obj_list:
  8715. if sel_obj.kind == 'excellon':
  8716. alpha_level = str(hex(
  8717. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8718. elif sel_obj.kind == 'gerber':
  8719. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8720. elif sel_obj.kind == 'geometry':
  8721. alpha_level = 'FF'
  8722. else:
  8723. log.debug(
  8724. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8725. continue
  8726. sel_obj.alpha_level = alpha_level
  8727. if act_name == _('Red'):
  8728. new_color = '#FF0000' + alpha_level
  8729. if act_name == _('Blue'):
  8730. new_color = '#0000FF' + alpha_level
  8731. if act_name == _('Yellow'):
  8732. new_color = '#FFDF00' + alpha_level
  8733. if act_name == _('Green'):
  8734. new_color = '#00FF00' + alpha_level
  8735. if act_name == _('Purple'):
  8736. new_color = '#FF00FF' + alpha_level
  8737. if act_name == _('Brown'):
  8738. new_color = '#A52A2A' + alpha_level
  8739. if act_name == _('White'):
  8740. new_color = '#FFFFFF' + alpha_level
  8741. if act_name == _('Black'):
  8742. new_color = '#000000' + alpha_level
  8743. if act_name == _('Custom'):
  8744. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8745. c_dialog = QtWidgets.QColorDialog()
  8746. plot_fill_color = c_dialog.getColor(initial=new_color)
  8747. if plot_fill_color.isValid() is False:
  8748. return
  8749. new_color = str(plot_fill_color.name()) + alpha_level
  8750. if act_name == _("Default"):
  8751. for sel_obj in sel_obj_list:
  8752. if sel_obj.kind == 'excellon':
  8753. new_color = self.defaults['excellon_plot_fill']
  8754. new_line_color = self.defaults['excellon_plot_line']
  8755. elif sel_obj.kind == 'gerber':
  8756. new_color = self.defaults['gerber_plot_fill']
  8757. new_line_color = self.defaults['gerber_plot_line']
  8758. elif sel_obj.kind == 'geometry':
  8759. new_color = self.defaults['geometry_plot_line']
  8760. new_line_color = self.defaults['geometry_plot_line']
  8761. else:
  8762. log.debug(
  8763. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8764. continue
  8765. sel_obj.fill_color = new_color
  8766. sel_obj.outline_color = new_line_color
  8767. sel_obj.shapes.redraw(
  8768. update_colors=(new_color, new_line_color)
  8769. )
  8770. return
  8771. if act_name == _("Opacity"):
  8772. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8773. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8774. if ok_button:
  8775. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8776. for sel_obj in sel_obj_list:
  8777. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8778. sel_obj.shapes.redraw(
  8779. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8780. )
  8781. return
  8782. new_line_color = color_variant(new_color[:7], 0.7)
  8783. if act_name == _("White"):
  8784. new_line_color = color_variant("#dedede", 0.7)
  8785. for sel_obj in sel_obj_list:
  8786. sel_obj.fill_color = new_color
  8787. sel_obj.outline_color = new_line_color
  8788. sel_obj.shapes.redraw(
  8789. update_colors=(new_color, new_line_color)
  8790. )
  8791. def generate_cnc_job(self, objects):
  8792. """
  8793. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8794. :param objects: Selected objects in the Project Tab
  8795. :return:
  8796. """
  8797. self.defaults.report_usage("generate_cnc_job()")
  8798. # for obj in objects:
  8799. # obj.generatecncjob()
  8800. for obj in objects:
  8801. obj.on_generatecnc_button_click()
  8802. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8803. """
  8804. Saves the current project to the specified file.
  8805. :param filename: Name of the file in which to save.
  8806. :type filename: str
  8807. :param quit_action: if the project saving will be followed by an app quit; boolean
  8808. :param silent: if True will not display status messages
  8809. :param from_tcl True is run from Tcl Shell
  8810. :return: None
  8811. """
  8812. self.log.debug("save_project()")
  8813. self.save_in_progress = True
  8814. with self.proc_container.new(_("Saving FlatCAM Project")):
  8815. # Capture the latest changes
  8816. # Current object
  8817. try:
  8818. current_object = self.collection.get_active()
  8819. if current_object:
  8820. current_object.read_form()
  8821. except Exception as e:
  8822. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8823. pass
  8824. # Serialize the whole project
  8825. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8826. "options": self.options,
  8827. "version": self.version}
  8828. if self.defaults["global_save_compressed"] is True:
  8829. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8830. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8831. # # Write
  8832. f.write(g)
  8833. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8834. else:
  8835. # Open file
  8836. try:
  8837. f = open(filename, 'w')
  8838. except IOError:
  8839. App.log.error("Failed to open file for saving: %s", filename)
  8840. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8841. return
  8842. # Write
  8843. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8844. f.close()
  8845. # verification of the saved project
  8846. # Open and parse
  8847. try:
  8848. saved_f = open(filename, 'r')
  8849. except IOError:
  8850. if silent is False:
  8851. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8852. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8853. return
  8854. try:
  8855. saved_d = json.load(saved_f, object_hook=dict2obj)
  8856. except Exception:
  8857. if silent is False:
  8858. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8859. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8860. f.close()
  8861. return
  8862. saved_f.close()
  8863. if silent is False:
  8864. if 'version' in saved_d:
  8865. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8866. else:
  8867. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8868. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8869. tb_settings = QSettings("Open Source", "FlatCAM")
  8870. lock_state = self.ui.lock_action.isChecked()
  8871. tb_settings.setValue('toolbar_lock', lock_state)
  8872. # This will write the setting to the platform specific storage.
  8873. del tb_settings
  8874. # if quit:
  8875. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8876. # t.start()
  8877. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8878. def start_delayed_quit(self, delay, filename, should_quit=None):
  8879. """
  8880. :param delay: period of checking if project file size is more than zero; in seconds
  8881. :param filename: the name of the project file to be checked periodically for size more than zero
  8882. :param should_quit: if the task finished will be followed by an app quit; boolean
  8883. :return:
  8884. """
  8885. to_quit = should_quit
  8886. self.save_timer = QtCore.QTimer()
  8887. self.save_timer.setInterval(delay)
  8888. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8889. self.save_timer.start()
  8890. def check_project_file_size(self, filename, should_quit=None):
  8891. """
  8892. :param filename: the name of the project file to be checked periodically for size more than zero
  8893. :param should_quit: will quit the app if True; boolean
  8894. :return:
  8895. """
  8896. try:
  8897. if os.stat(filename).st_size > 0:
  8898. self.save_in_progress = False
  8899. self.save_timer.stop()
  8900. if should_quit:
  8901. self.app_quit.emit()
  8902. except Exception:
  8903. traceback.print_exc()
  8904. def save_project_auto(self):
  8905. """
  8906. Called periodically to save the project.
  8907. 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
  8908. # progress.
  8909. :return:
  8910. """
  8911. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8912. self.on_file_saveproject()
  8913. def save_project_auto_update(self):
  8914. """
  8915. Update the auto save time interval value.
  8916. :return:
  8917. """
  8918. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8919. try:
  8920. if self.autosave_timer.isActive():
  8921. self.autosave_timer.stop()
  8922. except Exception:
  8923. pass
  8924. if self.defaults['global_autosave'] is True:
  8925. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8926. self.autosave_timer.start()
  8927. def on_options_app2project(self):
  8928. """
  8929. Callback for Options->Transfer Options->App=>Project. Copies options
  8930. from application defaults to project defaults.
  8931. :return: None
  8932. """
  8933. self.defaults.report_usage("on_options_app2project")
  8934. self.preferencesUiManager.defaults_read_form()
  8935. self.options.update(self.defaults)
  8936. def toggle_shell(self):
  8937. """
  8938. Toggle shell: if is visible close it, if it is closed then open it
  8939. :return: None
  8940. """
  8941. self.defaults.report_usage("toggle_shell()")
  8942. if self.ui.shell_dock.isVisible():
  8943. self.ui.shell_dock.hide()
  8944. self.plotcanvas.native.setFocus()
  8945. else:
  8946. self.ui.shell_dock.show()
  8947. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8948. # self.shell._edit.setFocus()
  8949. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8950. # HACK - simulate a mouse click - alternative
  8951. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8952. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8953. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8954. # no_km)
  8955. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8956. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8957. # no_km)
  8958. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8959. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8960. """
  8961. Shows a message on the FlatCAM Shell
  8962. :param msg: Message to display.
  8963. :param show: Opens the shell.
  8964. :param error: Shows the message as an error.
  8965. :param warning: Shows the message as an warning.
  8966. :param success: Shows the message as an success.
  8967. :param selected: Indicate that something was selected on canvas
  8968. :return: None
  8969. """
  8970. if show:
  8971. self.ui.shell_dock.show()
  8972. try:
  8973. if error:
  8974. self.shell.append_error(msg + "\n")
  8975. elif warning:
  8976. self.shell.append_warning(msg + "\n")
  8977. elif success:
  8978. self.shell.append_success(msg + "\n")
  8979. elif selected:
  8980. self.shell.append_selected(msg + "\n")
  8981. else:
  8982. self.shell.append_output(msg + "\n")
  8983. except AttributeError:
  8984. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8985. class ArgsThread(QtCore.QObject):
  8986. open_signal = pyqtSignal(list)
  8987. start = pyqtSignal()
  8988. if sys.platform == 'win32':
  8989. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8990. else:
  8991. address = ('/tmp/testipc', 'AF_UNIX')
  8992. def __init__(self):
  8993. super(ArgsThread, self).__init__()
  8994. self.listener = None
  8995. self.thread_exit = False
  8996. self.start.connect(self.run)
  8997. def my_loop(self, address):
  8998. try:
  8999. self.listener = Listener(*address)
  9000. while self.thread_exit is False:
  9001. conn = self.listener.accept()
  9002. self.serve(conn)
  9003. except socket.error:
  9004. try:
  9005. conn = Client(*address)
  9006. conn.send(sys.argv)
  9007. conn.send('close')
  9008. # close the current instance only if there are args
  9009. if len(sys.argv) > 1:
  9010. try:
  9011. self.listener.close()
  9012. except Exception:
  9013. pass
  9014. sys.exit()
  9015. except ConnectionRefusedError:
  9016. if sys.platform == 'win32':
  9017. pass
  9018. else:
  9019. os.system('rm /tmp/testipc')
  9020. self.listener = Listener(*address)
  9021. while True:
  9022. conn = self.listener.accept()
  9023. self.serve(conn)
  9024. def serve(self, conn):
  9025. while self.thread_exit is False:
  9026. msg = conn.recv()
  9027. if msg == 'close':
  9028. break
  9029. self.open_signal.emit(msg)
  9030. conn.close()
  9031. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9032. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9033. @pyqtSlot()
  9034. def run(self):
  9035. self.my_loop(self.address)
  9036. # end of file