FlatCAMApp.py 483 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import shutil
  16. from datetime import datetime
  17. import time
  18. import ctypes
  19. import traceback
  20. from PyQt5.QtCore import pyqtSlot, Qt
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Diverse
  37. from FlatCAMCommon import LoudDict, color_variant, ExclusionAreas
  38. from FlatCAMBookmark import BookmarkManager
  39. from FlatCAMDB import ToolsDB2
  40. from vispy.gloo.util import _screenshot
  41. from vispy.io import write_png
  42. # FlatCAM Objects
  43. from defaults import FlatCAMDefaults
  44. from flatcamGUI.preferences.OptionsGroupUI import OptionsGroupUI
  45. from flatcamGUI.preferences.PreferencesUIManager import PreferencesUIManager
  46. from flatcamObjects.ObjectCollection import *
  47. from flatcamObjects.FlatCAMObj import FlatCAMObj
  48. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  49. from flatcamObjects.FlatCAMDocument import DocumentObject
  50. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  51. from flatcamObjects.FlatCAMGeometry import GeometryObject
  52. from flatcamObjects.FlatCAMGerber import GerberObject
  53. from flatcamObjects.FlatCAMScript import ScriptObject
  54. # FlatCAM Parsing files
  55. from flatcamParsers.ParseExcellon import Excellon
  56. from flatcamParsers.ParseGerber import Gerber
  57. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  58. # FlatCAM GUI
  59. from flatcamGUI.PlotCanvas import *
  60. from flatcamGUI.PlotCanvasLegacy import *
  61. from flatcamGUI.FlatCAMGUI import *
  62. from flatcamGUI.GUIElements import FCFileSaveDialog
  63. # FlatCAM Pre-processors
  64. from FlatCAMPostProc import load_preprocessors
  65. # FlatCAM Editors
  66. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  67. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  68. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  69. from flatcamEditors.FlatCAMTextEditor import TextEditor
  70. from flatcamParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from FlatCAMProcess import *
  73. from FlatCAMWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from flatcamTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import FlatCAMTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = 8.993
  138. version_date = "2020/08/01"
  139. beta = True
  140. engine = '3D'
  141. # current date now
  142. date = str(datetime.today()).rpartition('.')[0]
  143. date = ''.join(c for c in date if c not in ':-')
  144. date = date.replace(' ', '_')
  145. # ###############################################################################################################
  146. # ############################################ URLS's ###########################################################
  147. # ###############################################################################################################
  148. # URL for update checks and statistics
  149. version_url = "http://flatcam.org/version"
  150. # App URL
  151. app_url = "http://flatcam.org"
  152. # Manual URL
  153. manual_url = "http://flatcam.org/manual/index.html"
  154. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  155. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  156. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  157. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  158. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  159. # this variable will hold the project status
  160. # if True it will mean that the project was modified and not saved
  161. should_we_save = False
  162. # flag is True if saving action has been triggered
  163. save_in_progress = False
  164. # ###############################################################################################################
  165. # ####################################### APP Signals ######################################################
  166. # ###############################################################################################################
  167. # Inform the user
  168. # Handled by:
  169. # * App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal(str)
  171. app_quit = QtCore.pyqtSignal()
  172. # General purpose background task
  173. worker_task = QtCore.pyqtSignal(dict)
  174. # File opened
  175. # Handled by:
  176. # * register_folder()
  177. # * register_recent()
  178. # Note: Setting the parameters to unicode does not seem
  179. # to have an effect. Then are received as Qstring
  180. # anyway.
  181. # File type and filename
  182. file_opened = QtCore.pyqtSignal(str, str)
  183. # File type and filename
  184. file_saved = QtCore.pyqtSignal(str, str)
  185. # Percentage of progress
  186. progress = QtCore.pyqtSignal(int)
  187. plots_updated = QtCore.pyqtSignal()
  188. # Emitted by new_object() and passes the new object as argument, plot flag.
  189. # on_object_created() adds the object to the collection, plots on appropriate flag
  190. # and emits new_object_available.
  191. object_created = QtCore.pyqtSignal(object, bool, bool)
  192. # Emitted when a object has been changed (like scaled, mirrored)
  193. object_changed = QtCore.pyqtSignal(object)
  194. # Emitted after object has been plotted.
  195. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  196. object_plotted = QtCore.pyqtSignal(object)
  197. # Emitted when a new object has been added or deleted from/to the collection
  198. object_status_changed = QtCore.pyqtSignal(object, str, str)
  199. message = QtCore.pyqtSignal(str, str, str)
  200. # Emmited when shell command is finished(one command only)
  201. shell_command_finished = QtCore.pyqtSignal(object)
  202. # Emitted when multiprocess pool has been recreated
  203. pool_recreated = QtCore.pyqtSignal(object)
  204. # Emitted when an unhandled exception happens
  205. # in the worker task.
  206. thread_exception = QtCore.pyqtSignal(object)
  207. # used to signal that there are arguments for the app
  208. args_at_startup = QtCore.pyqtSignal(list)
  209. # a reusable signal to replot a list of objects
  210. # should be disconnected after use so it can be reused
  211. replot_signal = pyqtSignal(list)
  212. # signal emitted when jumping
  213. jump_signal = pyqtSignal(tuple)
  214. # signal emitted when jumping
  215. locate_signal = pyqtSignal(tuple, str)
  216. # close app signal
  217. close_app_signal = pyqtSignal()
  218. # will perform the cleanup operation after a Graceful Exit
  219. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  220. # graphic residues behind
  221. cleanup = pyqtSignal()
  222. def __init__(self, user_defaults=True):
  223. """
  224. Starts the application.
  225. :return: app
  226. :rtype: App
  227. """
  228. super().__init__()
  229. App.log.info("FlatCAM Starting...")
  230. self.main_thread = QtWidgets.QApplication.instance().thread()
  231. # ############################################################################################################
  232. # ################# Setup the listening thread for another instance launching with args ######################
  233. # ############################################################################################################
  234. if sys.platform == 'win32' or sys.platform == 'linux':
  235. # make sure the thread is stored by using a self. otherwise it's garbage collected
  236. self.th = QtCore.QThread()
  237. self.th.start(priority=QtCore.QThread.LowestPriority)
  238. self.new_launch = ArgsThread()
  239. self.new_launch.open_signal[list].connect(self.on_startup_args)
  240. self.new_launch.moveToThread(self.th)
  241. self.new_launch.start.emit()
  242. # ############################################################################################################
  243. # # ######################################## OS-specific #####################################################
  244. # ############################################################################################################
  245. portable = False
  246. # Folder for user settings.
  247. if sys.platform == 'win32':
  248. if platform.architecture()[0] == '32bit':
  249. App.log.debug("Win32!")
  250. else:
  251. App.log.debug("Win64!")
  252. # #######################################################################################################
  253. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  254. # #######################################################################################################
  255. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  256. try:
  257. with open(config_file, 'r'):
  258. pass
  259. except FileNotFoundError:
  260. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  261. try:
  262. with open(config_file, 'r') as f:
  263. try:
  264. for line in f:
  265. param = str(line).replace('\n', '').rpartition('=')
  266. if param[0] == 'portable':
  267. try:
  268. portable = eval(param[2])
  269. except NameError:
  270. portable = False
  271. if param[0] == 'headless':
  272. if param[2].lower() == 'true':
  273. self.cmd_line_headless = 1
  274. else:
  275. self.cmd_line_headless = None
  276. except Exception as e:
  277. log.debug('App.__init__() -->%s' % str(e))
  278. return
  279. except FileNotFoundError as e:
  280. log.debug(str(e))
  281. pass
  282. if portable is False:
  283. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  284. else:
  285. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  286. self.os = 'windows'
  287. else: # Linux/Unix/MacOS
  288. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  289. self.os = 'unix'
  290. # ############################################################################################################
  291. # ################################# Setup folders and files ##################################################
  292. # ############################################################################################################
  293. if not os.path.exists(self.data_path):
  294. os.makedirs(self.data_path)
  295. App.log.debug('Created data folder: ' + self.data_path)
  296. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  297. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  298. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  299. if not os.path.exists(self.preprocessorpaths):
  300. os.makedirs(self.preprocessorpaths)
  301. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  302. # create geo_tools_db.FlatDB file if there is none
  303. try:
  304. f = open(self.data_path + '/geo_tools_db.FlatDB')
  305. f.close()
  306. except IOError:
  307. App.log.debug('Creating empty geo_tool_db.FlatDB')
  308. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  309. json.dump({}, f)
  310. f.close()
  311. # create current_defaults.FlatConfig file if there is none
  312. try:
  313. f = open(self.data_path + '/current_defaults.FlatConfig')
  314. f.close()
  315. except IOError:
  316. App.log.debug('Creating empty current_defaults.FlatConfig')
  317. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  318. json.dump({}, f)
  319. f.close()
  320. # Write factory_defaults.FlatConfig file to disk
  321. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  322. # create a recent files json file if there is none
  323. try:
  324. f = open(self.data_path + '/recent.json')
  325. f.close()
  326. except IOError:
  327. App.log.debug('Creating empty recent.json')
  328. f = open(self.data_path + '/recent.json', 'w')
  329. json.dump([], f)
  330. f.close()
  331. # create a recent projects json file if there is none
  332. try:
  333. fp = open(self.data_path + '/recent_projects.json')
  334. fp.close()
  335. except IOError:
  336. App.log.debug('Creating empty recent_projects.json')
  337. fp = open(self.data_path + '/recent_projects.json', 'w')
  338. json.dump([], fp)
  339. fp.close()
  340. # Application directory. CHDIR to it. Otherwise, trying to load
  341. # GUI icons will fail as their path is relative.
  342. # This will fail under cx_freeze ...
  343. self.app_home = os.path.dirname(os.path.realpath(__file__))
  344. App.log.debug("Application path is " + self.app_home)
  345. App.log.debug("Started in " + os.getcwd())
  346. # cx_freeze workaround
  347. if os.path.isfile(self.app_home):
  348. self.app_home = os.path.dirname(self.app_home)
  349. os.chdir(self.app_home)
  350. # ############################################################################################################
  351. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  352. # ############################################################################################################
  353. self.defaults = FlatCAMDefaults()
  354. self.defaults["root_folder_path"] = self.app_home
  355. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  356. if user_defaults:
  357. self.defaults.load(filename=current_defaults_path)
  358. if self.defaults['units'] == 'MM':
  359. self.decimals = int(self.defaults['decimals_metric'])
  360. else:
  361. self.decimals = int(self.defaults['decimals_inch'])
  362. if self.defaults["global_gray_icons"] is False:
  363. self.resource_location = 'assets/resources'
  364. else:
  365. self.resource_location = 'assets/resources/dark_resources'
  366. self.current_units = self.defaults['units']
  367. # ###########################################################################################################
  368. # #################################### SETUP OBJECT CLASSES #################################################
  369. # ###########################################################################################################
  370. self.setup_obj_classes()
  371. # ###########################################################################################################
  372. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  373. # ###########################################################################################################
  374. self.pool = Pool()
  375. # ###########################################################################################################
  376. # ###################################### Setting the Splash Screen ##########################################
  377. # ###########################################################################################################
  378. splash_settings = QSettings("Open Source", "FlatCAM")
  379. if splash_settings.contains("splash_screen"):
  380. show_splash = splash_settings.value("splash_screen")
  381. else:
  382. splash_settings.setValue('splash_screen', 1)
  383. # This will write the setting to the platform specific storage.
  384. del splash_settings
  385. show_splash = 1
  386. if show_splash and self.cmd_line_headless != 1:
  387. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  388. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  389. # self.splash.setMask(splash_pix.mask())
  390. # move splashscreen to the current monitor
  391. desktop = QtWidgets.QApplication.desktop()
  392. screen = desktop.screenNumber(QtGui.QCursor.pos())
  393. current_screen_center = desktop.availableGeometry(screen).center()
  394. self.splash.move(current_screen_center - self.splash.rect().center())
  395. self.splash.show()
  396. self.splash.showMessage(_("FlatCAM is initializing ..."),
  397. alignment=Qt.AlignBottom | Qt.AlignLeft,
  398. color=QtGui.QColor("gray"))
  399. else:
  400. show_splash = 0
  401. # ###########################################################################################################
  402. # ######################################### Initialize GUI ##################################################
  403. # ###########################################################################################################
  404. # FlatCAM colors used in plotting
  405. self.FC_light_green = '#BBF268BF'
  406. self.FC_dark_green = '#006E20BF'
  407. self.FC_light_blue = '#a5a5ffbf'
  408. self.FC_dark_blue = '#0000ffbf'
  409. self.ui = FlatCAMGUI(self)
  410. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  411. if theme_settings.contains("theme"):
  412. theme = theme_settings.value('theme', type=str)
  413. else:
  414. theme = 'white'
  415. if self.defaults["global_cursor_color_enabled"]:
  416. self.cursor_color_3D = self.defaults["global_cursor_color"]
  417. else:
  418. if theme == 'white':
  419. self.cursor_color_3D = 'black'
  420. else:
  421. self.cursor_color_3D = 'gray'
  422. # update the defaults dict with the setting in QSetting
  423. self.defaults['global_theme'] = theme
  424. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  425. self.ui.final_save.connect(self.final_save)
  426. # restore the toolbar view
  427. self.restore_toolbar_view()
  428. # restore the GUI geometry
  429. self.restore_main_win_geom()
  430. # set FlatCAM units in the Status bar
  431. self.set_screen_units(self.defaults['units'])
  432. # ###########################################################################################################
  433. # ########################################### AUTOSAVE SETUP ################################################
  434. # ###########################################################################################################
  435. self.block_autosave = False
  436. self.autosave_timer = QtCore.QTimer(self)
  437. self.save_project_auto_update()
  438. self.autosave_timer.timeout.connect(self.save_project_auto)
  439. # ###########################################################################################################
  440. # #################################### LOAD PREPROCESSORS ###################################################
  441. # ###########################################################################################################
  442. # ----------------------------------------- WARNING --------------------------------------------------------
  443. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  444. # That's because the number of preprocessors can vary and here the comboboxes are populated
  445. # -----------------------------------------------------------------------------------------------------------
  446. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  447. # the preprocessor file
  448. self.preprocessors = load_preprocessors(self)
  449. # make sure that always the 'default' preprocessor is the first item in the dictionary
  450. if 'default' in self.preprocessors.keys():
  451. new_ppp_dict = {}
  452. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  453. default_pp = self.preprocessors.pop('default')
  454. new_ppp_dict['default'] = default_pp
  455. # then add the rest of the keys
  456. for name, val_class in self.preprocessors.items():
  457. new_ppp_dict[name] = val_class
  458. # and now put back the ordered dict with 'default' key first
  459. self.preprocessors = new_ppp_dict
  460. for name in list(self.preprocessors.keys()):
  461. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  462. if name.partition('_')[0] == 'Paste':
  463. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  464. continue
  465. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  466. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  467. if name == 'hpgl':
  468. continue
  469. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  470. # ###########################################################################################################
  471. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  472. # ###########################################################################################################
  473. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  474. inform=self.inform)
  475. self.preferencesUiManager.defaults_write_form()
  476. # When the self.defaults dictionary changes will update the Preferences GUI forms
  477. self.defaults.set_change_callback(self.on_defaults_dict_change)
  478. # ###########################################################################################################
  479. # ##################################### FIRST RUN SECTION ###################################################
  480. # ################################ It's done only once after install #####################################
  481. # ###########################################################################################################
  482. if self.defaults["first_run"] is True:
  483. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  484. initial_lay = 'minimal'
  485. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  486. # Set the combobox in Preferences to the current layout
  487. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  488. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  489. # after the first run, this object should be False
  490. self.defaults["first_run"] = False
  491. self.preferencesUiManager.save_defaults(silent=True)
  492. # ###########################################################################################################
  493. # ############################################ Data #########################################################
  494. # ###########################################################################################################
  495. self.recent = []
  496. self.recent_projects = []
  497. self.clipboard = QtWidgets.QApplication.clipboard()
  498. self.project_filename = None
  499. self.toggle_units_ignore = False
  500. # ###########################################################################################################
  501. # ########################################## LOAD LANGUAGES ################################################
  502. # ###########################################################################################################
  503. self.languages = fcTranslate.load_languages()
  504. for name in sorted(self.languages.values()):
  505. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  506. # ###########################################################################################################
  507. # ####################################### APPLY APP LANGUAGE ################################################
  508. # ###########################################################################################################
  509. ret_val = fcTranslate.apply_language('strings')
  510. if ret_val == "no language":
  511. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  512. log.debug("Could not find the Language files. The App strings are missing.")
  513. else:
  514. # make the current language the current selection on the language combobox
  515. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  516. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  517. # ###########################################################################################################
  518. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  519. # ###########################################################################################################
  520. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  521. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  522. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  523. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  524. self.defaults.propagate_defaults()
  525. # ###########################################################################################################
  526. # ######################################## UPDATE THE OPTIONS ###############################################
  527. # ###########################################################################################################
  528. self.options = LoudDict()
  529. # -----------------------------------------------------------------------------------------------------------
  530. # Update the self.options from the self.defaults
  531. # The self.defaults holds the application defaults while the self.options holds the object defaults
  532. # -----------------------------------------------------------------------------------------------------------
  533. # Copy app defaults to project options
  534. for def_key, def_val in self.defaults.items():
  535. self.options[def_key] = deepcopy(def_val)
  536. self.preferencesUiManager.show_preferences_gui()
  537. # ### End of Data ####
  538. # ###########################################################################################################
  539. # #################################### SETUP OBJECT COLLECTION ##############################################
  540. # ###########################################################################################################
  541. self.collection = ObjectCollection(self)
  542. self.ui.project_tab_layout.addWidget(self.collection.view)
  543. # ### Adjust tabs width ## ##
  544. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  545. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  546. self.collection.view.setMinimumWidth(290)
  547. self.log.debug("Finished creating Object Collection.")
  548. # ###########################################################################################################
  549. # ######################################## SETUP Plot Area ##################################################
  550. # ###########################################################################################################
  551. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  552. if self.defaults["global_graphic_engine"] == '3D':
  553. self.is_legacy = False
  554. else:
  555. self.is_legacy = True
  556. # Event signals disconnect id holders
  557. self.mp = None
  558. self.mm = None
  559. self.mr = None
  560. self.mdc = None
  561. self.mp_zc = None
  562. self.kp = None
  563. # Matplotlib axis
  564. self.axes = None
  565. if show_splash:
  566. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  567. "Canvas initialization started."),
  568. alignment=Qt.AlignBottom | Qt.AlignLeft,
  569. color=QtGui.QColor("gray"))
  570. start_plot_time = time.time() # debug
  571. self.plotcanvas = None
  572. self.app_cursor = None
  573. self.hover_shapes = None
  574. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  575. # setup the PlotCanvas
  576. self.on_plotcanvas_setup()
  577. end_plot_time = time.time()
  578. self.used_time = end_plot_time - start_plot_time
  579. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  580. if show_splash:
  581. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  582. "Canvas initialization started.\n"
  583. "Canvas initialization finished in"), '%.2f' % self.used_time),
  584. alignment=Qt.AlignBottom | Qt.AlignLeft,
  585. color=QtGui.QColor("gray"))
  586. self.ui.splitter.setStretchFactor(1, 2)
  587. # ###########################################################################################################
  588. # ############################################### SYS TRAY ##################################################
  589. # ###########################################################################################################
  590. if self.defaults["global_systray_icon"]:
  591. self.parent_w = QtWidgets.QWidget()
  592. if self.cmd_line_headless == 1:
  593. self.trayIcon = FlatCAMSystemTray(app=self,
  594. icon=QtGui.QIcon(self.resource_location +
  595. '/flatcam_icon32_green.png'),
  596. headless=True,
  597. parent=self.parent_w)
  598. else:
  599. self.trayIcon = FlatCAMSystemTray(app=self,
  600. icon=QtGui.QIcon(self.resource_location +
  601. '/flatcam_icon32_green.png'),
  602. parent=self.parent_w)
  603. # ###########################################################################################################
  604. # ############################################### Worker SETUP ##############################################
  605. # ###########################################################################################################
  606. if self.defaults["global_worker_number"]:
  607. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  608. else:
  609. self.workers = WorkerStack(workers_number=2)
  610. self.worker_task.connect(self.workers.add_task)
  611. self.log.debug("Finished creating Workers crew.")
  612. # ###########################################################################################################
  613. # ############################################# Activity Monitor ###########################################
  614. # ###########################################################################################################
  615. self.activity_view = FlatCAMActivityView(app=self)
  616. self.ui.infobar.addWidget(self.activity_view)
  617. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  618. # ###########################################################################################################
  619. # ############################################# Signal handling #############################################
  620. # ###########################################################################################################
  621. # ########################################## Custom signals ################################################
  622. # signal for displaying messages in status bar
  623. self.inform.connect(self.info)
  624. # signal to be called when the app is quiting
  625. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  626. self.message.connect(self.message_dialog)
  627. # self.progress.connect(self.set_progress_bar)
  628. # signals that are emitted when object state changes
  629. self.object_created.connect(self.on_object_created)
  630. self.object_changed.connect(self.on_object_changed)
  631. self.object_plotted.connect(self.on_object_plotted)
  632. self.plots_updated.connect(self.on_plots_updated)
  633. # signals emitted when file state change
  634. self.file_opened.connect(self.register_recent)
  635. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  636. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  637. # ########################################## Standard signals ###############################################
  638. # ### Menu
  639. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  640. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  641. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  642. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  643. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  644. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  645. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  646. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  647. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  648. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  649. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  650. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  651. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  652. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  653. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  654. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  655. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  656. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  657. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  658. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  659. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  660. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  661. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  662. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  663. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  664. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  665. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  666. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  667. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  668. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  669. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  670. self.ui.menufile_exit.triggered.connect(self.final_save)
  671. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  672. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  673. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  674. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  675. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  676. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  677. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  678. self.ui.menueditdelete.triggered.connect(self.on_delete)
  679. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  680. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  681. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  682. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  683. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  684. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  685. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  686. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  687. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  688. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  689. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  690. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  691. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  692. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  693. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  694. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  695. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  696. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  697. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  698. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  699. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  700. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  701. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  702. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  703. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  704. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  705. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  706. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  707. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  708. self.ui.menuview_replot.triggered.connect(self.plot_all)
  709. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  710. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  711. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  712. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  713. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  714. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  715. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  716. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  717. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  718. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  719. self.ui.menuhelp_about.triggered.connect(self.on_about)
  720. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  721. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  722. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  723. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  724. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  725. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  726. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  727. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  728. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  729. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  730. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  731. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  732. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  733. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  734. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  735. # ToolBar signals
  736. self.connect_toolbar_signals()
  737. # Notebook and Plot Tab Area signals
  738. # make the right click on the notebook tab and plot tab area tab raise a menu
  739. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  740. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  741. self.on_tab_setup_context_menu()
  742. # activate initial state
  743. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  744. # Context Menu
  745. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  746. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  747. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  748. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  749. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  750. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  751. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  752. self.ui.clearplot.triggered.connect(self.clear_plots)
  753. self.ui.replot.triggered.connect(self.plot_all)
  754. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  755. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  756. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  757. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  758. self.ui.popmenu_move.triggered.connect(self.obj_move)
  759. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  760. # Project Context Menu -> Color Setting
  761. for act in self.ui.menuprojectcolor.actions():
  762. act.triggered.connect(self.on_set_color_action_triggered)
  763. # ###########################################################################################################
  764. # #################################### GUI PREFERENCES SIGNALS ##############################################
  765. # ###########################################################################################################
  766. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  767. lambda: self.on_toggle_units(no_pref=False))
  768. # ##################################### Workspace Setting Signals ###########################################
  769. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  770. self.on_workspace_modified)
  771. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  772. self.on_workspace_modified
  773. )
  774. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  775. # ###########################################################################################################
  776. # ######################################## GUI SETTINGS SIGNALS #############################################
  777. # ###########################################################################################################
  778. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  779. # ######################################## Tools related signals ############################################
  780. # Film Tool
  781. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  782. self.on_film_color_entry)
  783. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  784. self.on_film_color_button)
  785. # QRCode Tool
  786. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  787. self.on_qrcode_fill_color_entry)
  788. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  789. self.on_qrcode_fill_color_button)
  790. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  791. self.on_qrcode_back_color_entry)
  792. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  793. self.on_qrcode_back_color_button)
  794. # portability changed signal
  795. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  796. # Object list
  797. self.collection.view.activated.connect(self.on_row_activated)
  798. self.collection.item_selected.connect(self.on_row_selected)
  799. self.object_status_changed.connect(self.on_collection_updated)
  800. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  801. # Export Excellon parameters.
  802. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  803. self.on_update_exc_export
  804. )
  805. # call it once to make sure it is updated at startup
  806. self.on_update_exc_export(state=self.defaults["excellon_update"])
  807. # when there are arguments at application startup this get launched
  808. self.args_at_startup[list].connect(self.on_startup_args)
  809. # ###########################################################################################################
  810. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  811. # ###########################################################################################################
  812. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  813. lambda: self.restore_extensions(ext_type='excellon'))
  814. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  815. lambda: self.restore_extensions(ext_type='gcode'))
  816. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  817. lambda: self.restore_extensions(ext_type='gerber'))
  818. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  819. lambda: self.delete_all_extensions(ext_type='excellon'))
  820. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  821. lambda: self.delete_all_extensions(ext_type='gcode'))
  822. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  823. lambda: self.delete_all_extensions(ext_type='gerber'))
  824. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  825. lambda: self.add_extension(ext_type='excellon'))
  826. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  827. lambda: self.add_extension(ext_type='gcode'))
  828. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  829. lambda: self.add_extension(ext_type='gerber'))
  830. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  831. lambda: self.del_extension(ext_type='excellon'))
  832. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  833. lambda: self.del_extension(ext_type='gcode'))
  834. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  835. lambda: self.del_extension(ext_type='gerber'))
  836. # connect the 'Apply' buttons from the Preferences/File Associations
  837. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  838. lambda: self.on_register_files(obj_type='excellon'))
  839. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  840. lambda: self.on_register_files(obj_type='gcode'))
  841. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  842. lambda: self.on_register_files(obj_type='gerber'))
  843. # ###########################################################################################################
  844. # ########################################### KEYWORDS SIGNALS ##############################################
  845. # ###########################################################################################################
  846. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  847. lambda: self.restore_extensions(ext_type='keyword'))
  848. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  849. lambda: self.delete_all_extensions(ext_type='keyword'))
  850. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  851. lambda: self.add_extension(ext_type='keyword'))
  852. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  853. lambda: self.del_extension(ext_type='keyword'))
  854. # connect the abort_all_tasks related slots to the related signals
  855. self.proc_container.idle_flag.connect(self.app_is_idle)
  856. # signal emitted when a tab is closed in the Plot Area
  857. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  858. # signal to close the application
  859. self.close_app_signal.connect(self.kill_app)
  860. # ################################# FINISHED CONNECTING SIGNALS #############################################
  861. # ###########################################################################################################
  862. # ###########################################################################################################
  863. # ###########################################################################################################
  864. self.log.debug("Finished connecting Signals.")
  865. # ###########################################################################################################
  866. # ########################################## Other setups ###################################################
  867. # ###########################################################################################################
  868. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  869. # depending on from where those tools are called different actions can be done
  870. self.call_source = 'app'
  871. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  872. self.tool_tab_locked = False
  873. # decide if to show or hide the Notebook side of the screen at startup
  874. if self.defaults["global_project_at_startup"] is True:
  875. self.ui.splitter.setSizes([1, 1])
  876. else:
  877. self.ui.splitter.setSizes([0, 1])
  878. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  879. self.setup_component_editor()
  880. # ###########################################################################################################
  881. # ####################################### Auto-complete KEYWORDS ############################################
  882. # ###########################################################################################################
  883. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  884. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  885. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  886. 'export_exc',
  887. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  888. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  889. 'interiors', 'isolate', 'join_excellon',
  890. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  891. 'mirror', 'ncc',
  892. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  893. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  894. 'options', 'origin',
  895. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  896. 'save', 'save_project',
  897. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  898. 'skew', 'subtract_poly', 'subtract_rectangle',
  899. 'version', 'write_gcode'
  900. ]
  901. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  902. 'Paste_1',
  903. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  904. 'Toolchange_manual', 'True', 'Users',
  905. 'all', 'auto', 'axis',
  906. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  907. 'contour', 'default',
  908. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  909. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  910. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  911. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  912. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  913. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  914. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  915. 'spacing_columns',
  916. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  917. 'toolchange_xy', 'toolchangez', 'travelz',
  918. 'tooldia', 'use_threads', 'value',
  919. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  920. ]
  921. self.tcl_keywords = [
  922. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  923. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  924. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  925. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  926. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  927. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  928. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  929. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  930. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  931. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  932. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  933. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  934. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  935. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  936. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  937. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  938. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  939. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  940. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  941. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  942. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  943. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  944. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  945. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  946. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  947. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  948. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  949. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  950. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  951. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  952. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  953. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  954. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  955. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  956. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  957. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  958. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  959. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  960. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  961. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  962. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  963. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  964. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  965. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  966. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  967. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  968. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  969. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  970. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  971. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  972. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  973. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  974. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  975. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  976. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  977. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  978. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  979. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  980. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  981. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  982. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  983. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  984. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  985. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  986. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  987. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  988. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  989. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  990. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  991. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  992. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  993. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  994. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  995. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  996. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  997. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  998. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  999. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1000. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1001. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1002. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1003. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1004. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1005. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1006. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1007. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1008. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1009. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1010. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1011. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1012. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1013. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1014. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1015. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1016. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1017. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1018. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1019. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1020. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1021. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1022. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1023. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1024. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1025. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1026. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1027. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1028. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1029. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1030. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1031. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1032. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1033. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1034. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1035. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1036. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1037. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1038. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1039. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1040. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1041. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1042. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1043. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1044. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1045. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1046. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1047. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1048. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1049. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1050. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1051. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1052. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1053. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1054. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1055. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1056. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1057. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1058. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1059. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1060. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1061. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1062. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1063. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1064. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1065. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1066. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1067. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1068. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1069. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1070. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1071. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1072. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1073. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1074. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1075. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1076. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1077. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1078. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1079. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1080. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1081. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1082. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1083. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1084. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1085. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1086. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1087. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1088. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1089. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1090. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1091. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1092. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1093. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1094. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1095. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1096. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1097. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1098. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1099. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1100. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1101. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1102. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1103. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1104. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1105. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1106. ]
  1107. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1108. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1109. # ###########################################################################################################
  1110. # ############################################## Shell SETUP ################################################
  1111. # ###########################################################################################################
  1112. self.shell = FCShell(app=self, version=self.version)
  1113. self.ui.shell_dock.setWidget(self.shell)
  1114. self.log.debug("TCL Shell has been initialized.")
  1115. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1116. if self.defaults["global_shell_at_startup"]:
  1117. self.ui.shell_dock.show()
  1118. else:
  1119. self.ui.shell_dock.hide()
  1120. # ###########################################################################################################
  1121. # ########################################## Tools and Plugins ##############################################
  1122. # ###########################################################################################################
  1123. self.dblsidedtool = None
  1124. self.distance_tool = None
  1125. self.distance_min_tool = None
  1126. self.panelize_tool = None
  1127. self.film_tool = None
  1128. self.paste_tool = None
  1129. self.calculator_tool = None
  1130. self.rules_tool = None
  1131. self.sub_tool = None
  1132. self.move_tool = None
  1133. self.cutout_tool = None
  1134. self.ncclear_tool = None
  1135. self.optimal_tool = None
  1136. self.paint_tool = None
  1137. self.transform_tool = None
  1138. self.properties_tool = None
  1139. self.pdf_tool = None
  1140. self.image_tool = None
  1141. self.pcb_wizard_tool = None
  1142. self.cal_exc_tool = None
  1143. self.qrcode_tool = None
  1144. self.copper_thieving_tool = None
  1145. self.fiducial_tool = None
  1146. self.edrills_tool = None
  1147. self.align_objects_tool = None
  1148. self.punch_tool = None
  1149. self.invert_tool = None
  1150. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1151. try:
  1152. self.install_tools()
  1153. except AttributeError as e:
  1154. log.debug("App.__init__() install tools() --> %s" % str(e))
  1155. # ###########################################################################################################
  1156. # ############################################ SETUP RECENT ITEMS ###########################################
  1157. # ###########################################################################################################
  1158. self.setup_recent_items()
  1159. # ###########################################################################################################
  1160. # ######################################### BookMarks Manager ###############################################
  1161. # ###########################################################################################################
  1162. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1163. self.install_bookmarks()
  1164. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1165. # ###########################################################################################################
  1166. # ########################################### Tools Database ################################################
  1167. # ###########################################################################################################
  1168. self.tools_db_tab = None
  1169. # ### System Font Parsing ###
  1170. # self.f_parse = ParseFont(self)
  1171. # self.parse_system_fonts()
  1172. # ###########################################################################################################
  1173. # ######################################### Check for updates ###############################################
  1174. # ###########################################################################################################
  1175. # Separate thread (Not worker)
  1176. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1177. if (self.beta is False or self.beta is None) and \
  1178. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1179. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1180. # self.thr2 = QtCore.QThread()
  1181. self.worker_task.emit({'fcn': self.version_check,
  1182. 'params': []})
  1183. # self.thr2.start(QtCore.QThread.LowPriority)
  1184. # ###########################################################################################################
  1185. # ##################################### Register files with FlatCAM; #######################################
  1186. # ################################### It works only for Windows for now ####################################
  1187. # ###########################################################################################################
  1188. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1189. self.on_register_files()
  1190. # ###########################################################################################################
  1191. # ######################################## Variables for global usage #######################################
  1192. # ###########################################################################################################
  1193. # hold the App units
  1194. self.units = 'MM'
  1195. # coordinates for relative position display
  1196. self.rel_point1 = (0, 0)
  1197. self.rel_point2 = (0, 0)
  1198. # variable to store coordinates
  1199. self.pos = (0, 0)
  1200. self.pos_canvas = (0, 0)
  1201. self.pos_jump = (0, 0)
  1202. # variable to store mouse coordinates
  1203. self.mouse = [0, 0]
  1204. # variable to store the delta positions on cavnas
  1205. self.dx = 0
  1206. self.dy = 0
  1207. # decide if we have a double click or single click
  1208. self.doubleclick = False
  1209. # store here the is_dragging value
  1210. self.event_is_dragging = False
  1211. # variable to store if a command is active (then the var is not None) and which one it is
  1212. self.command_active = None
  1213. # variable to store the status of moving selection action
  1214. # None value means that it's not an selection action
  1215. # True value = a selection from left to right
  1216. # False value = a selection from right to left
  1217. self.selection_type = None
  1218. # List to store the objects that are currently loaded in FlatCAM
  1219. # This list is updated on each object creation or object delete
  1220. self.all_objects_list = []
  1221. self.objects_under_the_click_list = []
  1222. # List to store the objects that are selected
  1223. self.sel_objects_list = []
  1224. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1225. self.key_modifiers = None
  1226. # Variable to hold the status of the axis
  1227. self.toggle_axis = True
  1228. # Variable to hold the status of the grid lines
  1229. self.toggle_grid_lines = True
  1230. # Variable to store the status of the fullscreen event
  1231. self.toggle_fscreen = False
  1232. # Variable to store the status of the code editor
  1233. self.toggle_codeeditor = False
  1234. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1235. self.click_noproject = False
  1236. self.cursor = None
  1237. # Variable to store the GCODE that was edited
  1238. self.gcode_edited = ""
  1239. self.text_editor_tab = None
  1240. # reference for the self.ui.code_editor
  1241. self.reference_code_editor = None
  1242. self.script_code = ''
  1243. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1244. self.tools_db_changed_flag = False
  1245. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1246. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1247. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1248. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1249. 'tsm']
  1250. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1251. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1252. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1253. 'sbp', 'tap', 'xpi']
  1254. self.svg_list = ['svg']
  1255. self.dxf_list = ['dxf']
  1256. self.pdf_list = ['pdf']
  1257. self.prj_list = ['flatprj']
  1258. self.conf_list = ['flatconfig']
  1259. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1260. # flag for polygons not cleared
  1261. self.poly_not_cleared = False
  1262. # VisPy visuals
  1263. self.isHovering = False
  1264. self.notHovering = True
  1265. # Window geometry
  1266. self.x_pos = None
  1267. self.y_pos = None
  1268. self.width = None
  1269. self.height = None
  1270. # when True, the app has to return from any thread
  1271. self.abort_flag = False
  1272. # set the value used in the Windows Title
  1273. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1274. # this holds a widget that is installed in the Plot Area when View Source option is used
  1275. self.source_editor_tab = None
  1276. self.pagesize = {}
  1277. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1278. # VisPy visuals
  1279. if self.is_legacy is False:
  1280. try:
  1281. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1282. except AttributeError:
  1283. self.tool_shapes = None
  1284. else:
  1285. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1286. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1287. # used in the delayed shutdown self.start_delayed_quit() method
  1288. self.save_timer = None
  1289. # ###########################################################################################################
  1290. # ################################## ADDING FlatCAM EDITORS section #########################################
  1291. # ###########################################################################################################
  1292. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1293. # at the first launch of the App , the editors will not be functional.
  1294. try:
  1295. self.geo_editor = FlatCAMGeoEditor(self)
  1296. except AttributeError:
  1297. pass
  1298. try:
  1299. self.exc_editor = FlatCAMExcEditor(self)
  1300. except AttributeError:
  1301. pass
  1302. try:
  1303. self.grb_editor = FlatCAMGrbEditor(self)
  1304. except AttributeError:
  1305. pass
  1306. self.log.debug("Finished adding FlatCAM Editor's.")
  1307. self.set_ui_title(name=_("New Project - Not saved"))
  1308. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1309. current_platform = platform.architecture()[0]
  1310. if current_platform != '64bit':
  1311. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1312. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1313. # ###########################################################################################################
  1314. # ########################################### EXCLUSION AREAS ###############################################
  1315. # ###########################################################################################################
  1316. self.exc_areas = ExclusionAreas(app=self)
  1317. # ###########################################################################################################
  1318. # ##################################### Finished the CONSTRUCTOR ############################################
  1319. # ###########################################################################################################
  1320. App.log.debug("END of constructor. Releasing control.")
  1321. # ###########################################################################################################
  1322. # ########################################## SHOW GUI #######################################################
  1323. # ###########################################################################################################
  1324. # if the app is not started as headless, show it
  1325. if self.cmd_line_headless != 1:
  1326. if show_splash:
  1327. # finish the splash
  1328. self.splash.finish(self.ui)
  1329. mgui_settings = QSettings("Open Source", "FlatCAM")
  1330. if mgui_settings.contains("maximized_gui"):
  1331. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1332. if maximized_ui is True:
  1333. self.ui.showMaximized()
  1334. else:
  1335. self.ui.show()
  1336. else:
  1337. self.ui.show()
  1338. if self.defaults["global_systray_icon"]:
  1339. self.trayIcon.show()
  1340. else:
  1341. log.warning("******************* RUNNING HEADLESS *******************")
  1342. # ###########################################################################################################
  1343. # ######################################## START-UP ARGUMENTS ###############################################
  1344. # ###########################################################################################################
  1345. # test if the program was started with a script as parameter
  1346. if self.cmd_line_shellvar:
  1347. try:
  1348. cnt = 0
  1349. command_tcl = 0
  1350. for i in self.cmd_line_shellvar.split(','):
  1351. if i is not None:
  1352. # noinspection PyBroadException
  1353. try:
  1354. command_tcl = eval(i)
  1355. except Exception:
  1356. command_tcl = i
  1357. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1358. cnt += 1
  1359. # if there are Windows paths then replace the path separator with a Unix like one
  1360. if sys.platform == 'win32':
  1361. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1362. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1363. except Exception as ext:
  1364. print("ERROR: ", ext)
  1365. sys.exit(2)
  1366. if self.cmd_line_shellfile:
  1367. if self.cmd_line_headless != 1:
  1368. if self.ui.shell_dock.isHidden():
  1369. self.ui.shell_dock.show()
  1370. try:
  1371. with open(self.cmd_line_shellfile, "r") as myfile:
  1372. # if show_splash:
  1373. # self.splash.showMessage('%s: %ssec\n%s' % (
  1374. # _("Canvas initialization started.\n"
  1375. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1376. # _("Executing Tcl Script ...")),
  1377. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1378. # color=QtGui.QColor("gray"))
  1379. cmd_line_shellfile_text = myfile.read()
  1380. if self.cmd_line_headless != 1:
  1381. self.shell.exec_command(cmd_line_shellfile_text)
  1382. else:
  1383. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1384. except Exception as ext:
  1385. print("ERROR: ", ext)
  1386. sys.exit(2)
  1387. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1388. # the path/file_name must be enclosed in quotes if it contain spaces
  1389. if App.args:
  1390. self.args_at_startup.emit(App.args)
  1391. if self.defaults.old_defaults_found is True:
  1392. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1393. "Please reboot the application to update."))
  1394. self.defaults.old_defaults_found = False
  1395. # ######################################### INIT FINISHED #######################################################
  1396. # #################################################################################################################
  1397. # #################################################################################################################
  1398. # #################################################################################################################
  1399. # #################################################################################################################
  1400. # #################################################################################################################
  1401. @staticmethod
  1402. def copy_and_overwrite(from_path, to_path):
  1403. """
  1404. From here:
  1405. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1406. :param from_path: source path
  1407. :param to_path: destination path
  1408. :return: None
  1409. """
  1410. if os.path.exists(to_path):
  1411. shutil.rmtree(to_path)
  1412. try:
  1413. shutil.copytree(from_path, to_path)
  1414. except FileNotFoundError:
  1415. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1416. shutil.copytree(from_new_path, to_path)
  1417. def on_startup_args(self, args, silent=False):
  1418. """
  1419. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1420. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1421. :param args: a list containing the application args at startup
  1422. :return: None
  1423. """
  1424. if args is not None:
  1425. args_to_process = args
  1426. else:
  1427. args_to_process = App.args
  1428. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1429. for argument in args_to_process:
  1430. if '.FlatPrj'.lower() in argument.lower():
  1431. try:
  1432. project_name = str(argument)
  1433. if project_name == "":
  1434. if silent is False:
  1435. self.inform.emit(_("Cancelled."))
  1436. else:
  1437. # self.open_project(project_name)
  1438. run_from_arg = True
  1439. # self.worker_task.emit({'fcn': self.open_project,
  1440. # 'params': [project_name, run_from_arg]})
  1441. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1442. except Exception as e:
  1443. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1444. elif '.FlatConfig'.lower() in argument.lower():
  1445. try:
  1446. file_name = str(argument)
  1447. if file_name == "":
  1448. if silent is False:
  1449. self.inform.emit(_("Open Config file failed."))
  1450. else:
  1451. run_from_arg = True
  1452. # self.worker_task.emit({'fcn': self.open_config_file,
  1453. # 'params': [file_name, run_from_arg]})
  1454. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1455. except Exception as e:
  1456. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1457. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1458. try:
  1459. file_name = str(argument)
  1460. if file_name == "":
  1461. if silent is False:
  1462. self.inform.emit(_("Open Script file failed."))
  1463. else:
  1464. if silent is False:
  1465. self.on_fileopenscript(name=file_name)
  1466. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1467. self.on_filerunscript(name=file_name)
  1468. except Exception as e:
  1469. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1470. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1471. log.debug("App.on_startup_args() --> Quit event.")
  1472. sys.exit()
  1473. elif 'save'.lower() in argument.lower():
  1474. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1475. self.preferencesUiManager.save_defaults()
  1476. else:
  1477. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1478. proc_arg = argument.lower()
  1479. for ext in exc_list:
  1480. proc_ext = ext.replace(' ', '')
  1481. proc_ext = '.%s' % proc_ext
  1482. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1483. file_name = str(argument)
  1484. if file_name == "":
  1485. if silent is False:
  1486. self.inform.emit(_("Open Excellon file failed."))
  1487. else:
  1488. self.on_fileopenexcellon(name=file_name, signal=None)
  1489. return
  1490. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1491. for ext in gco_list:
  1492. proc_ext = ext.replace(' ', '')
  1493. proc_ext = '.%s' % proc_ext
  1494. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1495. file_name = str(argument)
  1496. if file_name == "":
  1497. if silent is False:
  1498. self.inform.emit(_("Open GCode file failed."))
  1499. else:
  1500. self.on_fileopengcode(name=file_name, signal=None)
  1501. return
  1502. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1503. for ext in grb_list:
  1504. proc_ext = ext.replace(' ', '')
  1505. proc_ext = '.%s' % proc_ext
  1506. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1507. file_name = str(argument)
  1508. if file_name == "":
  1509. if silent is False:
  1510. self.inform.emit(_("Open Gerber file failed."))
  1511. else:
  1512. self.on_fileopengerber(name=file_name, signal=None)
  1513. return
  1514. # if it reached here without already returning then the app was registered with a file that it does not
  1515. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1516. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1517. # for arg in args_to_process:
  1518. # if 'FlatCAM.exe' in arg:
  1519. # continue
  1520. # else:
  1521. # sys.exit(2)
  1522. def set_ui_title(self, name):
  1523. """
  1524. Sets the title of the main window.
  1525. :param name: String that store the project path and project name
  1526. :return: None
  1527. """
  1528. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1529. (self.version,
  1530. ('BETA' if self.beta else ''),
  1531. platform.architecture()[0],
  1532. self.engine,
  1533. name)
  1534. )
  1535. def on_app_restart(self):
  1536. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1537. # be left in the SySTray
  1538. try:
  1539. self.trayIcon.hide()
  1540. except Exception:
  1541. pass
  1542. fcTranslate.restart_program(app=self)
  1543. def clear_pool(self):
  1544. """
  1545. Clear the multiprocessing pool and calls garbage collector.
  1546. :return: None
  1547. """
  1548. self.pool.close()
  1549. self.pool = Pool()
  1550. self.pool_recreated.emit(self.pool)
  1551. gc.collect()
  1552. def install_tools(self):
  1553. """
  1554. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1555. Instantiation of the Tools classes.
  1556. The order that the tools are installed is important as they can depend on each other install position.
  1557. :return: None
  1558. """
  1559. self.distance_tool = Distance(self)
  1560. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1561. before=self.ui.menueditorigin,
  1562. separator=False)
  1563. self.distance_min_tool = DistanceMin(self)
  1564. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1565. pos=self.ui.menuedit,
  1566. before=self.ui.menueditorigin,
  1567. separator=True)
  1568. self.dblsidedtool = DblSidedTool(self)
  1569. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1570. self.cal_exc_tool = ToolCalibration(self)
  1571. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1572. before=self.dblsidedtool.menuAction,
  1573. separator=False)
  1574. self.align_objects_tool = AlignObjects(self)
  1575. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1576. self.edrills_tool = ToolExtractDrills(self)
  1577. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1578. self.panelize_tool = Panelize(self)
  1579. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1580. self.film_tool = Film(self)
  1581. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1582. self.paste_tool = SolderPaste(self)
  1583. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1584. self.calculator_tool = ToolCalculator(self)
  1585. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1586. self.sub_tool = ToolSub(self)
  1587. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1588. pos=self.ui.menutool, separator=True)
  1589. self.rules_tool = RulesCheck(self)
  1590. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1591. pos=self.ui.menutool, separator=False)
  1592. self.optimal_tool = ToolOptimal(self)
  1593. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1594. pos=self.ui.menutool, separator=True)
  1595. self.move_tool = ToolMove(self)
  1596. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1597. before=self.ui.menueditorigin, separator=True)
  1598. self.cutout_tool = CutOut(self)
  1599. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1600. before=self.sub_tool.menuAction)
  1601. self.ncclear_tool = NonCopperClear(self)
  1602. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1603. before=self.sub_tool.menuAction, separator=True)
  1604. self.paint_tool = ToolPaint(self)
  1605. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1606. before=self.sub_tool.menuAction, separator=True)
  1607. self.copper_thieving_tool = ToolCopperThieving(self)
  1608. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1609. pos=self.ui.menutool)
  1610. self.fiducial_tool = ToolFiducials(self)
  1611. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1612. pos=self.ui.menutool)
  1613. self.qrcode_tool = QRCode(self)
  1614. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1615. pos=self.ui.menutool)
  1616. self.punch_tool = ToolPunchGerber(self)
  1617. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1618. self.invert_tool = ToolInvertGerber(self)
  1619. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1620. self.transform_tool = ToolTransform(self)
  1621. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1622. pos=self.ui.menuoptions, separator=True)
  1623. self.properties_tool = Properties(self)
  1624. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1625. pos=self.ui.menuoptions)
  1626. self.pdf_tool = ToolPDF(self)
  1627. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1628. pos=self.ui.menufileimport,
  1629. separator=True)
  1630. self.image_tool = ToolImage(self)
  1631. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1632. pos=self.ui.menufileimport,
  1633. separator=True)
  1634. self.pcb_wizard_tool = PcbWizard(self)
  1635. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1636. pos=self.ui.menufileimport)
  1637. self.log.debug("Tools are installed.")
  1638. def remove_tools(self):
  1639. """
  1640. Will remove all the actions in the Tool menu.
  1641. :return: None
  1642. """
  1643. for act in self.ui.menutool.actions():
  1644. self.ui.menutool.removeAction(act)
  1645. def init_tools(self):
  1646. """
  1647. Initialize the Tool tab in the notebook side of the central widget.
  1648. Remove the actions in the Tools menu.
  1649. Instantiate again the FlatCAM tools (plugins).
  1650. All this is required when changing the layout: standard, compact etc.
  1651. :return: None
  1652. """
  1653. log.debug("init_tools()")
  1654. # delete the data currently in the Tools Tab and the Tab itself
  1655. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1656. if widget is not None:
  1657. widget.deleteLater()
  1658. self.ui.notebook.removeTab(2)
  1659. # rebuild the Tools Tab
  1660. self.ui.tool_tab = QtWidgets.QWidget()
  1661. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1662. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1663. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1664. self.ui.tool_scroll_area = VerticalScrollArea()
  1665. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1666. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1667. # first remove all of them
  1668. self.remove_tools()
  1669. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1670. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1671. '&Command Line\tS')
  1672. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1673. # third install all of them
  1674. try:
  1675. self.install_tools()
  1676. except AttributeError:
  1677. pass
  1678. self.log.debug("Tools are initialized.")
  1679. # def parse_system_fonts(self):
  1680. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1681. # 'params': []})
  1682. def connect_toolbar_signals(self):
  1683. """
  1684. Reconnect the signals to the actions in the toolbar.
  1685. This has to be done each time after the FlatCAM tools are removed/installed.
  1686. :return: None
  1687. """
  1688. # Toolbar
  1689. # File Toolbar Signals
  1690. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1691. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1692. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1693. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1694. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1695. # View Toolbar Signals
  1696. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1697. self.ui.replot_btn.triggered.connect(self.plot_all)
  1698. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1699. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1700. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1701. # Edit Toolbar Signals
  1702. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1703. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1704. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1705. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1706. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1707. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1708. self.ui.delete_btn.triggered.connect(self.on_delete)
  1709. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1710. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1711. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1712. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1713. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1714. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1715. # Scripting Toolbar Signals
  1716. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1717. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1718. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1719. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1720. # Tools Toolbar Signals
  1721. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1722. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1723. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1724. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1725. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1726. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1727. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1728. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1729. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1730. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1731. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1732. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1733. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1734. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1735. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1736. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1737. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1738. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1739. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1740. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1741. def object2editor(self):
  1742. """
  1743. Send the current Geometry or Excellon object (if any) into the it's editor.
  1744. :return: None
  1745. """
  1746. self.defaults.report_usage("object2editor()")
  1747. # disable the objects menu as it may interfere with the Editors
  1748. self.ui.menuobjects.setDisabled(True)
  1749. edited_object = self.collection.get_active()
  1750. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1751. isinstance(edited_object, ExcellonObject):
  1752. pass
  1753. else:
  1754. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1755. return
  1756. if isinstance(edited_object, GeometryObject):
  1757. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1758. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1759. # we set the notebook to hidden
  1760. # self.ui.splitter.setSizes([0, 1])
  1761. if edited_object.multigeo is True:
  1762. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1763. if len(sel_rows) > 1:
  1764. self.inform.emit('[WARNING_NOTCL] %s' %
  1765. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1766. "is not possible.\n"
  1767. "Edit only one geometry at a time."))
  1768. # determine the tool dia of the selected tool
  1769. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1770. # now find the key in the edited_object.tools that has this tooldia
  1771. multi_tool = 1
  1772. for tool in edited_object.tools:
  1773. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1774. multi_tool = tool
  1775. break
  1776. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1777. else:
  1778. self.geo_editor.edit_fcgeometry(edited_object)
  1779. # set call source to the Editor we go into
  1780. self.call_source = 'geo_editor'
  1781. elif isinstance(edited_object, ExcellonObject):
  1782. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1783. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1784. if self.ui.splitter.sizes()[0] == 0:
  1785. self.ui.splitter.setSizes([1, 1])
  1786. self.exc_editor.edit_fcexcellon(edited_object)
  1787. # set call source to the Editor we go into
  1788. self.call_source = 'exc_editor'
  1789. elif isinstance(edited_object, GerberObject):
  1790. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1791. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1792. if self.ui.splitter.sizes()[0] == 0:
  1793. self.ui.splitter.setSizes([1, 1])
  1794. self.grb_editor.edit_fcgerber(edited_object)
  1795. # set call source to the Editor we go into
  1796. self.call_source = 'grb_editor'
  1797. # reset the following variables so the UI is built again after edit
  1798. edited_object.ui_build = False
  1799. edited_object.build_aperture_storage = False
  1800. # make sure that we can't select another object while in Editor Mode:
  1801. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1802. self.ui.project_frame.setDisabled(True)
  1803. # delete any selection shape that might be active as they are not relevant in Editor
  1804. self.delete_selection_shape()
  1805. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1806. self.ui.plot_tab_area.protectTab(0)
  1807. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1808. self.should_we_save = True
  1809. def editor2object(self, cleanup=None):
  1810. """
  1811. Transfers the Geometry or Excellon from it's editor to the current object.
  1812. :return: None
  1813. """
  1814. self.defaults.report_usage("editor2object()")
  1815. # re-enable the objects menu that was disabled on entry in Editor mode
  1816. self.ui.menuobjects.setDisabled(False)
  1817. # do not update a geometry or excellon object unless it comes out of an editor
  1818. if self.call_source != 'app':
  1819. edited_obj = self.collection.get_active()
  1820. if cleanup is None:
  1821. msgbox = QtWidgets.QMessageBox()
  1822. msgbox.setText(_("Do you want to save the edited object?"))
  1823. msgbox.setWindowTitle(_("Close Editor"))
  1824. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1825. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1826. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1827. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1828. msgbox.setDefaultButton(bt_yes)
  1829. msgbox.exec_()
  1830. response = msgbox.clickedButton()
  1831. if response == bt_yes:
  1832. # clean the Tools Tab
  1833. self.ui.tool_scroll_area.takeWidget()
  1834. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1835. self.ui.notebook.setTabText(2, "Tool")
  1836. if isinstance(edited_obj, GeometryObject):
  1837. obj_type = "Geometry"
  1838. if cleanup is None:
  1839. self.geo_editor.update_fcgeometry(edited_obj)
  1840. # self.geo_editor.update_options(edited_obj)
  1841. self.geo_editor.deactivate()
  1842. # restore GUI to the Selected TAB
  1843. # Remove anything else in the GUI
  1844. self.ui.tool_scroll_area.takeWidget()
  1845. # update the geo object options so it is including the bounding box values
  1846. try:
  1847. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1848. edited_obj.options['xmin'] = xmin
  1849. edited_obj.options['ymin'] = ymin
  1850. edited_obj.options['xmax'] = xmax
  1851. edited_obj.options['ymax'] = ymax
  1852. except AttributeError as e:
  1853. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1854. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1855. edited_obj.build_ui()
  1856. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1857. elif isinstance(edited_obj, GerberObject):
  1858. obj_type = "Gerber"
  1859. if cleanup is None:
  1860. self.grb_editor.update_fcgerber()
  1861. self.grb_editor.update_options(edited_obj)
  1862. self.grb_editor.deactivate_grb_editor()
  1863. # delete the old object (the source object) if it was an empty one
  1864. try:
  1865. if len(edited_obj.solid_geometry) == 0:
  1866. old_name = edited_obj.options['name']
  1867. self.collection.set_active(old_name)
  1868. self.collection.delete_active()
  1869. except TypeError:
  1870. # if the solid_geometry is a single Polygon the len() will not work
  1871. # in any case, falling here means that we have something in the solid_geometry, even if only
  1872. # a single Polygon, therefore we pass this
  1873. pass
  1874. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1875. # restore GUI to the Selected TAB
  1876. # Remove anything else in the GUI
  1877. self.ui.selected_scroll_area.takeWidget()
  1878. elif isinstance(edited_obj, ExcellonObject):
  1879. obj_type = "Excellon"
  1880. if cleanup is None:
  1881. self.exc_editor.update_fcexcellon(edited_obj)
  1882. # self.exc_editor.update_options(edited_obj)
  1883. self.exc_editor.deactivate()
  1884. # restore GUI to the Selected TAB
  1885. # Remove anything else in the GUI
  1886. self.ui.tool_scroll_area.takeWidget()
  1887. # delete the old object (the source object) if it was an empty one
  1888. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1889. old_name = edited_obj.options['name']
  1890. self.collection.delete_by_name(name=old_name)
  1891. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1892. else:
  1893. self.inform.emit('[WARNING_NOTCL] %s' %
  1894. _("Select a Gerber, Geometry or Excellon Object to update."))
  1895. return
  1896. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1897. elif response == bt_no:
  1898. # clean the Tools Tab
  1899. self.ui.tool_scroll_area.takeWidget()
  1900. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1901. self.ui.notebook.setTabText(2, "Tool")
  1902. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1903. if isinstance(edited_obj, GeometryObject):
  1904. self.geo_editor.deactivate()
  1905. edited_obj.build_ui()
  1906. elif isinstance(edited_obj, GerberObject):
  1907. self.grb_editor.deactivate_grb_editor()
  1908. edited_obj.build_ui()
  1909. elif isinstance(edited_obj, ExcellonObject):
  1910. self.exc_editor.deactivate()
  1911. edited_obj.build_ui()
  1912. else:
  1913. self.inform.emit('[WARNING_NOTCL] %s' %
  1914. _("Select a Gerber, Geometry or Excellon Object to update."))
  1915. return
  1916. elif response == bt_cancel:
  1917. return
  1918. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1919. # edited_obj.build_ui()
  1920. # Switch notebook to Selected page
  1921. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1922. else:
  1923. if isinstance(edited_obj, GeometryObject):
  1924. self.geo_editor.deactivate()
  1925. elif isinstance(edited_obj, GerberObject):
  1926. self.grb_editor.deactivate_grb_editor()
  1927. elif isinstance(edited_obj, ExcellonObject):
  1928. self.exc_editor.deactivate()
  1929. else:
  1930. self.inform.emit('[WARNING_NOTCL] %s' %
  1931. _("Select a Gerber, Geometry or Excellon Object to update."))
  1932. return
  1933. # if notebook is hidden we show it
  1934. if self.ui.splitter.sizes()[0] == 0:
  1935. self.ui.splitter.setSizes([1, 1])
  1936. # restore the call_source to app
  1937. self.call_source = 'app'
  1938. edited_obj.plot()
  1939. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1940. self.ui.plot_tab_area.protectTab(0)
  1941. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1942. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1943. self.ui.project_frame.setDisabled(False)
  1944. def get_last_folder(self):
  1945. """
  1946. Get the folder path from where the last file was opened.
  1947. :return: String, last opened folder path
  1948. """
  1949. return self.defaults["global_last_folder"]
  1950. def get_last_save_folder(self):
  1951. """
  1952. Get the folder path from where the last file was saved.
  1953. :return: String, last saved folder path
  1954. """
  1955. loc = self.defaults["global_last_save_folder"]
  1956. if loc is None:
  1957. loc = self.defaults["global_last_folder"]
  1958. if loc is None:
  1959. loc = os.path.dirname(__file__)
  1960. return loc
  1961. def info(self, msg):
  1962. """
  1963. Informs the user. Normally on the status bar, optionally
  1964. also on the shell.
  1965. :param msg: Text to write.
  1966. :return: None
  1967. """
  1968. # Type of message in brackets at the beginning of the message.
  1969. match = re.search(r"\[(.*)\](.*)", msg)
  1970. if match:
  1971. level = match.group(1)
  1972. msg_ = match.group(2)
  1973. self.ui.fcinfo.set_status(str(msg_), level=level)
  1974. if level.lower() == "error":
  1975. self.shell_message(msg, error=True, show=True)
  1976. elif level.lower() == "warning":
  1977. self.shell_message(msg, warning=True, show=True)
  1978. elif level.lower() == "error_notcl":
  1979. self.shell_message(msg, error=True, show=False)
  1980. elif level.lower() == "warning_notcl":
  1981. self.shell_message(msg, warning=True, show=False)
  1982. elif level.lower() == "success":
  1983. self.shell_message(msg, success=True, show=False)
  1984. elif level.lower() == "selected":
  1985. self.shell_message(msg, selected=True, show=False)
  1986. else:
  1987. self.shell_message(msg, show=False)
  1988. else:
  1989. self.ui.fcinfo.set_status(str(msg), level="info")
  1990. # make sure that if the message is to clear the infobar with a space
  1991. # is not printed over and over on the shell
  1992. if msg != '':
  1993. self.shell_message(msg)
  1994. def restore_toolbar_view(self):
  1995. """
  1996. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1997. was saved in the defaults dictionary.
  1998. :return: None
  1999. """
  2000. tb = self.defaults["global_toolbar_view"]
  2001. if tb & 1:
  2002. self.ui.toolbarfile.setVisible(True)
  2003. else:
  2004. self.ui.toolbarfile.setVisible(False)
  2005. if tb & 2:
  2006. self.ui.toolbargeo.setVisible(True)
  2007. else:
  2008. self.ui.toolbargeo.setVisible(False)
  2009. if tb & 4:
  2010. self.ui.toolbarview.setVisible(True)
  2011. else:
  2012. self.ui.toolbarview.setVisible(False)
  2013. if tb & 8:
  2014. self.ui.toolbartools.setVisible(True)
  2015. else:
  2016. self.ui.toolbartools.setVisible(False)
  2017. if tb & 16:
  2018. self.ui.exc_edit_toolbar.setVisible(True)
  2019. else:
  2020. self.ui.exc_edit_toolbar.setVisible(False)
  2021. if tb & 32:
  2022. self.ui.geo_edit_toolbar.setVisible(True)
  2023. else:
  2024. self.ui.geo_edit_toolbar.setVisible(False)
  2025. if tb & 64:
  2026. self.ui.grb_edit_toolbar.setVisible(True)
  2027. else:
  2028. self.ui.grb_edit_toolbar.setVisible(False)
  2029. if tb & 128:
  2030. self.ui.snap_toolbar.setVisible(True)
  2031. else:
  2032. self.ui.snap_toolbar.setVisible(False)
  2033. if tb & 256:
  2034. self.ui.toolbarshell.setVisible(True)
  2035. else:
  2036. self.ui.toolbarshell.setVisible(False)
  2037. def on_import_preferences(self):
  2038. """
  2039. Loads the application default settings from a saved file into
  2040. ``self.defaults`` dictionary.
  2041. :return: None
  2042. """
  2043. self.defaults.report_usage("on_import_preferences")
  2044. App.log.debug("App.on_import_preferences()")
  2045. # Show file chooser
  2046. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2047. try:
  2048. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2049. directory=self.data_path,
  2050. filter=filter_)
  2051. except TypeError:
  2052. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2053. filter=filter_)
  2054. filename = str(filename)
  2055. if filename == "":
  2056. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2057. return
  2058. # Load in the defaults from the chosen file
  2059. self.defaults.load(filename=filename)
  2060. self.preferencesUiManager.on_preferences_edited()
  2061. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2062. def on_export_preferences(self):
  2063. """
  2064. Save the defaults dictionary to a file.
  2065. :return: None
  2066. """
  2067. self.defaults.report_usage("on_export_preferences")
  2068. App.log.debug("on_export_preferences()")
  2069. # defaults_file_content = None
  2070. # Show file chooser
  2071. date = str(datetime.today()).rpartition('.')[0]
  2072. date = ''.join(c for c in date if c not in ':-')
  2073. date = date.replace(' ', '_')
  2074. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2075. try:
  2076. filename, _f = FCFileSaveDialog.get_saved_filename(
  2077. caption=_("Export FlatCAM Preferences"),
  2078. directory=self.data_path + '/preferences_' + date,
  2079. filter=filter__
  2080. )
  2081. except TypeError:
  2082. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2083. filename = str(filename)
  2084. if filename == "":
  2085. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2086. return
  2087. # Update options
  2088. self.preferencesUiManager.defaults_read_form()
  2089. self.defaults.propagate_defaults()
  2090. # Save update options
  2091. try:
  2092. self.defaults.write(filename=filename)
  2093. except Exception:
  2094. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2095. return
  2096. if self.defaults["global_open_style"] is False:
  2097. self.file_opened.emit("preferences", filename)
  2098. self.file_saved.emit("preferences", filename)
  2099. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2100. def save_to_file(self, content_to_save, txt_content):
  2101. """
  2102. Save something to a file.
  2103. :return: None
  2104. """
  2105. self.defaults.report_usage("save_to_file")
  2106. App.log.debug("save_to_file()")
  2107. self.date = str(datetime.today()).rpartition('.')[0]
  2108. self.date = ''.join(c for c in self.date if c not in ':-')
  2109. self.date = self.date.replace(' ', '_')
  2110. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2111. path_to_save = self.defaults["global_last_save_folder"] if \
  2112. self.defaults["global_last_save_folder"] is not None else self.data_path
  2113. try:
  2114. filename, _f = FCFileSaveDialog.get_saved_filename(
  2115. caption=_("Save to file"),
  2116. directory=path_to_save + '/file_' + self.date,
  2117. filter=filter__
  2118. )
  2119. except TypeError:
  2120. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2121. filename = str(filename)
  2122. if filename == "":
  2123. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2124. return
  2125. else:
  2126. try:
  2127. with open(filename, 'w') as f:
  2128. ___ = f.read()
  2129. except PermissionError:
  2130. self.inform.emit('[WARNING] %s' %
  2131. _("Permission denied, saving not possible.\n"
  2132. "Most likely another app is holding the file open and not accessible."))
  2133. return
  2134. except IOError:
  2135. App.log.debug('Creating a new file ...')
  2136. f = open(filename, 'w')
  2137. f.close()
  2138. except Exception:
  2139. e = sys.exc_info()[0]
  2140. App.log.error("Could not load the file.")
  2141. App.log.error(str(e))
  2142. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2143. return
  2144. # Save content
  2145. if filename.rpartition('.')[2].lower() == 'html':
  2146. file_content = content_to_save
  2147. else:
  2148. file_content = txt_content
  2149. try:
  2150. with open(filename, "w") as f:
  2151. f.write(file_content)
  2152. except Exception:
  2153. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2154. return
  2155. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2156. def save_geometry(self, x, y, width, height, notebook_width):
  2157. """
  2158. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2159. launch of the application.
  2160. :param x: X position of the main window
  2161. :param y: Y position of the main window
  2162. :param width: width of the main window
  2163. :param height: height of the main window
  2164. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2165. :return: None
  2166. """
  2167. self.defaults["global_def_win_x"] = x
  2168. self.defaults["global_def_win_y"] = y
  2169. self.defaults["global_def_win_w"] = width
  2170. self.defaults["global_def_win_h"] = height
  2171. self.defaults["global_def_notebook_width"] = notebook_width
  2172. self.preferencesUiManager.save_defaults()
  2173. def restore_main_win_geom(self):
  2174. try:
  2175. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2176. self.defaults["global_def_win_y"],
  2177. self.defaults["global_def_win_w"],
  2178. self.defaults["global_def_win_h"])
  2179. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2180. except KeyError as e:
  2181. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2182. def message_dialog(self, title, message, kind="info"):
  2183. """
  2184. Builds and show a custom QMessageBox to be used in FlatCAM.
  2185. :param title: title of the QMessageBox
  2186. :param message: message to be displayed
  2187. :param kind: type of QMessageBox; will display a specific icon.
  2188. :return:
  2189. """
  2190. icon = {"info": QtWidgets.QMessageBox.Information,
  2191. "warning": QtWidgets.QMessageBox.Warning,
  2192. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2193. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2194. dlg.setText(message)
  2195. dlg.exec_()
  2196. def register_recent(self, kind, filename):
  2197. """
  2198. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2199. dictionary.
  2200. :param kind: type of file that was opened
  2201. :param filename: the path and file name for the file that was opened
  2202. :return:
  2203. """
  2204. self.log.debug("register_recent()")
  2205. self.log.debug(" %s" % kind)
  2206. self.log.debug(" %s" % filename)
  2207. record = {'kind': str(kind), 'filename': str(filename)}
  2208. if record in self.recent:
  2209. return
  2210. if record in self.recent_projects:
  2211. return
  2212. if record['kind'] == 'project':
  2213. self.recent_projects.insert(0, record)
  2214. else:
  2215. self.recent.insert(0, record)
  2216. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2217. self.recent.pop()
  2218. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2219. self.recent_projects.pop()
  2220. try:
  2221. f = open(self.data_path + '/recent.json', 'w')
  2222. except IOError:
  2223. App.log.error("Failed to open recent items file for writing.")
  2224. self.inform.emit('[ERROR_NOTCL] %s' %
  2225. _('Failed to open recent files file for writing.'))
  2226. return
  2227. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2228. f.close()
  2229. try:
  2230. fp = open(self.data_path + '/recent_projects.json', 'w')
  2231. except IOError:
  2232. App.log.error("Failed to open recent items file for writing.")
  2233. self.inform.emit('[ERROR_NOTCL] %s' %
  2234. _('Failed to open recent projects file for writing.'))
  2235. return
  2236. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2237. fp.close()
  2238. # Re-build the recent items menu
  2239. self.setup_recent_items()
  2240. def new_object(self, kind, name, initialize, plot=True, autoselected=True):
  2241. """
  2242. Creates a new specialized FlatCAMObj and attaches it to the application,
  2243. this is, updates the GUI accordingly, any other records and plots it.
  2244. This method is thread-safe.
  2245. Notes:
  2246. * If the name is in use, the self.collection will modify it
  2247. when appending it to the collection. There is no need to handle
  2248. name conflicts here.
  2249. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2250. :type kind: str
  2251. :param name: Name for the object.
  2252. :type name: str
  2253. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2254. The function is called with 2 parameters: the new object and the App instance.
  2255. :type initialize: function
  2256. :param plot: If to plot the resulting object
  2257. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2258. self.collection
  2259. :return: None
  2260. :rtype: None
  2261. """
  2262. App.log.debug("new_object()")
  2263. obj_plot = plot
  2264. obj_autoselected = autoselected
  2265. t0 = time.time() # Debug
  2266. # ## Create object
  2267. classdict = {
  2268. "gerber": GerberObject,
  2269. "excellon": ExcellonObject,
  2270. "cncjob": CNCJobObject,
  2271. "geometry": GeometryObject,
  2272. "script": ScriptObject,
  2273. "document": DocumentObject
  2274. }
  2275. App.log.debug("Calling object constructor...")
  2276. # Object creation/instantiation
  2277. obj = classdict[kind](name)
  2278. obj.units = self.options["units"]
  2279. # IMPORTANT
  2280. # The key names in defaults and options dictionary's are not random:
  2281. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2282. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2283. # copied to self.options. After that, below, depending on the type of
  2284. # object that is created, it will strip the name of the object and the underline (if the original key was
  2285. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2286. # "toolchange"
  2287. for option in self.options:
  2288. if option.find(kind + "_") == 0:
  2289. oname = option[len(kind) + 1:]
  2290. obj.options[oname] = self.options[option]
  2291. obj.isHovering = False
  2292. obj.notHovering = True
  2293. # Initialize as per user request
  2294. # User must take care to implement initialize
  2295. # in a thread-safe way as is is likely that we
  2296. # have been invoked in a separate thread.
  2297. t1 = time.time()
  2298. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2299. try:
  2300. return_value = initialize(obj, self)
  2301. except Exception as e:
  2302. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2303. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2304. msg += traceback.format_exc()
  2305. self.inform.emit(msg)
  2306. return "fail"
  2307. t2 = time.time()
  2308. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2309. if return_value == 'fail':
  2310. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2311. return "fail"
  2312. # Check units and convert if necessary
  2313. # This condition CAN be true because initialize() can change obj.units
  2314. if self.options["units"].upper() != obj.units.upper():
  2315. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2316. obj.convert_units(self.options["units"])
  2317. t3 = time.time()
  2318. self.log.debug("%f seconds converting units." % (t3 - t2))
  2319. # Create the bounding box for the object and then add the results to the obj.options
  2320. # But not for Scripts or for Documents
  2321. if kind != 'document' and kind != 'script':
  2322. try:
  2323. xmin, ymin, xmax, ymax = obj.bounds()
  2324. obj.options['xmin'] = xmin
  2325. obj.options['ymin'] = ymin
  2326. obj.options['xmax'] = xmax
  2327. obj.options['ymax'] = ymax
  2328. except Exception as e:
  2329. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2330. return "fail"
  2331. try:
  2332. if kind == 'excellon':
  2333. obj.fill_color = self.defaults["excellon_plot_fill"]
  2334. obj.outline_color = self.defaults["excellon_plot_line"]
  2335. if kind == 'gerber':
  2336. obj.fill_color = self.defaults["gerber_plot_fill"]
  2337. obj.outline_color = self.defaults["gerber_plot_line"]
  2338. except Exception as e:
  2339. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2340. # update the KeyWords list with the name of the file
  2341. self.myKeywords.append(obj.options['name'])
  2342. log.debug("Moving new object back to main thread.")
  2343. # Move the object to the main thread and let the app know that it is available.
  2344. obj.moveToThread(self.main_thread)
  2345. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2346. return obj
  2347. def new_excellon_object(self):
  2348. """
  2349. Creates a new, blank Excellon object.
  2350. :return: None
  2351. """
  2352. self.defaults.report_usage("new_excellon_object()")
  2353. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2354. def new_geometry_object(self):
  2355. """
  2356. Creates a new, blank and single-tool Geometry object.
  2357. :return: None
  2358. """
  2359. self.defaults.report_usage("new_geometry_object()")
  2360. def initialize(obj, app):
  2361. obj.multitool = False
  2362. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2363. def new_gerber_object(self):
  2364. """
  2365. Creates a new, blank Gerber object.
  2366. :return: None
  2367. """
  2368. self.defaults.report_usage("new_gerber_object()")
  2369. def initialize(grb_obj, app):
  2370. grb_obj.multitool = False
  2371. grb_obj.source_file = []
  2372. grb_obj.multigeo = False
  2373. grb_obj.follow = False
  2374. grb_obj.apertures = {}
  2375. grb_obj.solid_geometry = []
  2376. try:
  2377. grb_obj.options['xmin'] = 0
  2378. grb_obj.options['ymin'] = 0
  2379. grb_obj.options['xmax'] = 0
  2380. grb_obj.options['ymax'] = 0
  2381. except KeyError:
  2382. pass
  2383. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2384. def new_script_object(self):
  2385. """
  2386. Creates a new, blank TCL Script object.
  2387. :return: None
  2388. """
  2389. self.defaults.report_usage("new_script_object()")
  2390. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2391. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2392. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2393. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2394. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2395. # "ListSys, MillDrills,\n" \
  2396. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2397. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2398. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2399. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2400. # "# SubtractRectangle, Version, WriteGCode\n"
  2401. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2402. '# %s:\n' % _('TCL Tutorial is here') + \
  2403. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2404. '# %s:\n' % _("FlatCAM commands list")
  2405. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2406. "(displayed in Tcl Shell).")
  2407. def initialize(obj, app):
  2408. obj.source_file = deepcopy(new_source_file)
  2409. outname = 'new_script'
  2410. self.new_object('script', outname, initialize, plot=False)
  2411. def new_document_object(self):
  2412. """
  2413. Creates a new, blank Document object.
  2414. :return: None
  2415. """
  2416. self.defaults.report_usage("new_document_object()")
  2417. def initialize(obj, app):
  2418. obj.source_file = ""
  2419. self.new_object('document', 'new_document', initialize, plot=False)
  2420. def on_object_created(self, obj, plot, auto_select):
  2421. """
  2422. Event callback for object creation.
  2423. It will add the new object to the collection. After that it will plot the object in a threaded way
  2424. :param obj: The newly created FlatCAM object.
  2425. :param plot: if the newly create object t obe plotted
  2426. :param auto_select: if the newly created object to be autoselected after creation
  2427. :return: None
  2428. """
  2429. t0 = time.time() # DEBUG
  2430. self.log.debug("on_object_created()")
  2431. # The Collection might change the name if there is a collision
  2432. self.collection.append(obj)
  2433. # after adding the object to the collection always update the list of objects that are in the collection
  2434. self.all_objects_list = self.collection.get_list()
  2435. # self.inform.emit('[selected] %s created & selected: %s' %
  2436. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2437. if obj.kind == 'gerber':
  2438. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2439. kind=obj.kind.capitalize(),
  2440. color='green',
  2441. name=str(obj.options['name']), tx=_("created/selected"))
  2442. )
  2443. elif obj.kind == 'excellon':
  2444. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2445. kind=obj.kind.capitalize(),
  2446. color='brown',
  2447. name=str(obj.options['name']), tx=_("created/selected"))
  2448. )
  2449. elif obj.kind == 'cncjob':
  2450. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2451. kind=obj.kind.capitalize(),
  2452. color='blue',
  2453. name=str(obj.options['name']), tx=_("created/selected"))
  2454. )
  2455. elif obj.kind == 'geometry':
  2456. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2457. kind=obj.kind.capitalize(),
  2458. color='red',
  2459. name=str(obj.options['name']), tx=_("created/selected"))
  2460. )
  2461. elif obj.kind == 'script':
  2462. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2463. kind=obj.kind.capitalize(),
  2464. color='orange',
  2465. name=str(obj.options['name']), tx=_("created/selected"))
  2466. )
  2467. elif obj.kind == 'document':
  2468. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2469. kind=obj.kind.capitalize(),
  2470. color='darkCyan',
  2471. name=str(obj.options['name']), tx=_("created/selected"))
  2472. )
  2473. # update the SHELL auto-completer model with the name of the new object
  2474. self.shell._edit.set_model_data(self.myKeywords)
  2475. if auto_select:
  2476. # select the just opened object but deselect the previous ones
  2477. self.collection.set_all_inactive()
  2478. self.collection.set_active(obj.options["name"])
  2479. else:
  2480. self.collection.set_all_inactive()
  2481. # here it is done the object plotting
  2482. def worker_task(t_obj):
  2483. with self.proc_container.new(_("Plotting")):
  2484. if isinstance(t_obj, CNCJobObject):
  2485. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2486. else:
  2487. t_obj.plot()
  2488. t1 = time.time() # DEBUG
  2489. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2490. self.object_plotted.emit(t_obj)
  2491. # Send to worker
  2492. # self.worker.add_task(worker_task, [self])
  2493. if plot is True:
  2494. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2495. def on_object_changed(self, obj):
  2496. """
  2497. Called whenever the geometry of the object was changed in some way.
  2498. This require the update of it's bounding values so it can be the selected on canvas.
  2499. Update the bounding box data from obj.options
  2500. :param obj: the object that was changed
  2501. :return: None
  2502. """
  2503. xmin, ymin, xmax, ymax = obj.bounds()
  2504. obj.options['xmin'] = xmin
  2505. obj.options['ymin'] = ymin
  2506. obj.options['xmax'] = xmax
  2507. obj.options['ymax'] = ymax
  2508. log.debug("Object changed, updating the bounding box data on self.options")
  2509. # delete the old selection shape
  2510. self.delete_selection_shape()
  2511. self.should_we_save = True
  2512. def on_object_plotted(self):
  2513. """
  2514. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2515. :return: None
  2516. """
  2517. self.on_zoom_fit(None)
  2518. def on_about(self):
  2519. """
  2520. Displays the "about" dialog found in the Menu --> Help.
  2521. :return: None
  2522. """
  2523. self.defaults.report_usage("on_about")
  2524. version = self.version
  2525. version_date = self.version_date
  2526. beta = self.beta
  2527. class AboutDialog(QtWidgets.QDialog):
  2528. def __init__(self, app, parent=None):
  2529. QtWidgets.QDialog.__init__(self, parent)
  2530. self.app = app
  2531. # Icon and title
  2532. self.setWindowIcon(parent.app_icon)
  2533. self.setWindowTitle(_("About FlatCAM"))
  2534. self.resize(600, 200)
  2535. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2536. # self.setStyleSheet(
  2537. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2538. # "background-attachment: fixed"
  2539. # )
  2540. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2541. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2542. # palette = QtGui.QPalette()
  2543. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2544. # self.setPalette(palette)
  2545. logo = QtWidgets.QLabel()
  2546. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2547. title = QtWidgets.QLabel(
  2548. "<font size=8><B>FlatCAM</B></font><BR>"
  2549. "{title}<BR>"
  2550. "<BR>"
  2551. "<BR>"
  2552. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2553. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2554. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2555. "<B>{issue}</B></a><BR>".format(
  2556. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2557. devel=_("Development"),
  2558. down=_("DOWNLOAD"),
  2559. issue=_("Issue tracker"))
  2560. )
  2561. title.setOpenExternalLinks(True)
  2562. closebtn = QtWidgets.QPushButton(_("Close"))
  2563. tab_widget = QtWidgets.QTabWidget()
  2564. description_label = QtWidgets.QLabel(
  2565. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2566. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2567. version=version,
  2568. beta=('BETA' if beta else ''),
  2569. date=version_date,
  2570. arch=platform.architecture()[0])
  2571. )
  2572. description_label.setOpenExternalLinks(True)
  2573. lic_lbl_header = QtWidgets.QLabel(
  2574. '%s:<br>%s<br>' % (
  2575. _('Licensed under the MIT license'),
  2576. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2577. "http://www.opensource.org/licenses/mit-license.php</a>"
  2578. )
  2579. )
  2580. lic_lbl_header.setOpenExternalLinks(True)
  2581. lic_lbl_body = QtWidgets.QLabel(
  2582. _(
  2583. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2584. 'of this software and associated documentation files (the "Software"), to deal\n'
  2585. 'in the Software without restriction, including without limitation the rights\n'
  2586. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2587. 'copies of the Software, and to permit persons to whom the Software is\n'
  2588. 'furnished to do so, subject to the following conditions:\n\n'
  2589. 'The above copyright notice and this permission notice shall be included in\n'
  2590. 'all copies or substantial portions of the Software.\n\n'
  2591. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2592. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2593. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2594. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2595. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2596. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2597. 'THE SOFTWARE.'
  2598. )
  2599. )
  2600. attributions_label = QtWidgets.QLabel(
  2601. _(
  2602. 'Some of the icons used are from the following sources:<br>'
  2603. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2604. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2605. 'title="Flaticon">www.flaticon.com</a></div>'
  2606. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2607. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2608. )
  2609. )
  2610. attributions_label.setOpenExternalLinks(True)
  2611. # layouts
  2612. layout1 = QtWidgets.QVBoxLayout()
  2613. layout1_1 = QtWidgets.QHBoxLayout()
  2614. layout1_2 = QtWidgets.QHBoxLayout()
  2615. layout2 = QtWidgets.QHBoxLayout()
  2616. layout3 = QtWidgets.QHBoxLayout()
  2617. self.setLayout(layout1)
  2618. layout1.addLayout(layout1_1)
  2619. layout1.addLayout(layout1_2)
  2620. layout1.addLayout(layout2)
  2621. layout1.addLayout(layout3)
  2622. layout1_1.addStretch()
  2623. layout1_1.addWidget(description_label)
  2624. layout1_2.addWidget(tab_widget)
  2625. self.splash_tab = QtWidgets.QWidget()
  2626. self.splash_tab.setObjectName("splash_about")
  2627. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2628. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2629. tab_widget.addTab(self.splash_tab, _("Splash"))
  2630. self.programmmers_tab = QtWidgets.QWidget()
  2631. self.programmmers_tab.setObjectName("programmers_about")
  2632. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2633. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2634. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2635. self.translators_tab = QtWidgets.QWidget()
  2636. self.translators_tab.setObjectName("translators_about")
  2637. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2638. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2639. tab_widget.addTab(self.translators_tab, _("Translators"))
  2640. self.license_tab = QtWidgets.QWidget()
  2641. self.license_tab.setObjectName("license_about")
  2642. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2643. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2644. tab_widget.addTab(self.license_tab, _("License"))
  2645. self.attributions_tab = QtWidgets.QWidget()
  2646. self.attributions_tab.setObjectName("attributions_about")
  2647. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2648. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2649. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2650. self.splash_tab_layout.addWidget(logo, stretch=0)
  2651. self.splash_tab_layout.addWidget(title, stretch=1)
  2652. pal = QtGui.QPalette()
  2653. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2654. self.prog_grid_lay = QtWidgets.QGridLayout()
  2655. self.prog_grid_lay.setHorizontalSpacing(20)
  2656. self.prog_grid_lay.setColumnStretch(0, 0)
  2657. self.prog_grid_lay.setColumnStretch(2, 1)
  2658. prog_widget = QtWidgets.QWidget()
  2659. prog_widget.setLayout(self.prog_grid_lay)
  2660. prog_scroll = QtWidgets.QScrollArea()
  2661. prog_scroll.setWidget(prog_widget)
  2662. prog_scroll.setWidgetResizable(True)
  2663. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2664. prog_scroll.setPalette(pal)
  2665. self.programmmers_tab_layout.addWidget(prog_scroll)
  2666. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2704. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2705. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2706. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2707. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2708. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2709. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2710. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2711. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2712. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2713. self.translator_grid_lay = QtWidgets.QGridLayout()
  2714. self.translator_grid_lay.setColumnStretch(0, 0)
  2715. self.translator_grid_lay.setColumnStretch(1, 0)
  2716. self.translator_grid_lay.setColumnStretch(2, 1)
  2717. self.translator_grid_lay.setColumnStretch(3, 0)
  2718. # trans_widget = QtWidgets.QWidget()
  2719. # trans_widget.setLayout(self.translator_grid_lay)
  2720. # self.translators_tab_layout.addWidget(trans_widget)
  2721. # self.translators_tab_layout.addStretch()
  2722. trans_widget = QtWidgets.QWidget()
  2723. trans_widget.setLayout(self.translator_grid_lay)
  2724. trans_scroll = QtWidgets.QScrollArea()
  2725. trans_scroll.setWidget(trans_widget)
  2726. trans_scroll.setWidgetResizable(True)
  2727. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2728. trans_scroll.setPalette(pal)
  2729. self.translators_tab_layout.addWidget(trans_scroll)
  2730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2750. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2751. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2752. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2753. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2754. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2755. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2756. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2757. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2758. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2759. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2760. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2761. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2762. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2763. self.translator_grid_lay.setColumnStretch(0, 0)
  2764. self.translators_tab_layout.addStretch()
  2765. self.license_tab_layout.addWidget(lic_lbl_header)
  2766. self.license_tab_layout.addWidget(lic_lbl_body)
  2767. self.license_tab_layout.addStretch()
  2768. self.attributions_tab_layout.addWidget(attributions_label)
  2769. self.attributions_tab_layout.addStretch()
  2770. layout3.addStretch()
  2771. layout3.addWidget(closebtn)
  2772. closebtn.clicked.connect(self.accept)
  2773. AboutDialog(app=self, parent=self.ui).exec_()
  2774. def install_bookmarks(self, book_dict=None):
  2775. """
  2776. Install the bookmarks actions in the Help menu -> Bookmarks
  2777. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2778. :return: None
  2779. """
  2780. if book_dict is None:
  2781. self.defaults["global_bookmarks"].update(
  2782. {
  2783. '1': ['FlatCAM', "http://flatcam.org"],
  2784. '2': ['Backup Site', ""]
  2785. }
  2786. )
  2787. else:
  2788. self.defaults["global_bookmarks"].clear()
  2789. self.defaults["global_bookmarks"].update(book_dict)
  2790. # first try to disconnect if somehow they get connected from elsewhere
  2791. for act in self.ui.menuhelp_bookmarks.actions():
  2792. try:
  2793. act.triggered.disconnect()
  2794. except TypeError:
  2795. pass
  2796. # clear all actions except the last one who is the Bookmark manager
  2797. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2798. pass
  2799. else:
  2800. self.ui.menuhelp_bookmarks.removeAction(act)
  2801. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2802. if self.defaults["global_bookmarks"]:
  2803. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2804. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2805. # the JSON is first making the keys as strings (therefore I have to use strings too
  2806. # or do the conversion :(
  2807. # )
  2808. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2809. # the '10' entry jsut after '1' therefore ordering as strings
  2810. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2811. key=lambda x: int(x[0]))
  2812. for entry, bookmark in sorted_bookmarks:
  2813. title = bookmark[0]
  2814. weblink = bookmark[1]
  2815. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2816. act.setText(title)
  2817. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2818. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2819. if title == 'Backup Site' and weblink == "":
  2820. act.triggered.connect(self.on_backup_site)
  2821. else:
  2822. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2823. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2824. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2825. def on_bookmarks_manager(self):
  2826. """
  2827. Adds the bookmark manager in a Tab in Plot Area
  2828. :return:
  2829. """
  2830. for idx in range(self.ui.plot_tab_area.count()):
  2831. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2832. # there can be only one instance of Bookmark Manager at one time
  2833. return
  2834. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2835. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2836. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2837. # add the tab if it was closed
  2838. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2839. # delete the absolute and relative position and messages in the infobar
  2840. self.ui.position_label.setText("")
  2841. self.ui.rel_position_label.setText("")
  2842. # Switch plot_area to preferences page
  2843. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2844. def on_backup_site(self):
  2845. msgbox = QtWidgets.QMessageBox()
  2846. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2847. "1. FlatCAM.org website is down\n"
  2848. "2. Someone forked FlatCAM project and wants to point\n"
  2849. "to his own website\n\n"
  2850. "If you can't get any informations about FlatCAM beta\n"
  2851. "use the YouTube channel link from the Help menu."))
  2852. msgbox.setWindowTitle(_("Alternative website"))
  2853. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2854. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2855. msgbox.setDefaultButton(bt_yes)
  2856. msgbox.exec_()
  2857. # response = msgbox.clickedButton()
  2858. def on_file_savedefaults(self):
  2859. """
  2860. Callback for menu item File->Save Defaults. Saves application default options
  2861. ``self.defaults`` to current_defaults.FlatConfig.
  2862. :return: None
  2863. """
  2864. self.preferencesUiManager.save_defaults()
  2865. def final_save(self):
  2866. """
  2867. Callback for doing a preferences save to file whenever the application is about to quit.
  2868. If the project has changes, it will ask the user to save the project.
  2869. :return: None
  2870. """
  2871. if self.save_in_progress:
  2872. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2873. return
  2874. if self.should_we_save and self.collection.get_list():
  2875. msgbox = QtWidgets.QMessageBox()
  2876. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2877. "\n"
  2878. "Do you want to Save the project?"))
  2879. msgbox.setWindowTitle(_("Save changes"))
  2880. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2881. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2882. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2883. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2884. msgbox.setDefaultButton(bt_yes)
  2885. msgbox.exec_()
  2886. response = msgbox.clickedButton()
  2887. if response == bt_yes:
  2888. try:
  2889. self.trayIcon.hide()
  2890. except Exception:
  2891. pass
  2892. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2893. elif response == bt_no:
  2894. try:
  2895. self.trayIcon.hide()
  2896. except Exception:
  2897. pass
  2898. self.quit_application()
  2899. elif response == bt_cancel:
  2900. return
  2901. else:
  2902. try:
  2903. self.trayIcon.hide()
  2904. except Exception:
  2905. pass
  2906. self.quit_application()
  2907. def quit_application(self):
  2908. """
  2909. Called (as a pyslot or not) when the application is quit.
  2910. :return: None
  2911. """
  2912. self.preferencesUiManager.save_defaults(silent=True)
  2913. log.debug("App.quit_application() --> App Defaults saved.")
  2914. if self.cmd_line_headless != 1:
  2915. # save app state to file
  2916. stgs = QSettings("Open Source", "FlatCAM")
  2917. stgs.setValue('saved_gui_state', self.ui.saveState())
  2918. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2919. stgs.setValue(
  2920. 'language',
  2921. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2922. )
  2923. stgs.setValue(
  2924. 'notebook_font_size',
  2925. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2926. )
  2927. stgs.setValue(
  2928. 'axis_font_size',
  2929. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2930. )
  2931. stgs.setValue(
  2932. 'textbox_font_size',
  2933. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2934. )
  2935. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2936. stgs.setValue(
  2937. 'machinist',
  2938. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2939. )
  2940. # This will write the setting to the platform specific storage.
  2941. del stgs
  2942. log.debug("App.quit_application() --> App UI state saved.")
  2943. # try to quit the Socket opened by ArgsThread class
  2944. try:
  2945. self.new_launch.stop.emit()
  2946. except Exception as err:
  2947. log.debug("App.quit_application() --> %s" % str(err))
  2948. # try to quit the QThread that run ArgsThread class
  2949. try:
  2950. self.th.quit()
  2951. except Exception as e:
  2952. log.debug("App.quit_application() --> %s" % str(e))
  2953. # terminate workers
  2954. self.workers.__del__()
  2955. # quit app by signalling for self.kill_app() method
  2956. # self.close_app_signal.emit()
  2957. QtWidgets.qApp.quit()
  2958. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2959. # we use the following command
  2960. minor_v = sys.version_info.minor
  2961. if minor_v < 8:
  2962. sys.exit(0)
  2963. else:
  2964. os._exit(0) # fix to work with Python 3.8
  2965. @staticmethod
  2966. def kill_app():
  2967. QtWidgets.qApp.quit()
  2968. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2969. # we use the following command
  2970. sys.exit(0)
  2971. def on_portable_checked(self, state):
  2972. """
  2973. Callback called when the checkbox in Preferences GUI is checked.
  2974. It will set the application as portable by creating the preferences and recent files in the
  2975. 'config' folder found in the FlatCAM installation folder.
  2976. :param state: boolean, the state of the checkbox when clicked/checked
  2977. :return:
  2978. """
  2979. line_no = 0
  2980. data = None
  2981. if sys.platform != 'win32':
  2982. # this won't work in Linux or MacOS
  2983. return
  2984. # test if the app was frozen and choose the path for the configuration file
  2985. if getattr(sys, "frozen", False) is True:
  2986. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2987. else:
  2988. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2989. config_file = current_data_path + '\\configuration.txt'
  2990. try:
  2991. with open(config_file, 'r') as f:
  2992. try:
  2993. data = f.readlines()
  2994. except Exception as e:
  2995. log.debug('App.__init__() -->%s' % str(e))
  2996. return
  2997. except FileNotFoundError:
  2998. pass
  2999. for line in data:
  3000. line = line.strip('\n')
  3001. param = str(line).rpartition('=')
  3002. if param[0] == 'portable':
  3003. break
  3004. line_no += 1
  3005. if state:
  3006. data[line_no] = 'portable=True\n'
  3007. # create the new defauults files
  3008. # create current_defaults.FlatConfig file if there is none
  3009. try:
  3010. f = open(current_data_path + '/current_defaults.FlatConfig')
  3011. f.close()
  3012. except IOError:
  3013. App.log.debug('Creating empty current_defaults.FlatConfig')
  3014. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3015. json.dump({}, f)
  3016. f.close()
  3017. # create factory_defaults.FlatConfig file if there is none
  3018. try:
  3019. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3020. f.close()
  3021. except IOError:
  3022. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3023. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3024. json.dump({}, f)
  3025. f.close()
  3026. try:
  3027. f = open(current_data_path + '/recent.json')
  3028. f.close()
  3029. except IOError:
  3030. App.log.debug('Creating empty recent.json')
  3031. f = open(current_data_path + '/recent.json', 'w')
  3032. json.dump([], f)
  3033. f.close()
  3034. try:
  3035. fp = open(current_data_path + '/recent_projects.json')
  3036. fp.close()
  3037. except IOError:
  3038. App.log.debug('Creating empty recent_projects.json')
  3039. fp = open(current_data_path + '/recent_projects.json', 'w')
  3040. json.dump([], fp)
  3041. fp.close()
  3042. # save the current defaults to the new defaults file
  3043. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3044. else:
  3045. data[line_no] = 'portable=False\n'
  3046. with open(config_file, 'w') as f:
  3047. f.writelines(data)
  3048. def on_register_files(self, obj_type=None):
  3049. """
  3050. Called whenever there is a need to register file extensions with FlatCAM.
  3051. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3052. :param obj_type: the type of object to be register for.
  3053. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3054. :return: None
  3055. """
  3056. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3057. new_reg_path = 'Software\\Classes\\'
  3058. # find if the current user is admin
  3059. try:
  3060. is_admin = os.getuid() == 0
  3061. except AttributeError:
  3062. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3063. if is_admin is True:
  3064. root_path = winreg.HKEY_LOCAL_MACHINE
  3065. else:
  3066. root_path = winreg.HKEY_CURRENT_USER
  3067. # create the keys
  3068. def set_reg(name, root_pth, new_reg_path, value):
  3069. try:
  3070. winreg.CreateKey(root_pth, new_reg_path)
  3071. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3072. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3073. return True
  3074. except WindowsError:
  3075. return False
  3076. # delete key in registry
  3077. def delete_reg(root_pth, reg_path, key_to_del):
  3078. key_to_del_path = reg_path + key_to_del
  3079. try:
  3080. winreg.DeleteKey(root_pth, key_to_del_path)
  3081. return True
  3082. except WindowsError:
  3083. return False
  3084. if obj_type is None or obj_type == 'excellon':
  3085. exc_list = \
  3086. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3087. exc_list = [x for x in exc_list if x != '']
  3088. # register all keys in the Preferences window
  3089. for ext in exc_list:
  3090. new_k = new_reg_path + '.%s' % ext
  3091. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3092. # and unregister those that are no longer in the Preferences windows but are in the file
  3093. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3094. if ext not in exc_list:
  3095. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3096. # now write the updated extensions to the self.defaults
  3097. # new_ext = ''
  3098. # for ext in exc_list:
  3099. # new_ext = new_ext + ext + ', '
  3100. # self.defaults["fa_excellon"] = new_ext
  3101. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3102. if obj_type is None or obj_type == 'gcode':
  3103. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3104. gco_list = [x for x in gco_list if x != '']
  3105. # register all keys in the Preferences window
  3106. for ext in gco_list:
  3107. new_k = new_reg_path + '.%s' % ext
  3108. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3109. # and unregister those that are no longer in the Preferences windows but are in the file
  3110. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3111. if ext not in gco_list:
  3112. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3113. # now write the updated extensions to the self.defaults
  3114. # new_ext = ''
  3115. # for ext in gco_list:
  3116. # new_ext = new_ext + ext + ', '
  3117. # self.defaults["fa_gcode"] = new_ext
  3118. self.inform.emit('[success] %s' %
  3119. _("Selected GCode file extensions registered with FlatCAM."))
  3120. if obj_type is None or obj_type == 'gerber':
  3121. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3122. grb_list = [x for x in grb_list if x != '']
  3123. # register all keys in the Preferences window
  3124. for ext in grb_list:
  3125. new_k = new_reg_path + '.%s' % ext
  3126. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3127. # and unregister those that are no longer in the Preferences windows but are in the file
  3128. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3129. if ext not in grb_list:
  3130. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3131. # now write the updated extensions to the self.defaults
  3132. # new_ext = ''
  3133. # for ext in grb_list:
  3134. # new_ext = new_ext + ext + ', '
  3135. # self.defaults["fa_gerber"] = new_ext
  3136. self.inform.emit('[success] %s' %
  3137. _("Selected Gerber file extensions registered with FlatCAM."))
  3138. def add_extension(self, ext_type):
  3139. """
  3140. Add a file extension to the list for a specific object
  3141. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3142. :return:
  3143. """
  3144. if ext_type == 'excellon':
  3145. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3146. if new_ext == '':
  3147. return
  3148. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3149. if new_ext in old_val:
  3150. return
  3151. old_val.append(new_ext)
  3152. old_val.sort()
  3153. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3154. if ext_type == 'gcode':
  3155. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3156. if new_ext == '':
  3157. return
  3158. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3159. if new_ext in old_val:
  3160. return
  3161. old_val.append(new_ext)
  3162. old_val.sort()
  3163. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3164. if ext_type == 'gerber':
  3165. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3166. if new_ext == '':
  3167. return
  3168. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3169. if new_ext in old_val:
  3170. return
  3171. old_val.append(new_ext)
  3172. old_val.sort()
  3173. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3174. if ext_type == 'keyword':
  3175. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3176. if new_kw == '':
  3177. return
  3178. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3179. if new_kw in old_val:
  3180. return
  3181. old_val.append(new_kw)
  3182. old_val.sort()
  3183. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3184. # update the self.myKeywords so the model is updated
  3185. self.autocomplete_kw_list = \
  3186. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3187. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3188. self.shell._edit.set_model_data(self.myKeywords)
  3189. def del_extension(self, ext_type):
  3190. """
  3191. Remove a file extension from the list for a specific object
  3192. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3193. :return:
  3194. """
  3195. if ext_type == 'excellon':
  3196. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3197. if new_ext == '':
  3198. return
  3199. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3200. if new_ext not in old_val:
  3201. return
  3202. old_val.remove(new_ext)
  3203. old_val.sort()
  3204. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3205. if ext_type == 'gcode':
  3206. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3207. if new_ext == '':
  3208. return
  3209. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3210. if new_ext not in old_val:
  3211. return
  3212. old_val.remove(new_ext)
  3213. old_val.sort()
  3214. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3215. if ext_type == 'gerber':
  3216. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3217. if new_ext == '':
  3218. return
  3219. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3220. if new_ext not in old_val:
  3221. return
  3222. old_val.remove(new_ext)
  3223. old_val.sort()
  3224. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3225. if ext_type == 'keyword':
  3226. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3227. if new_kw == '':
  3228. return
  3229. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3230. if new_kw not in old_val:
  3231. return
  3232. old_val.remove(new_kw)
  3233. old_val.sort()
  3234. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3235. # update the self.myKeywords so the model is updated
  3236. self.autocomplete_kw_list = \
  3237. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3238. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3239. self.shell._edit.set_model_data(self.myKeywords)
  3240. def restore_extensions(self, ext_type):
  3241. """
  3242. Restore all file extensions associations with FlatCAM, for a specific object
  3243. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3244. :return:
  3245. """
  3246. if ext_type == 'excellon':
  3247. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3248. # for the ability to open Excellon files with .txt extension
  3249. new_exc_list = deepcopy(self.exc_list)
  3250. try:
  3251. new_exc_list.remove('txt')
  3252. except ValueError:
  3253. pass
  3254. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3255. if ext_type == 'gcode':
  3256. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3257. if ext_type == 'gerber':
  3258. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3259. if ext_type == 'keyword':
  3260. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3261. # update the self.myKeywords so the model is updated
  3262. self.autocomplete_kw_list = self.default_keywords
  3263. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3264. self.shell._edit.set_model_data(self.myKeywords)
  3265. def delete_all_extensions(self, ext_type):
  3266. """
  3267. Delete all file extensions associations with FlatCAM, for a specific object
  3268. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3269. :return:
  3270. """
  3271. if ext_type == 'excellon':
  3272. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3273. if ext_type == 'gcode':
  3274. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3275. if ext_type == 'gerber':
  3276. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3277. if ext_type == 'keyword':
  3278. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3279. # update the self.myKeywords so the model is updated
  3280. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3281. self.shell._edit.set_model_data(self.myKeywords)
  3282. def on_edit_join(self, name=None):
  3283. """
  3284. Callback for Edit->Join. Joins the selected geometry objects into
  3285. a new one.
  3286. :return: None
  3287. """
  3288. self.defaults.report_usage("on_edit_join()")
  3289. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3290. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3291. geo_type_set = set()
  3292. objs = self.collection.get_selected()
  3293. if len(objs) < 2:
  3294. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3295. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3296. return 'fail'
  3297. for obj in objs:
  3298. geo_type_set.add(obj.multigeo)
  3299. # if len(geo_type_list) == 1 means that all list elements are the same
  3300. if len(geo_type_set) != 1:
  3301. self.inform.emit('[ERROR] %s' %
  3302. _("Failed join. The Geometry objects are of different types.\n"
  3303. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3304. "convert from one to another and retry joining \n"
  3305. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3306. "the result may not be what was expected. \n"
  3307. "Check the generated GCODE."))
  3308. return
  3309. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3310. if True in geo_type_set:
  3311. def initialize(geo_obj, app):
  3312. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3313. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3314. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3315. for v in geo_obj.tools.values():
  3316. v['data']['name'] = obj_name_multi
  3317. self.new_object("geometry", obj_name_multi, initialize)
  3318. else:
  3319. def initialize(geo_obj, app):
  3320. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3321. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3322. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3323. for v in geo_obj.tools.values():
  3324. v['data']['name'] = obj_name_single
  3325. self.new_object("geometry", obj_name_single, initialize)
  3326. self.should_we_save = True
  3327. def on_edit_join_exc(self):
  3328. """
  3329. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3330. a new Excellon.
  3331. :return: None
  3332. """
  3333. self.defaults.report_usage("on_edit_join_exc()")
  3334. objs = self.collection.get_selected()
  3335. for obj in objs:
  3336. if not isinstance(obj, ExcellonObject):
  3337. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3338. return
  3339. if len(objs) < 2:
  3340. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3341. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3342. return 'fail'
  3343. def initialize(exc_obj, app):
  3344. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3345. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3346. self.new_object("excellon", 'Combo_Excellon', initialize)
  3347. self.should_we_save = True
  3348. def on_edit_join_grb(self):
  3349. """
  3350. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3351. a new Gerber object.
  3352. :return: None
  3353. """
  3354. self.defaults.report_usage("on_edit_join_grb()")
  3355. objs = self.collection.get_selected()
  3356. for obj in objs:
  3357. if not isinstance(obj, GerberObject):
  3358. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3359. return
  3360. if len(objs) < 2:
  3361. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3362. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3363. return 'fail'
  3364. def initialize(grb_obj, app):
  3365. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3366. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3367. self.new_object("gerber", 'Combo_Gerber', initialize)
  3368. self.should_we_save = True
  3369. def on_convert_singlegeo_to_multigeo(self):
  3370. """
  3371. Called for converting a Geometry object from single-geo to multi-geo.
  3372. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3373. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3374. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3375. the solid-geometry of that tool.
  3376. :return: None
  3377. """
  3378. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3379. obj = self.collection.get_active()
  3380. if obj is None:
  3381. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3382. return
  3383. if not isinstance(obj, GeometryObject):
  3384. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3385. return
  3386. obj.multigeo = True
  3387. for tooluid, dict_value in obj.tools.items():
  3388. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3389. if not isinstance(obj.solid_geometry, list):
  3390. obj.solid_geometry = [obj.solid_geometry]
  3391. # obj.solid_geometry[:] = []
  3392. obj.plot()
  3393. self.should_we_save = True
  3394. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3395. def on_convert_multigeo_to_singlegeo(self):
  3396. """
  3397. Called for converting a Geometry object from multi-geo to single-geo.
  3398. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3399. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3400. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3401. the solid-geometry of that tool.
  3402. :return: None
  3403. """
  3404. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3405. obj = self.collection.get_active()
  3406. if obj is None:
  3407. self.inform.emit('[ERROR_NOTCL] %s' %
  3408. _("Failed. Select a Geometry Object and try again."))
  3409. return
  3410. if not isinstance(obj, GeometryObject):
  3411. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3412. (_("Expected a GeometryObject, got"), type(obj)))
  3413. return
  3414. obj.multigeo = False
  3415. total_solid_geometry = []
  3416. for tooluid, dict_value in obj.tools.items():
  3417. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3418. # clear the original geometry
  3419. dict_value['solid_geometry'][:] = []
  3420. obj.solid_geometry = deepcopy(total_solid_geometry)
  3421. obj.plot()
  3422. self.should_we_save = True
  3423. self.inform.emit('[success] %s' %
  3424. _("A Geometry object was converted to SingleGeo type."))
  3425. def on_defaults_dict_change(self, field):
  3426. """
  3427. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3428. Edit -> Preferences tab window.
  3429. :param field: the key of the self.defaults dictionary that was changed.
  3430. :return: None
  3431. """
  3432. self.preferencesUiManager.defaults_write_form_field(field=field)
  3433. if field == "units":
  3434. self.set_screen_units(self.defaults['units'])
  3435. def set_screen_units(self, units):
  3436. """
  3437. Set the FlatCAM units on the status bar.
  3438. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3439. :return: None
  3440. """
  3441. self.ui.units_label.setText("[" + units.lower() + "]")
  3442. def on_toggle_units_click(self):
  3443. try:
  3444. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3445. except (TypeError, AttributeError):
  3446. pass
  3447. if self.defaults["units"] == 'MM':
  3448. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3449. else:
  3450. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3451. self.on_toggle_units(no_pref=True)
  3452. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3453. lambda: self.on_toggle_units(no_pref=False))
  3454. def on_toggle_units(self, no_pref=False):
  3455. """
  3456. Callback for the Units radio-button change in the Preferences tab.
  3457. Changes the application's default units adn for the project too.
  3458. If changing the project's units, the change propagates to all of
  3459. the objects in the project.
  3460. :return: None
  3461. """
  3462. self.defaults.report_usage("on_toggle_units")
  3463. if self.toggle_units_ignore:
  3464. return
  3465. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3466. # If option is the same, then ignore
  3467. if new_units == self.defaults["units"].upper():
  3468. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3469. return
  3470. # Keys in self.defaults for which to scale their values
  3471. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3472. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3473. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3474. "gerber_editor_ma_high",
  3475. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3476. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3477. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3478. "excellon_feedrate_probe", "excellon_milling_dia",
  3479. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3480. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3481. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3482. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3483. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3484. "geometry_extracut_length", "geometry_z_pdepth",
  3485. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3486. 'cncjob_tooldia',
  3487. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3488. "tools_paintnewdia",
  3489. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3490. "tools_nccnewdia", "tools_ncc_offset_value",
  3491. "tools_2sided_drilldia",
  3492. "tools_film_boundary", "tools_film_scale_stroke",
  3493. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3494. "tools_cutout_depthperpass",
  3495. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3496. "tools_panelize_spacing_rows",
  3497. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3498. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3499. "tools_transform_buffer_dis",
  3500. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3501. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3502. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3503. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3504. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3505. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3506. "tools_cr_h2h_val", "tools_cr_dh_val",
  3507. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3508. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3509. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3510. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3511. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3512. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3513. "tools_copper_thieving_mask_clearance",
  3514. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3515. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3516. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3517. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3518. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3519. "tools_invert_margin",
  3520. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3521. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3522. def scale_defaults(sfactor):
  3523. for dim in dimensions:
  3524. if dim in [
  3525. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3526. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3527. 'tools_transform_mirror_point'
  3528. ]:
  3529. if self.defaults[dim] is None or self.defaults[dim] == '':
  3530. continue
  3531. try:
  3532. coordinates = self.defaults[dim].split(",")
  3533. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3534. coords_xy[0] *= sfactor
  3535. coords_xy[1] *= sfactor
  3536. self.defaults[dim] = "%.*f, %.*f" % (
  3537. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3538. except Exception as e:
  3539. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3540. elif dim in [
  3541. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3542. ]:
  3543. if self.defaults[dim] is None or self.defaults[dim] == '':
  3544. continue
  3545. try:
  3546. self.defaults[dim] = float(self.defaults[dim])
  3547. tools_diameters = [self.defaults[dim]]
  3548. except ValueError:
  3549. try:
  3550. tools_string = self.defaults[dim].split(",")
  3551. tools_diameters = [eval(a) for a in tools_string if a != '']
  3552. except Exception as e:
  3553. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3554. continue
  3555. self.defaults[dim] = ''
  3556. td_len = len(tools_diameters)
  3557. if td_len > 1:
  3558. for t in range(td_len):
  3559. tools_diameters[t] *= sfactor
  3560. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3561. else:
  3562. tools_diameters[0] *= sfactor
  3563. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3564. elif dim in ['global_gridx', 'global_gridy']:
  3565. # format the number of decimals to the one specified in self.decimals
  3566. try:
  3567. val = float(self.defaults[dim]) * sfactor
  3568. except Exception as e:
  3569. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3570. continue
  3571. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3572. else:
  3573. # the number of decimals for the rest is kept unchanged
  3574. if self.defaults[dim]:
  3575. try:
  3576. val = float(self.defaults[dim]) * sfactor
  3577. except Exception as e:
  3578. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3579. continue
  3580. self.defaults[dim] = val
  3581. # The scaling factor depending on choice of units.
  3582. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3583. # Changing project units. Warn user.
  3584. msgbox = QtWidgets.QMessageBox()
  3585. msgbox.setWindowTitle(_("Toggle Units"))
  3586. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3587. msgbox.setText(_("Changing the units of the project\n"
  3588. "will scale all objects.\n\n"
  3589. "Do you want to continue?"))
  3590. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3591. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3592. msgbox.setDefaultButton(bt_ok)
  3593. msgbox.exec_()
  3594. response = msgbox.clickedButton()
  3595. if response == bt_ok:
  3596. if no_pref is False:
  3597. self.preferencesUiManager.defaults_read_form()
  3598. scale_defaults(factor)
  3599. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3600. self.defaults["units"] = new_units
  3601. # update the defaults from form, some may assume that the conversion is enough and it's not
  3602. self.on_options_app2project()
  3603. # update the objects
  3604. for obj in self.collection.get_list():
  3605. obj.convert_units(new_units)
  3606. # make that the properties stored in the object are also updated
  3607. self.object_changed.emit(obj)
  3608. # rebuild the object UI
  3609. obj.build_ui()
  3610. # change this only if the workspace is active
  3611. if self.defaults['global_workspace'] is True:
  3612. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3613. # adjust the grid values on the main toolbar
  3614. val_x = float(self.defaults['global_gridx']) * factor
  3615. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3616. current = self.collection.get_active()
  3617. if current is not None:
  3618. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3619. if not isinstance(current, GeometryObject):
  3620. current.to_form()
  3621. # replot all objects
  3622. self.plot_all()
  3623. # set the status labels to reflect the current FlatCAM units
  3624. self.set_screen_units(new_units)
  3625. # signal to the app that we changed the object properties and it should save the project
  3626. self.should_we_save = True
  3627. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3628. else:
  3629. # Undo toggling
  3630. self.toggle_units_ignore = True
  3631. if self.defaults['units'].upper() == 'MM':
  3632. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3633. else:
  3634. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3635. self.toggle_units_ignore = False
  3636. # store the grid values so they are not changed in the next step
  3637. val_x = float(self.defaults['global_gridx'])
  3638. val_y = float(self.defaults['global_gridy'])
  3639. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3640. self.preferencesUiManager.defaults_read_form()
  3641. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3642. # in self.defaults from the GUI elements but
  3643. # I don't want it for the grid values, so I update them here
  3644. self.defaults['global_gridx'] = val_x
  3645. self.defaults['global_gridy'] = val_y
  3646. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3647. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3648. def on_fullscreen(self, disable=False):
  3649. self.defaults.report_usage("on_fullscreen()")
  3650. flags = self.ui.windowFlags()
  3651. if self.toggle_fscreen is False and disable is False:
  3652. # self.ui.showFullScreen()
  3653. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3654. a = self.ui.geometry()
  3655. self.x_pos = a.x()
  3656. self.y_pos = a.y()
  3657. self.width = a.width()
  3658. self.height = a.height()
  3659. # set new geometry to full desktop rect
  3660. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3661. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3662. # everything else will not work without this hack. This happen in Windows.
  3663. # https://bugreports.qt.io/browse/QTBUG-41309
  3664. desktop = QtWidgets.QApplication.desktop()
  3665. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3666. rec = desktop.screenGeometry(screen)
  3667. x = rec.x() - 1
  3668. y = rec.y() - 1
  3669. h = rec.height() + 2
  3670. w = rec.width() + 2
  3671. self.ui.setGeometry(x, y, w, h)
  3672. self.ui.show()
  3673. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3674. tb.setVisible(False)
  3675. self.ui.snap_toolbar.setVisible(True) # This is always visible
  3676. # self.ui.splitter_left.setVisible(False)
  3677. self.ui.splitter.setSizes([0, 1])
  3678. self.toggle_fscreen = True
  3679. elif self.toggle_fscreen is True or disable is True:
  3680. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3681. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3682. self.ui.showNormal()
  3683. self.restore_toolbar_view()
  3684. # self.ui.splitter_left.setVisible(True)
  3685. self.toggle_fscreen = False
  3686. def on_toggle_plotarea(self):
  3687. self.defaults.report_usage("on_toggle_plotarea()")
  3688. try:
  3689. name = self.ui.plot_tab_area.widget(0).objectName()
  3690. except AttributeError:
  3691. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3692. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3693. self.ui.plot_tab_area.protectTab(0)
  3694. return
  3695. if name != 'plotarea_tab':
  3696. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3697. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3698. self.ui.plot_tab_area.protectTab(0)
  3699. else:
  3700. self.ui.plot_tab_area.closeTab(0)
  3701. def on_toggle_notebook(self):
  3702. if self.ui.splitter.sizes()[0] == 0:
  3703. self.ui.splitter.setSizes([1, 1])
  3704. self.ui.menu_toggle_nb.setChecked(True)
  3705. else:
  3706. self.ui.splitter.setSizes([0, 1])
  3707. self.ui.menu_toggle_nb.setChecked(False)
  3708. def on_toggle_axis(self):
  3709. self.defaults.report_usage("on_toggle_axis()")
  3710. if self.toggle_axis is False:
  3711. if self.is_legacy is False:
  3712. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3713. parent=self.plotcanvas.view.scene)
  3714. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3715. parent=self.plotcanvas.view.scene)
  3716. else:
  3717. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3718. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3719. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3720. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3721. self.plotcanvas.canvas.draw()
  3722. self.toggle_axis = True
  3723. else:
  3724. if self.is_legacy is False:
  3725. self.plotcanvas.v_line.parent = None
  3726. self.plotcanvas.h_line.parent = None
  3727. else:
  3728. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3729. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3730. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3731. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3732. self.plotcanvas.canvas.draw()
  3733. self.toggle_axis = False
  3734. def on_toggle_grid(self):
  3735. self.defaults.report_usage("on_toggle_grid()")
  3736. self.ui.grid_snap_btn.trigger()
  3737. def on_toggle_grid_lines(self):
  3738. self.defaults.report_usage("on_toggle_grd_lines()")
  3739. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3740. if tt_settings.contains("theme"):
  3741. theme = tt_settings.value('theme', type=str)
  3742. else:
  3743. theme = 'white'
  3744. if self.toggle_grid_lines is False:
  3745. if self.is_legacy is False:
  3746. if theme == 'white':
  3747. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3748. else:
  3749. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3750. else:
  3751. self.plotcanvas.axes.grid(True)
  3752. try:
  3753. self.plotcanvas.canvas.draw()
  3754. except IndexError:
  3755. pass
  3756. pass
  3757. self.toggle_grid_lines = True
  3758. else:
  3759. if self.is_legacy is False:
  3760. if theme == 'white':
  3761. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3762. else:
  3763. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3764. else:
  3765. self.plotcanvas.axes.grid(False)
  3766. try:
  3767. self.plotcanvas.canvas.draw()
  3768. except IndexError:
  3769. pass
  3770. self.toggle_grid_lines = False
  3771. if self.is_legacy is False:
  3772. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3773. # - perhaps is a bug in VisPy implementation
  3774. if self.grid_status():
  3775. self.app_cursor.enabled = False
  3776. self.app_cursor.enabled = True
  3777. else:
  3778. self.app_cursor.enabled = True
  3779. self.app_cursor.enabled = False
  3780. def on_update_exc_export(self, state):
  3781. """
  3782. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3783. if the update_excellon_cb checkbox is checked
  3784. :param state: state of the checkbox whose signals is tied to his slot
  3785. :return:
  3786. """
  3787. if state:
  3788. # first try to disconnect
  3789. try:
  3790. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3791. disconnect(self.on_excellon_format_changed)
  3792. except TypeError:
  3793. pass
  3794. try:
  3795. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3796. disconnect(self.on_excellon_format_changed)
  3797. except TypeError:
  3798. pass
  3799. try:
  3800. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3801. disconnect(self.on_excellon_format_changed)
  3802. except TypeError:
  3803. pass
  3804. try:
  3805. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3806. disconnect(self.on_excellon_format_changed)
  3807. except TypeError:
  3808. pass
  3809. try:
  3810. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3811. disconnect(self.on_excellon_zeros_changed)
  3812. except TypeError:
  3813. pass
  3814. try:
  3815. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3816. disconnect(self.on_excellon_zeros_changed)
  3817. except TypeError:
  3818. pass
  3819. # the connect them
  3820. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3821. self.on_excellon_format_changed)
  3822. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3823. self.on_excellon_format_changed)
  3824. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3825. self.on_excellon_format_changed)
  3826. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3827. self.on_excellon_format_changed)
  3828. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3829. self.on_excellon_zeros_changed)
  3830. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3831. self.on_excellon_units_changed)
  3832. else:
  3833. # disconnect the signals
  3834. try:
  3835. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3836. disconnect(self.on_excellon_format_changed)
  3837. except TypeError:
  3838. pass
  3839. try:
  3840. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3841. disconnect(self.on_excellon_format_changed)
  3842. except TypeError:
  3843. pass
  3844. try:
  3845. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3846. disconnect(self.on_excellon_format_changed)
  3847. except TypeError:
  3848. pass
  3849. try:
  3850. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3851. disconnect(self.on_excellon_format_changed)
  3852. except TypeError:
  3853. pass
  3854. try:
  3855. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3856. disconnect(self.on_excellon_zeros_changed)
  3857. except TypeError:
  3858. pass
  3859. try:
  3860. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3861. disconnect(self.on_excellon_zeros_changed)
  3862. except TypeError:
  3863. pass
  3864. def on_excellon_format_changed(self):
  3865. """
  3866. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3867. :return: None
  3868. """
  3869. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3870. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3871. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3872. )
  3873. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3874. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3875. )
  3876. else:
  3877. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3878. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3879. )
  3880. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3881. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3882. )
  3883. def on_excellon_zeros_changed(self):
  3884. """
  3885. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3886. :return: None
  3887. """
  3888. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3889. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3890. )
  3891. def on_excellon_units_changed(self):
  3892. """
  3893. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3894. :return: None
  3895. """
  3896. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3897. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3898. )
  3899. self.on_excellon_format_changed()
  3900. def on_film_color_entry(self):
  3901. self.defaults['tools_film_color'] = \
  3902. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3903. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3904. "background-color:%s;"
  3905. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3906. )
  3907. def on_film_color_button(self):
  3908. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3909. c_dialog = QtWidgets.QColorDialog()
  3910. film_color = c_dialog.getColor(initial=current_color)
  3911. if film_color.isValid() is False:
  3912. return
  3913. # if new color is different then mark that the Preferences are changed
  3914. if film_color != current_color:
  3915. self.preferencesUiManager.on_preferences_edited()
  3916. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3917. "background-color:%s;"
  3918. "border-color: dimgray" % str(film_color.name())
  3919. )
  3920. new_val_sel = str(film_color.name())
  3921. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3922. self.defaults['tools_film_color'] = new_val_sel
  3923. def on_qrcode_fill_color_entry(self):
  3924. self.defaults['tools_qrcode_fill_color'] = \
  3925. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3926. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3927. "background-color:%s;"
  3928. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3929. )
  3930. def on_qrcode_fill_color_button(self):
  3931. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3932. c_dialog = QtWidgets.QColorDialog()
  3933. fill_color = c_dialog.getColor(initial=current_color)
  3934. if fill_color.isValid() is False:
  3935. return
  3936. # if new color is different then mark that the Preferences are changed
  3937. if fill_color != current_color:
  3938. self.preferencesUiManager.on_preferences_edited()
  3939. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3940. "background-color:%s;"
  3941. "border-color: dimgray" % str(fill_color.name())
  3942. )
  3943. new_val_sel = str(fill_color.name())
  3944. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3945. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3946. def on_qrcode_back_color_entry(self):
  3947. self.defaults['tools_qrcode_back_color'] = \
  3948. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3949. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3950. "background-color:%s;"
  3951. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3952. )
  3953. def on_qrcode_back_color_button(self):
  3954. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3955. c_dialog = QtWidgets.QColorDialog()
  3956. back_color = c_dialog.getColor(initial=current_color)
  3957. if back_color.isValid() is False:
  3958. return
  3959. # if new color is different then mark that the Preferences are changed
  3960. if back_color != current_color:
  3961. self.preferencesUiManager.on_preferences_edited()
  3962. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3963. "background-color:%s;"
  3964. "border-color: dimgray" % str(back_color.name())
  3965. )
  3966. new_val_sel = str(back_color.name())
  3967. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3968. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3969. def on_tab_rmb_click(self, checked):
  3970. self.ui.notebook.set_detachable(val=checked)
  3971. self.defaults["global_tabs_detachable"] = checked
  3972. self.ui.plot_tab_area.set_detachable(val=checked)
  3973. self.defaults["global_tabs_detachable"] = checked
  3974. def on_tab_setup_context_menu(self):
  3975. initial_checked = self.defaults["global_tabs_detachable"]
  3976. action_name = str(_("Detachable Tabs"))
  3977. action = QtWidgets.QAction(self)
  3978. action.setCheckable(True)
  3979. action.setText(action_name)
  3980. action.setChecked(initial_checked)
  3981. self.ui.notebook.tabBar.addAction(action)
  3982. self.ui.plot_tab_area.tabBar.addAction(action)
  3983. try:
  3984. action.triggered.disconnect()
  3985. except TypeError:
  3986. pass
  3987. action.triggered.connect(self.on_tab_rmb_click)
  3988. def on_deselect_all(self):
  3989. self.collection.set_all_inactive()
  3990. self.delete_selection_shape()
  3991. def on_workspace_modified(self):
  3992. # self.save_defaults(silent=True)
  3993. if self.is_legacy is True:
  3994. self.plotcanvas.delete_workspace()
  3995. self.preferencesUiManager.defaults_read_form()
  3996. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3997. def on_workspace(self):
  3998. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3999. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4000. else:
  4001. self.plotcanvas.delete_workspace()
  4002. self.preferencesUiManager.defaults_read_form()
  4003. # self.save_defaults(silent=True)
  4004. def on_workspace_toggle(self):
  4005. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4006. try:
  4007. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4008. except TypeError:
  4009. pass
  4010. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4011. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4012. self.on_workspace()
  4013. def on_cursor_type(self, val):
  4014. """
  4015. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4016. :return: None
  4017. """
  4018. self.app_cursor.enabled = False
  4019. if val == 'small':
  4020. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4021. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4022. self.app_cursor = self.plotcanvas.new_cursor()
  4023. else:
  4024. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4025. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4026. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4027. if self.ui.grid_snap_btn.isChecked():
  4028. self.app_cursor.enabled = True
  4029. else:
  4030. self.app_cursor.enabled = False
  4031. def on_tool_add_keypress(self):
  4032. # ## Current application units in Upper Case
  4033. self.units = self.defaults['units'].upper()
  4034. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4035. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4036. if notebook_widget_name == 'selected_tab':
  4037. if self.collection.get_active().kind == 'geometry':
  4038. # Tool add works for Geometry only if Advanced is True in Preferences
  4039. if self.defaults["global_app_level"] == 'a':
  4040. tool_add_popup = FCInputDialog(title="New Tool ...",
  4041. text='Enter a Tool Diameter:',
  4042. min=0.0000, max=99.9999, decimals=4)
  4043. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4044. val, ok = tool_add_popup.get_value()
  4045. if ok:
  4046. if float(val) == 0:
  4047. self.inform.emit('[WARNING_NOTCL] %s' %
  4048. _("Please enter a tool diameter with non-zero value, in Float format."))
  4049. return
  4050. self.collection.get_active().on_tool_add(dia=float(val))
  4051. else:
  4052. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4053. else:
  4054. msgbox = QtWidgets.QMessageBox()
  4055. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4056. "Go to Preferences -> General - Show Advanced Options."))
  4057. msgbox.setWindowTitle("Tool adding ...")
  4058. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4059. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4060. msgbox.setDefaultButton(bt_ok)
  4061. msgbox.exec_()
  4062. # work only if the notebook tab on focus is the Tools_Tab
  4063. if notebook_widget_name == 'tool_tab':
  4064. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4065. # and only if the tool is NCC Tool
  4066. if tool_widget == self.ncclear_tool.toolName:
  4067. self.ncclear_tool.on_add_tool_by_key()
  4068. # and only if the tool is Paint Area Tool
  4069. elif tool_widget == self.paint_tool.toolName:
  4070. self.paint_tool.on_add_tool_by_key()
  4071. # and only if the tool is Solder Paste Dispensing Tool
  4072. elif tool_widget == self.paste_tool.toolName:
  4073. self.paste_tool.on_add_tool_by_key()
  4074. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4075. # See description below.
  4076. def on_delete_keypress(self):
  4077. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4078. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4079. if notebook_widget_name == 'selected_tab':
  4080. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4081. self.collection.get_active().on_tool_delete()
  4082. # work only if the notebook tab on focus is the Tools_Tab
  4083. elif notebook_widget_name == 'tool_tab':
  4084. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4085. # and only if the tool is NCC Tool
  4086. if tool_widget == self.ncclear_tool.toolName:
  4087. self.ncclear_tool.on_tool_delete()
  4088. # and only if the tool is Paint Tool
  4089. elif tool_widget == self.paint_tool.toolName:
  4090. self.paint_tool.on_tool_delete()
  4091. # and only if the tool is Solder Paste Dispensing Tool
  4092. elif tool_widget == self.paste_tool.toolName:
  4093. self.paste_tool.on_tool_delete()
  4094. else:
  4095. self.on_delete()
  4096. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4097. # some screens you have to be careful where you hover with your mouse.
  4098. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4099. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4100. # Complicated, I know :)
  4101. def on_delete(self, force_deletion=False):
  4102. """
  4103. Delete the currently selected FlatCAMObjs.
  4104. :param force_deletion: used by Tcl command
  4105. :return: None
  4106. """
  4107. self.defaults.report_usage("on_delete()")
  4108. response = None
  4109. bt_ok = None
  4110. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4111. # a geometry object before we update it.
  4112. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4113. and self.grb_editor.editor_active is False:
  4114. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4115. msgbox = QtWidgets.QMessageBox()
  4116. msgbox.setWindowTitle(_("Delete objects"))
  4117. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4118. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4119. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4120. "the selected objects?"))
  4121. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4122. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4123. msgbox.setDefaultButton(bt_ok)
  4124. msgbox.exec_()
  4125. response = msgbox.clickedButton()
  4126. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4127. response = bt_ok
  4128. if response == bt_ok:
  4129. if self.collection.get_active():
  4130. self.log.debug("App.on_delete()")
  4131. for obj_active in self.collection.get_selected():
  4132. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4133. if obj_active.kind == 'gerber':
  4134. for el in obj_active.mark_shapes:
  4135. obj_active.mark_shapes[el].clear(update=True)
  4136. obj_active.mark_shapes[el].enabled = False
  4137. # obj_active.mark_shapes[el] = None
  4138. del el
  4139. elif isinstance(obj_active, CNCJobObject):
  4140. try:
  4141. obj_active.text_col.enabled = False
  4142. del obj_active.text_col
  4143. obj_active.annotation.clear(update=True)
  4144. del obj_active.annotation
  4145. except AttributeError as e:
  4146. log.debug(
  4147. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4148. )
  4149. while self.collection.get_selected():
  4150. self.delete_first_selected()
  4151. self.inform.emit('%s...' % _("Object(s) deleted"))
  4152. # make sure that the selection shape is deleted, too
  4153. self.delete_selection_shape()
  4154. # if there are no longer objects delete also the exclusion areas shapes
  4155. if not self.collection.get_list():
  4156. self.exc_areas.clear_shapes()
  4157. else:
  4158. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4159. else:
  4160. self.inform.emit(_("Save the work in Editor and try again ..."))
  4161. def delete_first_selected(self):
  4162. # Keep this for later
  4163. try:
  4164. sel_obj = self.collection.get_active()
  4165. name = sel_obj.options["name"]
  4166. isPlotted = sel_obj.options["plot"]
  4167. except AttributeError:
  4168. self.log.debug("Nothing selected for deletion")
  4169. return
  4170. if self.is_legacy is True:
  4171. # Remove plot only if the object was plotted otherwise delaxes will fail
  4172. if isPlotted:
  4173. try:
  4174. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4175. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4176. except Exception as e:
  4177. log.debug("App.delete_first_selected() --> %s" % str(e))
  4178. self.plotcanvas.auto_adjust_axes()
  4179. # Remove from dictionary
  4180. self.collection.delete_active()
  4181. # Clear form
  4182. self.setup_component_editor()
  4183. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4184. def on_set_origin(self):
  4185. """
  4186. Set the origin to the left mouse click position
  4187. :return: None
  4188. """
  4189. # display the message for the user
  4190. # and ask him to click on the desired position
  4191. self.defaults.report_usage("on_set_origin()")
  4192. def origin_replot():
  4193. def worker_task():
  4194. with self.proc_container.new('%s...' % _("Plotting")):
  4195. for obj in self.collection.get_list():
  4196. obj.plot()
  4197. self.plotcanvas.fit_view()
  4198. if self.is_legacy:
  4199. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4200. else:
  4201. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4202. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4203. self.inform.emit(_('Click to set the origin ...'))
  4204. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4205. # first disconnect it as it may have been used by something else
  4206. try:
  4207. self.replot_signal.disconnect()
  4208. except TypeError:
  4209. pass
  4210. self.replot_signal[list].connect(origin_replot)
  4211. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4212. """
  4213. :param event:
  4214. :param location:
  4215. :param noplot:
  4216. :param use_thread:
  4217. :return:
  4218. """
  4219. noplot_sig = noplot
  4220. def worker_task():
  4221. with self.proc_container.new(_("Setting Origin...")):
  4222. obj_list = self.collection.get_list()
  4223. for obj in obj_list:
  4224. obj.offset((x, y))
  4225. self.object_changed.emit(obj)
  4226. # Update the object bounding box options
  4227. a, b, c, d = obj.bounds()
  4228. obj.options['xmin'] = a
  4229. obj.options['ymin'] = b
  4230. obj.options['xmax'] = c
  4231. obj.options['ymax'] = d
  4232. self.inform.emit('[success] %s...' % _('Origin set'))
  4233. for obj in obj_list:
  4234. out_name = obj.options["name"]
  4235. if obj.kind == 'gerber':
  4236. obj.source_file = self.export_gerber(
  4237. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4238. elif obj.kind == 'excellon':
  4239. obj.source_file = self.export_excellon(
  4240. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4241. if noplot_sig is False:
  4242. self.replot_signal.emit([])
  4243. if location is not None:
  4244. if len(location) != 2:
  4245. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4246. return 'fail'
  4247. x, y = location
  4248. if use_thread is True:
  4249. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4250. else:
  4251. worker_task()
  4252. self.should_we_save = True
  4253. return
  4254. if event.button == 1:
  4255. if self.is_legacy is False:
  4256. event_pos = event.pos
  4257. else:
  4258. event_pos = (event.xdata, event.ydata)
  4259. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4260. if self.grid_status():
  4261. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4262. else:
  4263. pos = pos_canvas
  4264. x = 0 - pos[0]
  4265. y = 0 - pos[1]
  4266. if use_thread is True:
  4267. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4268. else:
  4269. worker_task()
  4270. self.should_we_save = True
  4271. def on_move2origin(self, use_thread=True):
  4272. """
  4273. Move selected objects to origin.
  4274. :param use_thread: Control if to use threaded operation. Boolean.
  4275. :return:
  4276. """
  4277. def worker_task():
  4278. with self.proc_container.new(_("Moving to Origin...")):
  4279. obj_list = self.collection.get_selected()
  4280. if not obj_list:
  4281. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4282. return
  4283. xminlist = []
  4284. yminlist = []
  4285. # first get a bounding box to fit all
  4286. for obj in obj_list:
  4287. xmin, ymin, xmax, ymax = obj.bounds()
  4288. xminlist.append(xmin)
  4289. yminlist.append(ymin)
  4290. # get the minimum x,y for all objects selected
  4291. x = min(xminlist)
  4292. y = min(yminlist)
  4293. for obj in obj_list:
  4294. obj.offset((-x, -y))
  4295. self.object_changed.emit(obj)
  4296. # Update the object bounding box options
  4297. a, b, c, d = obj.bounds()
  4298. obj.options['xmin'] = a
  4299. obj.options['ymin'] = b
  4300. obj.options['xmax'] = c
  4301. obj.options['ymax'] = d
  4302. for obj in obj_list:
  4303. obj.plot()
  4304. for obj in obj_list:
  4305. out_name = obj.options["name"]
  4306. if obj.kind == 'gerber':
  4307. obj.source_file = self.export_gerber(
  4308. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4309. elif obj.kind == 'excellon':
  4310. obj.source_file = self.export_excellon(
  4311. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4312. self.inform.emit('[success] %s...' % _('Origin set'))
  4313. if use_thread is True:
  4314. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4315. else:
  4316. worker_task()
  4317. self.should_we_save = True
  4318. def on_jump_to(self, custom_location=None, fit_center=True):
  4319. """
  4320. Jump to a location by setting the mouse cursor location.
  4321. :param custom_location: Jump to a specified point. (x, y) tuple.
  4322. :param fit_center: If to fit view. Boolean.
  4323. :return:
  4324. """
  4325. self.defaults.report_usage("on_jump_to()")
  4326. if not custom_location:
  4327. dia_box_location = None
  4328. try:
  4329. dia_box_location = eval(self.clipboard.text())
  4330. except Exception:
  4331. pass
  4332. if type(dia_box_location) == tuple:
  4333. dia_box_location = str(dia_box_location)
  4334. else:
  4335. dia_box_location = None
  4336. # dia_box = Dialog_box(title=_("Jump to ..."),
  4337. # label=_("Enter the coordinates in format X,Y:"),
  4338. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4339. # initial_text=dia_box_location)
  4340. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4341. label=_("Enter the coordinates in format X,Y:"),
  4342. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4343. initial_text=dia_box_location,
  4344. reference=self.defaults['global_jump_ref'])
  4345. if dia_box.ok is True:
  4346. try:
  4347. location = eval(dia_box.location)
  4348. if not isinstance(location, tuple):
  4349. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4350. return
  4351. if dia_box.reference == 'rel':
  4352. rel_x = self.mouse[0] + location[0]
  4353. rel_y = self.mouse[1] + location[1]
  4354. location = (rel_x, rel_y)
  4355. self.defaults['global_jump_ref'] = dia_box.reference
  4356. except Exception:
  4357. return
  4358. else:
  4359. return
  4360. else:
  4361. location = custom_location
  4362. self.jump_signal.emit(location)
  4363. if fit_center:
  4364. self.plotcanvas.fit_center(loc=location)
  4365. cursor = QtGui.QCursor()
  4366. if self.is_legacy is False:
  4367. # I don't know where those differences come from but they are constant for the current
  4368. # execution of the application and they are multiples of a value around 0.0263mm.
  4369. # In a random way sometimes they are more sometimes they are less
  4370. # if units == 'MM':
  4371. # cal_factor = 0.0263
  4372. # else:
  4373. # cal_factor = 0.0263 / 25.4
  4374. cal_location = (location[0], location[1])
  4375. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4376. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4377. j_pos = (
  4378. int(canvas_origin.x() + round(jump_loc[0])),
  4379. int(canvas_origin.y() + round(jump_loc[1]))
  4380. )
  4381. cursor.setPos(j_pos[0], j_pos[1])
  4382. else:
  4383. # find the canvas origin which is in the top left corner
  4384. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4385. # determine the coordinates for the lowest left point of the canvas
  4386. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4387. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4388. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4389. # canvas) and the point (width, height) is in the top-right location
  4390. loc = self.plotcanvas.axes.transData.transform_point(location)
  4391. j_pos = (
  4392. int(x0 + loc[0]),
  4393. int(y0 - loc[1])
  4394. )
  4395. cursor.setPos(j_pos[0], j_pos[1])
  4396. self.plotcanvas.mouse = [location[0], location[1]]
  4397. if self.defaults["global_cursor_color_enabled"] is True:
  4398. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4399. else:
  4400. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4401. if self.grid_status():
  4402. # Update cursor
  4403. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4404. symbol='++', edge_color=self.cursor_color_3D,
  4405. edge_width=self.defaults["global_cursor_width"],
  4406. size=self.defaults["global_cursor_size"])
  4407. # Set the relative position label
  4408. dx = location[0] - float(self.rel_point1[0])
  4409. dy = location[1] - float(self.rel_point1[1])
  4410. # self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4411. # "<b>Y</b>: %.4f" % (location[0], location[1]))
  4412. # # Set the position label
  4413. #
  4414. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4415. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4416. units = self.defaults["units"].lower()
  4417. self.plotcanvas.text_hud.text = \
  4418. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4419. dx, units, dy, units, location[0], units, location[1], units)
  4420. self.inform.emit('[success] %s' % _("Done."))
  4421. return location
  4422. def on_locate(self, obj, fit_center=True):
  4423. """
  4424. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4425. :param obj: The object on which to locate certain points
  4426. :param fit_center: If to fit view. Boolean.
  4427. :return: A point location. (x, y) tuple.
  4428. """
  4429. self.defaults.report_usage("on_locate()")
  4430. if obj is None:
  4431. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4432. return 'fail'
  4433. class DialogBoxChoice(QtWidgets.QDialog):
  4434. def __init__(self, title=None, icon=None, choice='bl'):
  4435. """
  4436. :param title: string with the window title
  4437. """
  4438. super(DialogBoxChoice, self).__init__()
  4439. self.ok = False
  4440. self.setWindowIcon(icon)
  4441. self.setWindowTitle(str(title))
  4442. self.form = QtWidgets.QFormLayout(self)
  4443. self.ref_radio = RadioSet([
  4444. {"label": _("Bottom-Left"), "value": "bl"},
  4445. {"label": _("Top-Left"), "value": "tl"},
  4446. {"label": _("Bottom-Right"), "value": "br"},
  4447. {"label": _("Top-Right"), "value": "tr"},
  4448. {"label": _("Center"), "value": "c"}
  4449. ], orientation='vertical', stretch=False)
  4450. self.ref_radio.set_value(choice)
  4451. self.form.addRow(self.ref_radio)
  4452. self.button_box = QtWidgets.QDialogButtonBox(
  4453. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4454. Qt.Horizontal, parent=self)
  4455. self.form.addRow(self.button_box)
  4456. self.button_box.accepted.connect(self.accept)
  4457. self.button_box.rejected.connect(self.reject)
  4458. if self.exec_() == QtWidgets.QDialog.Accepted:
  4459. self.ok = True
  4460. self.location_point = self.ref_radio.get_value()
  4461. else:
  4462. self.ok = False
  4463. self.location_point = None
  4464. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4465. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4466. choice=self.defaults['global_locate_pt'])
  4467. if dia_box.ok is True:
  4468. try:
  4469. location_point = dia_box.location_point
  4470. self.defaults['global_locate_pt'] = dia_box.location_point
  4471. except Exception:
  4472. return
  4473. else:
  4474. return
  4475. loc_b = obj.bounds()
  4476. if location_point == 'bl':
  4477. location = (loc_b[0], loc_b[1])
  4478. elif location_point == 'tl':
  4479. location = (loc_b[0], loc_b[3])
  4480. elif location_point == 'br':
  4481. location = (loc_b[2], loc_b[1])
  4482. elif location_point == 'tr':
  4483. location = (loc_b[2], loc_b[3])
  4484. else:
  4485. # center
  4486. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4487. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4488. location = (cx, cy)
  4489. self.locate_signal.emit(location, location_point)
  4490. if fit_center:
  4491. self.plotcanvas.fit_center(loc=location)
  4492. cursor = QtGui.QCursor()
  4493. if self.is_legacy is False:
  4494. # I don't know where those differences come from but they are constant for the current
  4495. # execution of the application and they are multiples of a value around 0.0263mm.
  4496. # In a random way sometimes they are more sometimes they are less
  4497. # if units == 'MM':
  4498. # cal_factor = 0.0263
  4499. # else:
  4500. # cal_factor = 0.0263 / 25.4
  4501. cal_location = (location[0], location[1])
  4502. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4503. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4504. j_pos = (
  4505. int(canvas_origin.x() + round(jump_loc[0])),
  4506. int(canvas_origin.y() + round(jump_loc[1]))
  4507. )
  4508. cursor.setPos(j_pos[0], j_pos[1])
  4509. else:
  4510. # find the canvas origin which is in the top left corner
  4511. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4512. # determine the coordinates for the lowest left point of the canvas
  4513. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4514. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4515. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4516. # canvas) and the point (width, height) is in the top-right location
  4517. loc = self.plotcanvas.axes.transData.transform_point(location)
  4518. j_pos = (
  4519. int(x0 + loc[0]),
  4520. int(y0 - loc[1])
  4521. )
  4522. cursor.setPos(j_pos[0], j_pos[1])
  4523. self.plotcanvas.mouse = [location[0], location[1]]
  4524. if self.defaults["global_cursor_color_enabled"] is True:
  4525. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4526. else:
  4527. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4528. if self.grid_status():
  4529. # Update cursor
  4530. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4531. symbol='++', edge_color=self.cursor_color_3D,
  4532. edge_width=self.defaults["global_cursor_width"],
  4533. size=self.defaults["global_cursor_size"])
  4534. # Set the relative position label
  4535. self.dx = location[0] - float(self.rel_point1[0])
  4536. self.dy = location[1] - float(self.rel_point1[1])
  4537. # Set the position label
  4538. # self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4539. # "<b>Y</b>: %.4f" % (location[0], location[1]))
  4540. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4541. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4542. units = self.defaults["units"].lower()
  4543. self.plotcanvas.text_hud.text = \
  4544. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4545. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4546. self.inform.emit('[success] %s' % _("Done."))
  4547. return location
  4548. def on_copy_command(self):
  4549. """
  4550. Will copy a selection of objects, creating new objects.
  4551. :return:
  4552. """
  4553. self.defaults.report_usage("on_copy_command()")
  4554. def initialize(obj_init, app):
  4555. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4556. try:
  4557. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4558. except AttributeError:
  4559. pass
  4560. try:
  4561. obj_init.apertures = deepcopy(obj.apertures)
  4562. except AttributeError:
  4563. pass
  4564. try:
  4565. if obj.tools:
  4566. obj_init.tools = deepcopy(obj.tools)
  4567. except Exception as err:
  4568. log.debug("App.on_copy_command() --> %s" % str(err))
  4569. try:
  4570. obj_init.source_file = deepcopy(obj.source_file)
  4571. except (AttributeError, TypeError):
  4572. pass
  4573. def initialize_excellon(obj_init, app):
  4574. obj_init.source_file = deepcopy(obj.source_file)
  4575. obj_init.tools = deepcopy(obj.tools)
  4576. # drills are offset, so they need to be deep copied
  4577. obj_init.drills = deepcopy(obj.drills)
  4578. # slots are offset, so they need to be deep copied
  4579. obj_init.slots = deepcopy(obj.slots)
  4580. obj_init.create_geometry()
  4581. def initialize_script(obj_init, app_obj):
  4582. obj_init.source_file = deepcopy(obj.source_file)
  4583. def initialize_document(obj_init, app_obj):
  4584. obj_init.source_file = deepcopy(obj.source_file)
  4585. for obj in self.collection.get_selected():
  4586. obj_name = obj.options["name"]
  4587. try:
  4588. if isinstance(obj, ExcellonObject):
  4589. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4590. elif isinstance(obj, GerberObject):
  4591. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4592. elif isinstance(obj, GeometryObject):
  4593. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4594. elif isinstance(obj, ScriptObject):
  4595. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4596. elif isinstance(obj, DocumentObject):
  4597. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4598. except Exception as e:
  4599. return "Operation failed: %s" % str(e)
  4600. def on_copy_object2(self, custom_name):
  4601. def initialize_geometry(obj_init, app):
  4602. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4603. try:
  4604. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4605. except AttributeError:
  4606. pass
  4607. try:
  4608. obj_init.apertures = deepcopy(obj.apertures)
  4609. except AttributeError:
  4610. pass
  4611. try:
  4612. if obj.tools:
  4613. obj_init.tools = deepcopy(obj.tools)
  4614. except Exception as ee:
  4615. log.debug("on_copy_object2() --> %s" % str(ee))
  4616. def initialize_gerber(obj_init, app):
  4617. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4618. obj_init.apertures = deepcopy(obj.apertures)
  4619. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4620. def initialize_excellon(obj_init, app):
  4621. obj_init.tools = deepcopy(obj.tools)
  4622. # drills are offset, so they need to be deep copied
  4623. obj_init.drills = deepcopy(obj.drills)
  4624. # slots are offset, so they need to be deep copied
  4625. obj_init.slots = deepcopy(obj.slots)
  4626. obj_init.create_geometry()
  4627. for obj in self.collection.get_selected():
  4628. obj_name = obj.options["name"]
  4629. try:
  4630. if isinstance(obj, ExcellonObject):
  4631. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4632. elif isinstance(obj, GerberObject):
  4633. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4634. elif isinstance(obj, GeometryObject):
  4635. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4636. except Exception as er:
  4637. return "Operation failed: %s" % str(er)
  4638. def on_rename_object(self, text):
  4639. """
  4640. Will rename an object.
  4641. :param text: New name for the object.
  4642. :return:
  4643. """
  4644. self.defaults.report_usage("on_rename_object()")
  4645. named_obj = self.collection.get_active()
  4646. for obj in named_obj:
  4647. if obj is list:
  4648. self.on_rename_object(text)
  4649. else:
  4650. try:
  4651. obj.options['name'] = text
  4652. except Exception as e:
  4653. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4654. def convert_any2geo(self):
  4655. """
  4656. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4657. :return:
  4658. """
  4659. self.defaults.report_usage("convert_any2geo()")
  4660. def initialize(obj_init, app):
  4661. obj_init.solid_geometry = obj.solid_geometry
  4662. try:
  4663. obj_init.follow_geometry = obj.follow_geometry
  4664. except AttributeError:
  4665. pass
  4666. try:
  4667. obj_init.apertures = obj.apertures
  4668. except AttributeError:
  4669. pass
  4670. try:
  4671. if obj.tools:
  4672. obj_init.tools = obj.tools
  4673. except AttributeError:
  4674. pass
  4675. def initialize_excellon(obj_init, app):
  4676. # objs = self.collection.get_selected()
  4677. # GeometryObject.merge(objs, obj)
  4678. solid_geo = []
  4679. for tool in obj.tools:
  4680. for geo in obj.tools[tool]['solid_geometry']:
  4681. solid_geo.append(geo)
  4682. obj_init.solid_geometry = deepcopy(solid_geo)
  4683. if not self.collection.get_selected():
  4684. log.warning("App.convert_any2geo --> No object selected")
  4685. self.inform.emit('[WARNING_NOTCL] %s' %
  4686. _("No object is selected. Select an object and try again."))
  4687. return
  4688. for obj in self.collection.get_selected():
  4689. obj_name = obj.options["name"]
  4690. try:
  4691. if isinstance(obj, ExcellonObject):
  4692. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4693. else:
  4694. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4695. except Exception as e:
  4696. return "Operation failed: %s" % str(e)
  4697. def convert_any2gerber(self):
  4698. """
  4699. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4700. :return:
  4701. """
  4702. self.defaults.report_usage("convert_any2gerber()")
  4703. def initialize_geometry(obj_init, app):
  4704. apertures = {}
  4705. apid = 0
  4706. apertures[str(apid)] = {}
  4707. apertures[str(apid)]['geometry'] = []
  4708. for obj_orig in obj.solid_geometry:
  4709. new_elem = {}
  4710. new_elem['solid'] = obj_orig
  4711. try:
  4712. new_elem['follow'] = obj_orig.exterior
  4713. except AttributeError:
  4714. pass
  4715. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4716. apertures[str(apid)]['size'] = 0.0
  4717. apertures[str(apid)]['type'] = 'C'
  4718. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4719. obj_init.apertures = deepcopy(apertures)
  4720. def initialize_excellon(obj_init, app):
  4721. apertures = {}
  4722. apid = 10
  4723. for tool in obj.tools:
  4724. apertures[str(apid)] = {}
  4725. apertures[str(apid)]['geometry'] = []
  4726. for geo in obj.tools[tool]['solid_geometry']:
  4727. new_el = {}
  4728. new_el['solid'] = geo
  4729. new_el['follow'] = geo.exterior
  4730. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4731. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4732. apertures[str(apid)]['type'] = 'C'
  4733. apid += 1
  4734. # create solid_geometry
  4735. solid_geometry = []
  4736. for apid in apertures:
  4737. for geo_el in apertures[apid]['geometry']:
  4738. solid_geometry.append(geo_el['solid'])
  4739. solid_geometry = MultiPolygon(solid_geometry)
  4740. solid_geometry = solid_geometry.buffer(0.0000001)
  4741. obj_init.solid_geometry = deepcopy(solid_geometry)
  4742. obj_init.apertures = deepcopy(apertures)
  4743. # clear the working objects (perhaps not necessary due of Python GC)
  4744. apertures.clear()
  4745. if not self.collection.get_selected():
  4746. log.warning("App.convert_any2gerber --> No object selected")
  4747. self.inform.emit('[WARNING_NOTCL] %s' %
  4748. _("No object is selected. Select an object and try again."))
  4749. return
  4750. for obj in self.collection.get_selected():
  4751. obj_name = obj.options["name"]
  4752. try:
  4753. if isinstance(obj, ExcellonObject):
  4754. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4755. elif isinstance(obj, GeometryObject):
  4756. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4757. else:
  4758. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4759. except Exception as e:
  4760. return "Operation failed: %s" % str(e)
  4761. def abort_all_tasks(self):
  4762. """
  4763. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4764. on the first possible occasion.
  4765. :return:
  4766. """
  4767. if self.abort_flag is False:
  4768. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4769. self.abort_flag = True
  4770. self.cleanup.emit()
  4771. def app_is_idle(self):
  4772. if self.abort_flag:
  4773. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4774. self.abort_flag = False
  4775. def on_selectall(self):
  4776. """
  4777. Will draw a selection box shape around the selected objects.
  4778. :return:
  4779. """
  4780. self.defaults.report_usage("on_selectall()")
  4781. # delete the possible selection box around a possible selected object
  4782. self.delete_selection_shape()
  4783. for name in self.collection.get_names():
  4784. self.collection.set_active(name)
  4785. curr_sel_obj = self.collection.get_by_name(name)
  4786. # create the selection box around the selected object
  4787. if self.defaults['global_selection_shape'] is True:
  4788. self.draw_selection_shape(curr_sel_obj)
  4789. def on_preferences(self):
  4790. """
  4791. Adds the Preferences in a Tab in Plot Area
  4792. :return:
  4793. """
  4794. # add the tab if it was closed
  4795. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4796. # delete the absolute and relative position and messages in the infobar
  4797. # self.ui.position_label.setText("")
  4798. # self.ui.rel_position_label.setText("")
  4799. # Switch plot_area to preferences page
  4800. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4801. # self.ui.show()
  4802. # detect changes in the preferences
  4803. for idx in range(self.ui.pref_tab_area.count()):
  4804. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4805. try:
  4806. try:
  4807. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4808. except (TypeError, AttributeError):
  4809. pass
  4810. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4811. except AttributeError:
  4812. pass
  4813. try:
  4814. try:
  4815. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4816. except (TypeError, AttributeError):
  4817. pass
  4818. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4819. except AttributeError:
  4820. pass
  4821. try:
  4822. try:
  4823. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4824. except (TypeError, AttributeError):
  4825. pass
  4826. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4827. except AttributeError:
  4828. pass
  4829. try:
  4830. try:
  4831. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4832. except (TypeError, AttributeError):
  4833. pass
  4834. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4835. except AttributeError:
  4836. pass
  4837. try:
  4838. try:
  4839. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4840. except (TypeError, AttributeError):
  4841. pass
  4842. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4843. except AttributeError:
  4844. pass
  4845. def on_tools_database(self, source='app'):
  4846. """
  4847. Adds the Tools Database in a Tab in Plot Area.
  4848. :return:
  4849. """
  4850. for idx in range(self.ui.plot_tab_area.count()):
  4851. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4852. # there can be only one instance of Tools Database at one time
  4853. return
  4854. if source == 'app':
  4855. self.tools_db_tab = ToolsDB2(
  4856. app=self,
  4857. parent=self.ui,
  4858. callback_on_edited=self.on_tools_db_edited,
  4859. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4860. )
  4861. elif source == 'ncc':
  4862. self.tools_db_tab = ToolsDB2(
  4863. app=self,
  4864. parent=self.ui,
  4865. callback_on_edited=self.on_tools_db_edited,
  4866. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4867. )
  4868. elif source == 'paint':
  4869. self.tools_db_tab = ToolsDB2(
  4870. app=self,
  4871. parent=self.ui,
  4872. callback_on_edited=self.on_tools_db_edited,
  4873. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4874. )
  4875. # add the tab if it was closed
  4876. try:
  4877. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4878. self.tools_db_tab.setObjectName("database_tab")
  4879. except Exception as e:
  4880. log.debug("App.on_tools_database() --> %s" % str(e))
  4881. return
  4882. # delete the absolute and relative position and messages in the infobar
  4883. self.ui.position_label.setText("")
  4884. self.ui.rel_position_label.setText("")
  4885. # Switch plot_area to preferences page
  4886. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4887. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4888. self.tools_db_tab.ui_connect()
  4889. def on_tools_db_edited(self):
  4890. """
  4891. Executed whenever a tool is edited in Tools Database.
  4892. Will color the text of the Tools Database tab to Red color.
  4893. :return:
  4894. """
  4895. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4896. for idx in range(self.ui.plot_tab_area.count()):
  4897. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4898. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4899. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4900. self.tools_db_changed_flag = True
  4901. def on_geometry_tool_add_from_db_executed(self, tool):
  4902. """
  4903. Here add the tool from DB in the selected geometry object.
  4904. :return:
  4905. """
  4906. tool_from_db = deepcopy(tool)
  4907. obj = self.collection.get_active()
  4908. if isinstance(obj, GeometryObject):
  4909. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4910. # close the tab and delete it
  4911. for idx in range(self.ui.plot_tab_area.count()):
  4912. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4913. wdg = self.ui.plot_tab_area.widget(idx)
  4914. wdg.deleteLater()
  4915. self.ui.plot_tab_area.removeTab(idx)
  4916. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4917. else:
  4918. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4919. def on_plot_area_tab_closed(self, tab_obj_name):
  4920. """
  4921. Executed whenever a QTab is closed in the Plot Area.
  4922. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4923. :return:
  4924. """
  4925. if tab_obj_name == "preferences_tab":
  4926. self.preferencesUiManager.on_close_preferences_tab()
  4927. elif tab_obj_name == "database_tab":
  4928. # disconnect the signals from the table widget in tab
  4929. self.tools_db_tab.ui_disconnect()
  4930. if self.tools_db_changed_flag is True:
  4931. msgbox = QtWidgets.QMessageBox()
  4932. msgbox.setText(_("One or more Tools are edited.\n"
  4933. "Do you want to update the Tools Database?"))
  4934. msgbox.setWindowTitle(_("Save Tools Database"))
  4935. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4936. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4937. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4938. msgbox.setDefaultButton(bt_yes)
  4939. msgbox.exec_()
  4940. response = msgbox.clickedButton()
  4941. if response == bt_yes:
  4942. self.tools_db_tab.on_save_tools_db()
  4943. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4944. else:
  4945. self.tools_db_changed_flag = False
  4946. self.inform.emit('')
  4947. return
  4948. self.tools_db_tab.deleteLater()
  4949. elif tab_obj_name == "text_editor_tab":
  4950. self.toggle_codeeditor = False
  4951. elif tab_obj_name == "bookmarks_tab":
  4952. self.book_dialog_tab.rebuild_actions()
  4953. self.book_dialog_tab.deleteLater()
  4954. else:
  4955. return
  4956. # def on_plotarea_tab_closed(self, tab_idx):
  4957. # """
  4958. #
  4959. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4960. # :return:
  4961. # """
  4962. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4963. #
  4964. # if widget is not None:
  4965. # widget.deleteLater()
  4966. # self.ui.plot_tab_area.removeTab(tab_idx)
  4967. def on_flipy(self):
  4968. """
  4969. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4970. :return:
  4971. """
  4972. self.defaults.report_usage("on_flipy()")
  4973. obj_list = self.collection.get_selected()
  4974. xminlist = []
  4975. yminlist = []
  4976. xmaxlist = []
  4977. ymaxlist = []
  4978. if not obj_list:
  4979. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4980. else:
  4981. try:
  4982. # first get a bounding box to fit all
  4983. for obj in obj_list:
  4984. xmin, ymin, xmax, ymax = obj.bounds()
  4985. xminlist.append(xmin)
  4986. yminlist.append(ymin)
  4987. xmaxlist.append(xmax)
  4988. ymaxlist.append(ymax)
  4989. # get the minimum x,y and maximum x,y for all objects selected
  4990. xminimal = min(xminlist)
  4991. yminimal = min(yminlist)
  4992. xmaximal = max(xmaxlist)
  4993. ymaximal = max(ymaxlist)
  4994. px = 0.5 * (xminimal + xmaximal)
  4995. py = 0.5 * (yminimal + ymaximal)
  4996. # execute mirroring
  4997. for obj in obj_list:
  4998. obj.mirror('X', [px, py])
  4999. obj.plot()
  5000. self.object_changed.emit(obj)
  5001. self.inform.emit('[success] %s' %
  5002. _("Flip on Y axis done."))
  5003. except Exception as e:
  5004. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5005. return
  5006. def on_flipx(self):
  5007. """
  5008. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5009. :return:
  5010. """
  5011. self.defaults.report_usage("on_flipx()")
  5012. obj_list = self.collection.get_selected()
  5013. xminlist = []
  5014. yminlist = []
  5015. xmaxlist = []
  5016. ymaxlist = []
  5017. if not obj_list:
  5018. self.inform.emit('[WARNING_NOTCL] %s' %
  5019. _("No object selected to Flip on X axis."))
  5020. else:
  5021. try:
  5022. # first get a bounding box to fit all
  5023. for obj in obj_list:
  5024. xmin, ymin, xmax, ymax = obj.bounds()
  5025. xminlist.append(xmin)
  5026. yminlist.append(ymin)
  5027. xmaxlist.append(xmax)
  5028. ymaxlist.append(ymax)
  5029. # get the minimum x,y and maximum x,y for all objects selected
  5030. xminimal = min(xminlist)
  5031. yminimal = min(yminlist)
  5032. xmaximal = max(xmaxlist)
  5033. ymaximal = max(ymaxlist)
  5034. px = 0.5 * (xminimal + xmaximal)
  5035. py = 0.5 * (yminimal + ymaximal)
  5036. # execute mirroring
  5037. for obj in obj_list:
  5038. obj.mirror('Y', [px, py])
  5039. obj.plot()
  5040. self.object_changed.emit(obj)
  5041. self.inform.emit('[success] %s' %
  5042. _("Flip on X axis done."))
  5043. except Exception as e:
  5044. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5045. return
  5046. def on_rotate(self, silent=False, preset=None):
  5047. """
  5048. Executed when Options -> Rotate Selection menu entry is clicked.
  5049. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5050. :param preset: A value to be used as predefined angle for rotation.
  5051. :return:
  5052. """
  5053. self.defaults.report_usage("on_rotate()")
  5054. obj_list = self.collection.get_selected()
  5055. xminlist = []
  5056. yminlist = []
  5057. xmaxlist = []
  5058. ymaxlist = []
  5059. if not obj_list:
  5060. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5061. else:
  5062. if silent is False:
  5063. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5064. min=-360, max=360, decimals=4,
  5065. init_val=float(self.defaults['tools_transform_rotate']))
  5066. num, ok = rotatebox.get_value()
  5067. else:
  5068. num = preset
  5069. ok = True
  5070. if ok:
  5071. try:
  5072. # first get a bounding box to fit all
  5073. for obj in obj_list:
  5074. xmin, ymin, xmax, ymax = obj.bounds()
  5075. xminlist.append(xmin)
  5076. yminlist.append(ymin)
  5077. xmaxlist.append(xmax)
  5078. ymaxlist.append(ymax)
  5079. # get the minimum x,y and maximum x,y for all objects selected
  5080. xminimal = min(xminlist)
  5081. yminimal = min(yminlist)
  5082. xmaximal = max(xmaxlist)
  5083. ymaximal = max(ymaxlist)
  5084. px = 0.5 * (xminimal + xmaximal)
  5085. py = 0.5 * (yminimal + ymaximal)
  5086. for sel_obj in obj_list:
  5087. sel_obj.rotate(-float(num), point=(px, py))
  5088. sel_obj.plot()
  5089. self.object_changed.emit(sel_obj)
  5090. self.inform.emit('[success] %s' %
  5091. _("Rotation done."))
  5092. except Exception as e:
  5093. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5094. return
  5095. def on_skewx(self):
  5096. """
  5097. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5098. :return:
  5099. """
  5100. self.defaults.report_usage("on_skewx()")
  5101. obj_list = self.collection.get_selected()
  5102. xminlist = []
  5103. yminlist = []
  5104. if not obj_list:
  5105. self.inform.emit('[WARNING_NOTCL] %s' %
  5106. _("No object selected to Skew/Shear on X axis."))
  5107. else:
  5108. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5109. min=-360, max=360, decimals=4,
  5110. init_val=float(self.defaults['tools_transform_skew_x']))
  5111. num, ok = skewxbox.get_value()
  5112. if ok:
  5113. # first get a bounding box to fit all
  5114. for obj in obj_list:
  5115. xmin, ymin, xmax, ymax = obj.bounds()
  5116. xminlist.append(xmin)
  5117. yminlist.append(ymin)
  5118. # get the minimum x,y and maximum x,y for all objects selected
  5119. xminimal = min(xminlist)
  5120. yminimal = min(yminlist)
  5121. for obj in obj_list:
  5122. obj.skew(num, 0, point=(xminimal, yminimal))
  5123. obj.plot()
  5124. self.object_changed.emit(obj)
  5125. self.inform.emit('[success] %s' %
  5126. _("Skew on X axis done."))
  5127. def on_skewy(self):
  5128. """
  5129. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5130. :return:
  5131. """
  5132. self.defaults.report_usage("on_skewy()")
  5133. obj_list = self.collection.get_selected()
  5134. xminlist = []
  5135. yminlist = []
  5136. if not obj_list:
  5137. self.inform.emit('[WARNING_NOTCL] %s' %
  5138. _("No object selected to Skew/Shear on Y axis."))
  5139. else:
  5140. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5141. min=-360, max=360, decimals=4,
  5142. init_val=float(self.defaults['tools_transform_skew_y']))
  5143. num, ok = skewybox.get_value()
  5144. if ok:
  5145. # first get a bounding box to fit all
  5146. for obj in obj_list:
  5147. xmin, ymin, xmax, ymax = obj.bounds()
  5148. xminlist.append(xmin)
  5149. yminlist.append(ymin)
  5150. # get the minimum x,y and maximum x,y for all objects selected
  5151. xminimal = min(xminlist)
  5152. yminimal = min(yminlist)
  5153. for obj in obj_list:
  5154. obj.skew(0, num, point=(xminimal, yminimal))
  5155. obj.plot()
  5156. self.object_changed.emit(obj)
  5157. self.inform.emit('[success] %s' %
  5158. _("Skew on Y axis done."))
  5159. def on_plots_updated(self):
  5160. """
  5161. Callback used to report when the plots have changed.
  5162. Adjust axes and zooms to fit.
  5163. :return: None
  5164. """
  5165. if self.is_legacy is False:
  5166. self.plotcanvas.update()
  5167. else:
  5168. self.plotcanvas.auto_adjust_axes()
  5169. self.on_zoom_fit(None)
  5170. self.collection.update_view()
  5171. # self.inform.emit(_("Plots updated ..."))
  5172. def on_toolbar_replot(self):
  5173. """
  5174. Callback for toolbar button. Re-plots all objects.
  5175. :return: None
  5176. """
  5177. self.defaults.report_usage("on_toolbar_replot")
  5178. self.log.debug("on_toolbar_replot()")
  5179. try:
  5180. self.collection.get_active().read_form()
  5181. except AttributeError:
  5182. self.log.debug("on_toolbar_replot(): AttributeError")
  5183. pass
  5184. self.plot_all()
  5185. def on_row_activated(self, index):
  5186. if index.isValid():
  5187. if index.internalPointer().parent_item != self.collection.root_item:
  5188. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5189. self.collection.on_item_activated(index)
  5190. def on_row_selected(self, obj_name):
  5191. """
  5192. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5193. It mean we clicked outside of the items and deselected all
  5194. :param obj_name:
  5195. :return:
  5196. """
  5197. if obj_name == 'none':
  5198. for act in self.ui.menuobjects.actions():
  5199. act.setChecked(False)
  5200. return
  5201. # get the name of the selected objects and add them to a list
  5202. name_list = []
  5203. for obj in self.collection.get_selected():
  5204. name_list.append(obj.options['name'])
  5205. # set all actions as unchecked but the ones selected make them checked
  5206. for act in self.ui.menuobjects.actions():
  5207. act.setChecked(False)
  5208. if act.text() in name_list:
  5209. act.setChecked(True)
  5210. def on_collection_updated(self, obj, state, old_name):
  5211. """
  5212. Create a menu from the object loaded in the collection.
  5213. :param obj: object that was changed (added, deleted, renamed)
  5214. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5215. :param old_name: the old name of the object before the action that triggered this slot happened
  5216. :return: None
  5217. """
  5218. icon_files = {
  5219. "gerber": self.resource_location + "/flatcam_icon16.png",
  5220. "excellon": self.resource_location + "/drill16.png",
  5221. "cncjob": self.resource_location + "/cnc16.png",
  5222. "geometry": self.resource_location + "/geometry16.png",
  5223. "script": self.resource_location + "/script_new16.png",
  5224. "document": self.resource_location + "/notes16_1.png"
  5225. }
  5226. if state == 'append':
  5227. for act in self.ui.menuobjects.actions():
  5228. try:
  5229. act.triggered.disconnect()
  5230. except TypeError:
  5231. pass
  5232. self.ui.menuobjects.clear()
  5233. gerber_list = []
  5234. exc_list = []
  5235. cncjob_list = []
  5236. geo_list = []
  5237. script_list = []
  5238. doc_list = []
  5239. for name in self.collection.get_names():
  5240. obj_named = self.collection.get_by_name(name)
  5241. if obj_named.kind == 'gerber':
  5242. gerber_list.append(name)
  5243. elif obj_named.kind == 'excellon':
  5244. exc_list.append(name)
  5245. elif obj_named.kind == 'cncjob':
  5246. cncjob_list.append(name)
  5247. elif obj_named.kind == 'geometry':
  5248. geo_list.append(name)
  5249. elif obj_named.kind == 'script':
  5250. script_list.append(name)
  5251. elif obj_named.kind == 'document':
  5252. doc_list.append(name)
  5253. def add_act(o_name):
  5254. obj_for_icon = self.collection.get_by_name(o_name)
  5255. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5256. add_action.setCheckable(True)
  5257. add_action.setText(o_name)
  5258. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5259. add_action.triggered.connect(
  5260. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5261. self.collection.set_inactive(o_name))
  5262. self.ui.menuobjects.addAction(add_action)
  5263. for name in gerber_list:
  5264. add_act(name)
  5265. self.ui.menuobjects.addSeparator()
  5266. for name in exc_list:
  5267. add_act(name)
  5268. self.ui.menuobjects.addSeparator()
  5269. for name in cncjob_list:
  5270. add_act(name)
  5271. self.ui.menuobjects.addSeparator()
  5272. for name in geo_list:
  5273. add_act(name)
  5274. self.ui.menuobjects.addSeparator()
  5275. for name in script_list:
  5276. add_act(name)
  5277. self.ui.menuobjects.addSeparator()
  5278. for name in doc_list:
  5279. add_act(name)
  5280. self.ui.menuobjects.addSeparator()
  5281. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5282. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5283. _('Select All')
  5284. )
  5285. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5286. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5287. _('Deselect All')
  5288. )
  5289. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5290. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5291. elif state == 'delete':
  5292. for act in self.ui.menuobjects.actions():
  5293. if act.text() == obj.options['name']:
  5294. try:
  5295. act.triggered.disconnect()
  5296. except TypeError:
  5297. pass
  5298. self.ui.menuobjects.removeAction(act)
  5299. break
  5300. elif state == 'rename':
  5301. for act in self.ui.menuobjects.actions():
  5302. if act.text() == old_name:
  5303. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5304. add_action.setText(obj.options['name'])
  5305. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5306. add_action.triggered.connect(
  5307. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5308. self.collection.set_inactive(obj.options['name']))
  5309. self.ui.menuobjects.insertAction(act, add_action)
  5310. try:
  5311. act.triggered.disconnect()
  5312. except TypeError:
  5313. pass
  5314. self.ui.menuobjects.removeAction(act)
  5315. break
  5316. elif state == 'delete_all':
  5317. for act in self.ui.menuobjects.actions():
  5318. try:
  5319. act.triggered.disconnect()
  5320. except TypeError:
  5321. pass
  5322. self.ui.menuobjects.clear()
  5323. self.ui.menuobjects.addSeparator()
  5324. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5325. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5326. _('Select All')
  5327. )
  5328. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5329. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5330. _('Deselect All')
  5331. )
  5332. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5333. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5334. def on_objects_selection(self, on_off):
  5335. obj_list = self.collection.get_names()
  5336. if on_off is True:
  5337. self.collection.set_all_active()
  5338. for act in self.ui.menuobjects.actions():
  5339. try:
  5340. act.setChecked(True)
  5341. except Exception:
  5342. pass
  5343. if obj_list:
  5344. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5345. else:
  5346. self.collection.set_all_inactive()
  5347. for act in self.ui.menuobjects.actions():
  5348. try:
  5349. act.setChecked(False)
  5350. except Exception:
  5351. pass
  5352. if obj_list:
  5353. self.inform.emit('%s' % _("Objects selection is cleared."))
  5354. else:
  5355. self.inform.emit('')
  5356. def grid_status(self):
  5357. if self.ui.grid_snap_btn.isChecked():
  5358. return True
  5359. else:
  5360. return False
  5361. def populate_cmenu_grids(self):
  5362. units = self.defaults['units'].lower()
  5363. # for act in self.ui.cmenu_gridmenu.actions():
  5364. # act.triggered.disconnect()
  5365. self.ui.cmenu_gridmenu.clear()
  5366. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5367. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5368. _("Grid On/Off"))
  5369. grid_toggle.setCheckable(True)
  5370. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5371. self.ui.cmenu_gridmenu.addSeparator()
  5372. for grid in sorted_list:
  5373. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5374. "%s" % str(grid))
  5375. action.triggered.connect(self.set_grid)
  5376. self.ui.cmenu_gridmenu.addSeparator()
  5377. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5378. _("Add"))
  5379. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5380. _("Delete"))
  5381. grid_add.triggered.connect(self.on_grid_add)
  5382. grid_delete.triggered.connect(self.on_grid_delete)
  5383. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5384. def set_grid(self):
  5385. menu_action = self.sender()
  5386. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5387. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5388. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5389. def on_grid_add(self):
  5390. # ## Current application units in lower Case
  5391. units = self.defaults['units'].lower()
  5392. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5393. text=_('Enter a Grid Value:'),
  5394. min=0.0000, max=99.9999, decimals=4)
  5395. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5396. val, ok = grid_add_popup.get_value()
  5397. if ok:
  5398. if float(val) == 0:
  5399. self.inform.emit('[WARNING_NOTCL] %s' %
  5400. _("Please enter a grid value with non-zero value, in Float format."))
  5401. return
  5402. else:
  5403. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5404. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5405. self.inform.emit('[success] %s...' %
  5406. _("New Grid added"))
  5407. else:
  5408. self.inform.emit('[WARNING_NOTCL] %s...' %
  5409. _("Grid already exists"))
  5410. else:
  5411. self.inform.emit('[WARNING_NOTCL] %s...' %
  5412. _("Adding New Grid cancelled"))
  5413. def on_grid_delete(self):
  5414. # ## Current application units in lower Case
  5415. units = self.defaults['units'].lower()
  5416. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5417. text='Enter a Grid Value:',
  5418. min=0.0000, max=99.9999, decimals=4)
  5419. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5420. val, ok = grid_del_popup.get_value()
  5421. if ok:
  5422. if float(val) == 0:
  5423. self.inform.emit('[WARNING_NOTCL] %s' %
  5424. _("Please enter a grid value with non-zero value, in Float format."))
  5425. return
  5426. else:
  5427. try:
  5428. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5429. except ValueError:
  5430. self.inform.emit('[ERROR_NOTCL]%s...' %
  5431. _(" Grid Value does not exist"))
  5432. return
  5433. self.inform.emit('[success] %s...' %
  5434. _("Grid Value deleted"))
  5435. else:
  5436. self.inform.emit('[WARNING_NOTCL] %s...' %
  5437. _("Delete Grid value cancelled"))
  5438. def on_shortcut_list(self):
  5439. self.defaults.report_usage("on_shortcut_list()")
  5440. # add the tab if it was closed
  5441. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5442. # delete the absolute and relative position and messages in the infobar
  5443. self.ui.position_label.setText("")
  5444. self.ui.rel_position_label.setText("")
  5445. # Switch plot_area to preferences page
  5446. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5447. # self.ui.show()
  5448. def on_select_tab(self, name):
  5449. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5450. if self.ui.splitter.sizes()[0] == 0:
  5451. self.ui.splitter.setSizes([1, 1])
  5452. else:
  5453. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5454. self.ui.splitter.setSizes([0, 1])
  5455. if name == 'project':
  5456. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5457. elif name == 'selected':
  5458. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5459. elif name == 'tool':
  5460. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5461. def on_copy_name(self):
  5462. self.defaults.report_usage("on_copy_name()")
  5463. obj = self.collection.get_active()
  5464. try:
  5465. name = obj.options["name"]
  5466. except AttributeError:
  5467. log.debug("on_copy_name() --> No object selected to copy it's name")
  5468. self.inform.emit('[WARNING_NOTCL]%s' %
  5469. _(" No object selected to copy it's name"))
  5470. return
  5471. self.clipboard.setText(name)
  5472. self.inform.emit(_("Name copied on clipboard ..."))
  5473. def on_mouse_click_over_plot(self, event):
  5474. """
  5475. Default actions are:
  5476. :param event: Contains information about the event, like which button
  5477. was clicked, the pixel coordinates and the axes coordinates.
  5478. :return: None
  5479. """
  5480. self.pos = []
  5481. if self.is_legacy is False:
  5482. event_pos = event.pos
  5483. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5484. # # Set the mouse button for panning
  5485. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5486. else:
  5487. event_pos = (event.xdata, event.ydata)
  5488. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5489. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5490. # So it can receive key presses
  5491. self.plotcanvas.native.setFocus()
  5492. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5493. if self.grid_status():
  5494. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5495. else:
  5496. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5497. try:
  5498. if event.button == 1:
  5499. # Reset here the relative coordinates so there is a new reference on the click position
  5500. if self.rel_point1 is None:
  5501. self.rel_point1 = self.pos
  5502. else:
  5503. self.rel_point2 = copy(self.rel_point1)
  5504. self.rel_point1 = self.pos
  5505. self.on_mouse_move_over_plot(event, origin_click=True)
  5506. except Exception as e:
  5507. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5508. def on_mouse_double_click_over_plot(self, event):
  5509. if event.button == 1:
  5510. self.doubleclick = True
  5511. def on_mouse_move_over_plot(self, event, origin_click=None):
  5512. """
  5513. Callback for the mouse motion event over the plot.
  5514. :param event: Contains information about the event.
  5515. :param origin_click
  5516. :return: None
  5517. """
  5518. if self.is_legacy is False:
  5519. event_pos = event.pos
  5520. if self.defaults["global_pan_button"] == '2':
  5521. pan_button = 2
  5522. else:
  5523. pan_button = 3
  5524. self.event_is_dragging = event.is_dragging
  5525. else:
  5526. event_pos = (event.xdata, event.ydata)
  5527. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5528. if self.defaults["global_pan_button"] == '2':
  5529. pan_button = 3
  5530. else:
  5531. pan_button = 2
  5532. self.event_is_dragging = self.plotcanvas.is_dragging
  5533. # So it can receive key presses but not when the Tcl Shell is active
  5534. if not self.ui.shell_dock.isVisible():
  5535. if not self.plotcanvas.native.hasFocus():
  5536. self.plotcanvas.native.setFocus()
  5537. self.pos_jump = event_pos
  5538. self.ui.popMenu.mouse_is_panning = False
  5539. if origin_click is None:
  5540. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5541. if event.button == pan_button and self.event_is_dragging == 1:
  5542. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5543. if self.ui.popMenu.popup_active:
  5544. self.ui.popMenu.popup_active = False
  5545. return
  5546. self.ui.popMenu.mouse_is_panning = True
  5547. return
  5548. if self.rel_point1 is not None:
  5549. try: # May fail in case mouse not within axes
  5550. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5551. if pos_canvas[0] is None or pos_canvas[1] is None:
  5552. return
  5553. if self.grid_status():
  5554. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5555. # Update cursor
  5556. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5557. symbol='++', edge_color=self.cursor_color_3D,
  5558. edge_width=self.defaults["global_cursor_width"],
  5559. size=self.defaults["global_cursor_size"])
  5560. else:
  5561. pos = (pos_canvas[0], pos_canvas[1])
  5562. self.dx = pos[0] - float(self.rel_point1[0])
  5563. self.dy = pos[1] - float(self.rel_point1[1])
  5564. # self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5565. # "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5566. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5567. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5568. units = self.defaults["units"].lower()
  5569. self.plotcanvas.text_hud.text = \
  5570. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5571. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5572. self.mouse = [pos[0], pos[1]]
  5573. # if the mouse is moved and the LMB is clicked then the action is a selection
  5574. if self.event_is_dragging == 1 and event.button == 1:
  5575. self.delete_selection_shape()
  5576. if self.dx < 0:
  5577. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5578. face_color=self.defaults['global_alt_sel_fill'])
  5579. self.selection_type = False
  5580. elif self.dx >= 0:
  5581. self.draw_moving_selection_shape(self.pos, pos)
  5582. self.selection_type = True
  5583. else:
  5584. self.selection_type = None
  5585. else:
  5586. self.selection_type = None
  5587. # hover effect - enabled in Preferences -> General -> GUI Settings
  5588. if self.defaults['global_hover']:
  5589. for obj in self.collection.get_list():
  5590. try:
  5591. # select the object(s) only if it is enabled (plotted)
  5592. if obj.options['plot']:
  5593. if obj not in self.collection.get_selected():
  5594. poly_obj = Polygon(
  5595. [(obj.options['xmin'], obj.options['ymin']),
  5596. (obj.options['xmax'], obj.options['ymin']),
  5597. (obj.options['xmax'], obj.options['ymax']),
  5598. (obj.options['xmin'], obj.options['ymax'])]
  5599. )
  5600. if Point(pos).within(poly_obj):
  5601. if obj.isHovering is False:
  5602. obj.isHovering = True
  5603. obj.notHovering = True
  5604. # create the selection box around the selected object
  5605. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5606. else:
  5607. if obj.notHovering is True:
  5608. obj.notHovering = False
  5609. obj.isHovering = False
  5610. self.delete_hover_shape()
  5611. except Exception:
  5612. # the Exception here will happen if we try to select on screen and we have an
  5613. # newly (and empty) just created Geometry or Excellon object that do not have the
  5614. # xmin, xmax, ymin, ymax options.
  5615. # In this case poly_obj creation (see above) will fail
  5616. pass
  5617. except Exception as e:
  5618. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5619. # self.ui.position_label.setText("")
  5620. # self.ui.rel_position_label.setText("")
  5621. self.mouse = None
  5622. def on_mouse_click_release_over_plot(self, event):
  5623. """
  5624. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5625. and has been registered in ''self.__init__()''.
  5626. :param event: contains information about the event.
  5627. :return:
  5628. """
  5629. if self.is_legacy is False:
  5630. event_pos = event.pos
  5631. right_button = 2
  5632. else:
  5633. event_pos = (event.xdata, event.ydata)
  5634. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5635. right_button = 3
  5636. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5637. if self.grid_status():
  5638. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5639. else:
  5640. pos = (pos_canvas[0], pos_canvas[1])
  5641. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5642. # canvas menu
  5643. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5644. self.ui.popMenu.mouse_is_panning = False
  5645. self.cursor = QtGui.QCursor()
  5646. self.populate_cmenu_grids()
  5647. self.ui.popMenu.popup(self.cursor.pos())
  5648. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5649. # selection and then select a type of selection ("enclosing" or "touching")
  5650. if event.button == 1: # left click
  5651. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5652. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5653. if modifiers == QtCore.Qt.ShiftModifier:
  5654. # do not auto open the Project Tab
  5655. self.click_noproject = True
  5656. self.clipboard.setText(
  5657. self.defaults["global_point_clipboard_format"] %
  5658. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5659. )
  5660. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5661. return
  5662. if self.doubleclick is True:
  5663. self.doubleclick = False
  5664. if self.collection.get_selected():
  5665. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5666. if self.ui.splitter.sizes()[0] == 0:
  5667. self.ui.splitter.setSizes([1, 1])
  5668. try:
  5669. # delete the selection shape(S) as it may be in the way
  5670. self.delete_selection_shape()
  5671. self.delete_hover_shape()
  5672. except Exception as e:
  5673. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5674. return
  5675. else:
  5676. # WORKAROUND for LEGACY MODE
  5677. if self.is_legacy is True:
  5678. # if there is no move on canvas then we have no dragging selection
  5679. if self.dx == 0 or self.dy == 0:
  5680. self.selection_type = None
  5681. if self.selection_type is not None:
  5682. try:
  5683. self.selection_area_handler(self.pos, pos, self.selection_type)
  5684. self.selection_type = None
  5685. except Exception as e:
  5686. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5687. return
  5688. else:
  5689. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5690. if key_modifier == QtCore.Qt.ShiftModifier:
  5691. mod_key = 'Shift'
  5692. elif key_modifier == QtCore.Qt.ControlModifier:
  5693. mod_key = 'Control'
  5694. else:
  5695. mod_key = None
  5696. try:
  5697. if self.command_active is None:
  5698. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5699. # deselect, and if it's not selected then it will be selected
  5700. # If there is no active command (self.command_active is None) then we check if we clicked
  5701. # on a object by checking the bounding limits against mouse click position
  5702. if mod_key == self.defaults["global_mselect_key"]:
  5703. self.select_objects(key='multisel')
  5704. else:
  5705. # If there is no active command (self.command_active is None) then we check if
  5706. # we clicked on a object by checking the bounding limits against mouse click position
  5707. self.select_objects()
  5708. self.delete_hover_shape()
  5709. except Exception as e:
  5710. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5711. return
  5712. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5713. """
  5714. :param start_pos: mouse position when the selection LMB click was done
  5715. :param end_pos: mouse position when the left mouse button is released
  5716. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5717. :return:
  5718. """
  5719. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5720. # delete previous selection shape
  5721. self.delete_selection_shape()
  5722. # make all objects inactive
  5723. self.collection.set_all_inactive()
  5724. for obj in self.collection.get_list():
  5725. try:
  5726. # select the object(s) only if it is enabled (plotted)
  5727. if obj.options['plot']:
  5728. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5729. (obj.options['xmax'], obj.options['ymin']),
  5730. (obj.options['xmax'], obj.options['ymax']),
  5731. (obj.options['xmin'], obj.options['ymax'])])
  5732. if sel_type is True:
  5733. if poly_obj.within(poly_selection):
  5734. # create the selection box around the selected object
  5735. if self.defaults['global_selection_shape'] is True:
  5736. self.draw_selection_shape(obj)
  5737. self.collection.set_active(obj.options['name'])
  5738. else:
  5739. if poly_selection.intersects(poly_obj):
  5740. # create the selection box around the selected object
  5741. if self.defaults['global_selection_shape'] is True:
  5742. self.draw_selection_shape(obj)
  5743. self.collection.set_active(obj.options['name'])
  5744. obj.selection_shape_drawn = True
  5745. except Exception as e:
  5746. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5747. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5748. # In this case poly_obj creation (see above) will fail
  5749. log.debug("App.selection_area_handler() --> %s" % str(e))
  5750. def select_objects(self, key=None):
  5751. """
  5752. Will select objects clicked on canvas
  5753. :param key: for future use in cumulative selection
  5754. :return:
  5755. """
  5756. # list where we store the overlapped objects under our mouse left click position
  5757. if key is None:
  5758. self.objects_under_the_click_list = []
  5759. # Populate the list with the overlapped objects on the click position
  5760. curr_x, curr_y = self.pos
  5761. for obj in self.all_objects_list:
  5762. # ScriptObject and DocumentObject objects can't be selected
  5763. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5764. continue
  5765. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5766. continue
  5767. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5768. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5769. if obj.options['name'] not in self.objects_under_the_click_list:
  5770. if obj.options['plot']:
  5771. # add objects to the objects_under_the_click list only if the object is plotted
  5772. # (active and not disabled)
  5773. self.objects_under_the_click_list.append(obj.options['name'])
  5774. try:
  5775. if self.objects_under_the_click_list:
  5776. curr_sel_obj = self.collection.get_active()
  5777. # case when there is only an object under the click and we toggle it
  5778. if len(self.objects_under_the_click_list) == 1:
  5779. if curr_sel_obj is None:
  5780. self.collection.set_active(self.objects_under_the_click_list[0])
  5781. curr_sel_obj = self.collection.get_active()
  5782. # create the selection box around the selected object
  5783. if self.defaults['global_selection_shape'] is True:
  5784. self.draw_selection_shape(curr_sel_obj)
  5785. curr_sel_obj.selection_shape_drawn = True
  5786. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5787. self.on_objects_selection(False)
  5788. self.delete_selection_shape()
  5789. curr_sel_obj.selection_shape_drawn = False
  5790. self.collection.set_active(self.objects_under_the_click_list[0])
  5791. curr_sel_obj = self.collection.get_active()
  5792. # create the selection box around the selected object
  5793. if self.defaults['global_selection_shape'] is True:
  5794. self.draw_selection_shape(curr_sel_obj)
  5795. curr_sel_obj.selection_shape_drawn = True
  5796. self.selected_message(curr_sel_obj=curr_sel_obj)
  5797. elif curr_sel_obj.selection_shape_drawn is False:
  5798. if self.defaults['global_selection_shape'] is True:
  5799. self.draw_selection_shape(curr_sel_obj)
  5800. curr_sel_obj.selection_shape_drawn = True
  5801. else:
  5802. self.on_objects_selection(False)
  5803. self.delete_selection_shape()
  5804. if self.call_source != 'app':
  5805. self.call_source = 'app'
  5806. self.selected_message(curr_sel_obj=curr_sel_obj)
  5807. else:
  5808. # If there is no selected object
  5809. # make active the first element of the overlapped objects list
  5810. if self.collection.get_active() is None:
  5811. self.collection.set_active(self.objects_under_the_click_list[0])
  5812. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5813. name_sel_obj = self.collection.get_active().options['name']
  5814. # In case that there is a selected object but it is not in the overlapped object list
  5815. # make that object inactive and activate the first element in the overlapped object list
  5816. if name_sel_obj not in self.objects_under_the_click_list:
  5817. self.collection.set_inactive(name_sel_obj)
  5818. name_sel_obj = self.objects_under_the_click_list[0]
  5819. self.collection.set_active(name_sel_obj)
  5820. else:
  5821. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5822. self.collection.set_all_inactive()
  5823. self.collection.set_active(
  5824. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5825. curr_sel_obj = self.collection.get_active()
  5826. # delete the possible selection box around a possible selected object
  5827. self.delete_selection_shape()
  5828. curr_sel_obj.selection_shape_drawn = False
  5829. # create the selection box around the selected object
  5830. if self.defaults['global_selection_shape'] is True:
  5831. self.draw_selection_shape(curr_sel_obj)
  5832. curr_sel_obj.selection_shape_drawn = True
  5833. self.selected_message(curr_sel_obj=curr_sel_obj)
  5834. else:
  5835. # deselect everything
  5836. self.on_objects_selection(False)
  5837. # delete the possible selection box around a possible selected object
  5838. self.delete_selection_shape()
  5839. for o in self.collection.get_list():
  5840. o.selection_shape_drawn = False
  5841. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5842. # only when working on App
  5843. if self.call_source == 'app':
  5844. if self.click_noproject is False:
  5845. # if the Tool Tab is in focus don't change focus to Project Tab
  5846. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5847. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5848. else:
  5849. # restore auto open the Project Tab
  5850. self.click_noproject = False
  5851. # delete any text in the status bar, implicitly the last object name that was selected
  5852. # self.inform.emit("")
  5853. else:
  5854. self.call_source = 'app'
  5855. except Exception as e:
  5856. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5857. def selected_message(self, curr_sel_obj):
  5858. if curr_sel_obj:
  5859. if curr_sel_obj.kind == 'gerber':
  5860. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5861. color='green',
  5862. name=str(curr_sel_obj.options['name']),
  5863. tx=_("selected"))
  5864. )
  5865. elif curr_sel_obj.kind == 'excellon':
  5866. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5867. color='brown',
  5868. name=str(curr_sel_obj.options['name']),
  5869. tx=_("selected"))
  5870. )
  5871. elif curr_sel_obj.kind == 'cncjob':
  5872. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5873. color='blue',
  5874. name=str(curr_sel_obj.options['name']),
  5875. tx=_("selected"))
  5876. )
  5877. elif curr_sel_obj.kind == 'geometry':
  5878. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5879. color='red',
  5880. name=str(curr_sel_obj.options['name']),
  5881. tx=_("selected"))
  5882. )
  5883. def delete_hover_shape(self):
  5884. self.hover_shapes.clear()
  5885. self.hover_shapes.redraw()
  5886. def draw_hover_shape(self, sel_obj, color=None):
  5887. """
  5888. :param sel_obj: The object for which the hover shape must be drawn
  5889. :param color: The color of the hover shape
  5890. :return: None
  5891. """
  5892. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5893. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5894. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5895. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5896. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5897. if self.defaults['units'].upper() == 'MM':
  5898. hover_rect = hover_rect.buffer(-0.1)
  5899. hover_rect = hover_rect.buffer(0.2)
  5900. else:
  5901. hover_rect = hover_rect.buffer(-0.00393)
  5902. hover_rect = hover_rect.buffer(0.00787)
  5903. # if color:
  5904. # face = Color(color)
  5905. # face.alpha = 0.2
  5906. # outline = Color(color, alpha=0.8)
  5907. # else:
  5908. # face = Color(self.defaults['global_sel_fill'])
  5909. # face.alpha = 0.2
  5910. # outline = self.defaults['global_sel_line']
  5911. if color:
  5912. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5913. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5914. else:
  5915. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5916. outline = self.defaults['global_sel_line']
  5917. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5918. if self.is_legacy is True:
  5919. self.hover_shapes.redraw()
  5920. def delete_selection_shape(self):
  5921. self.move_tool.sel_shapes.clear()
  5922. self.move_tool.sel_shapes.redraw()
  5923. def draw_selection_shape(self, sel_obj, color=None):
  5924. """
  5925. Will draw a selection shape around the selected object.
  5926. :param sel_obj: The object for which the selection shape must be drawn
  5927. :param color: The color for the selection shape.
  5928. :return: None
  5929. """
  5930. if sel_obj is None:
  5931. return
  5932. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5933. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5934. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5935. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5936. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5937. if self.defaults['units'].upper() == 'MM':
  5938. sel_rect = sel_rect.buffer(-0.1)
  5939. sel_rect = sel_rect.buffer(0.2)
  5940. else:
  5941. sel_rect = sel_rect.buffer(-0.00393)
  5942. sel_rect = sel_rect.buffer(0.00787)
  5943. if color:
  5944. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5945. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5946. else:
  5947. if self.is_legacy is False:
  5948. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5949. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5950. else:
  5951. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5952. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5953. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5954. color=outline,
  5955. face_color=face,
  5956. update=True,
  5957. layer=0,
  5958. tolerance=None))
  5959. if self.is_legacy is True:
  5960. self.move_tool.sel_shapes.redraw()
  5961. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5962. """
  5963. Will draw a selection shape when dragging mouse on canvas.
  5964. :param old_coords: Old coordinates
  5965. :param coords: New coordinates
  5966. :param kwargs: Keyword arguments
  5967. :return:
  5968. """
  5969. if 'color' in kwargs:
  5970. color = kwargs['color']
  5971. else:
  5972. color = self.defaults['global_sel_line']
  5973. if 'face_color' in kwargs:
  5974. face_color = kwargs['face_color']
  5975. else:
  5976. face_color = self.defaults['global_sel_fill']
  5977. if 'face_alpha' in kwargs:
  5978. face_alpha = kwargs['face_alpha']
  5979. else:
  5980. face_alpha = 0.3
  5981. x0, y0 = old_coords
  5982. x1, y1 = coords
  5983. pt1 = (x0, y0)
  5984. pt2 = (x1, y0)
  5985. pt3 = (x1, y1)
  5986. pt4 = (x0, y1)
  5987. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5988. # color_t = Color(face_color)
  5989. # color_t.alpha = face_alpha
  5990. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5991. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5992. layer=0, tolerance=None)
  5993. if self.is_legacy is True:
  5994. self.move_tool.sel_shapes.redraw()
  5995. def on_file_new_click(self):
  5996. """
  5997. Callback for menu item File -> New.
  5998. Executed on clicking the Menu -> File -> New Project
  5999. :return:
  6000. """
  6001. if self.collection.get_list() and self.should_we_save:
  6002. msgbox = QtWidgets.QMessageBox()
  6003. # msgbox.setText("<B>Save changes ...</B>")
  6004. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6005. "Creating a New project will delete them.\n"
  6006. "Do you want to Save the project?"))
  6007. msgbox.setWindowTitle(_("Save changes"))
  6008. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6009. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6010. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6011. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6012. msgbox.setDefaultButton(bt_yes)
  6013. msgbox.exec_()
  6014. response = msgbox.clickedButton()
  6015. if response == bt_yes:
  6016. self.on_file_saveprojectas()
  6017. elif response == bt_cancel:
  6018. return
  6019. elif response == bt_no:
  6020. self.on_file_new()
  6021. else:
  6022. self.on_file_new()
  6023. self.inform.emit('[success] %s...' % _("New Project created"))
  6024. def on_file_new(self, cli=None):
  6025. """
  6026. Returns the application to its startup state. This method is thread-safe.
  6027. :param cli: Boolean. If True this method was run from command line
  6028. :return: None
  6029. """
  6030. self.defaults.report_usage("on_file_new")
  6031. # Remove everything from memory
  6032. App.log.debug("on_file_new()")
  6033. # close any editor that might be open
  6034. if self.call_source != 'app':
  6035. self.editor2object(cleanup=True)
  6036. # ## EDITOR section
  6037. self.geo_editor = FlatCAMGeoEditor(self)
  6038. self.exc_editor = FlatCAMExcEditor(self)
  6039. self.grb_editor = FlatCAMGrbEditor(self)
  6040. # Clear pool
  6041. self.clear_pool()
  6042. for obj in self.collection.get_list():
  6043. # delete shapes left drawn from mark shape_collections, if any
  6044. if isinstance(obj, GerberObject):
  6045. try:
  6046. for el in obj.mark_shapes:
  6047. obj.mark_shapes[el].clear(update=True)
  6048. obj.mark_shapes[el].enabled = False
  6049. del el
  6050. except AttributeError:
  6051. pass
  6052. # also delete annotation shapes, if any
  6053. elif isinstance(obj, CNCJobObject):
  6054. try:
  6055. obj.text_col.enabled = False
  6056. del obj.text_col
  6057. obj.annotation.clear(update=True)
  6058. del obj.annotation
  6059. except AttributeError:
  6060. pass
  6061. # delete the exclusion areas
  6062. self.exc_areas.clear_shapes()
  6063. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6064. self.shell.init_tcl()
  6065. # delete any selection shape on canvas
  6066. self.delete_selection_shape()
  6067. # delete all FlatCAM objects
  6068. self.collection.delete_all()
  6069. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  6070. self.setup_component_editor()
  6071. # Clear project filename
  6072. self.project_filename = None
  6073. # Load the application defaults
  6074. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6075. # Re-fresh project options
  6076. self.on_options_app2project()
  6077. # Init FlatCAMTools
  6078. self.init_tools()
  6079. # Try to close all tabs in the PlotArea but only if the GUI is active (CLI is None)
  6080. if cli is None:
  6081. # we need to go in reverse because once we remove a tab then the index changes
  6082. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  6083. # and so on. Therefore the deletion should be done in reverse
  6084. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  6085. for index in range(wdg_count, -1, -1):
  6086. try:
  6087. self.ui.plot_tab_area.closeTab(index)
  6088. except Exception as e:
  6089. log.debug("App.on_file_new() --> %s" % str(e))
  6090. # # And then add again the Plot Area
  6091. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  6092. self.ui.plot_tab_area.protectTab(0)
  6093. # take the focus of the Notebook on Project Tab.
  6094. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6095. self.set_ui_title(name=_("New Project - Not saved"))
  6096. def obj_properties(self):
  6097. """
  6098. Will launch the object Properties Tool
  6099. :return:
  6100. """
  6101. self.defaults.report_usage("obj_properties()")
  6102. self.properties_tool.run(toggle=False)
  6103. def on_project_context_save(self):
  6104. """
  6105. Wrapper, will save the object function of it's type
  6106. :return:
  6107. """
  6108. obj = self.collection.get_active()
  6109. if type(obj) == GeometryObject:
  6110. self.on_file_exportdxf()
  6111. elif type(obj) == ExcellonObject:
  6112. self.on_file_saveexcellon()
  6113. elif type(obj) == CNCJobObject:
  6114. obj.on_exportgcode_button_click()
  6115. elif type(obj) == GerberObject:
  6116. self.on_file_savegerber()
  6117. elif type(obj) == ScriptObject:
  6118. self.on_file_savescript()
  6119. elif type(obj) == DocumentObject:
  6120. self.on_file_savedocument()
  6121. def obj_move(self):
  6122. """
  6123. Callback for the Move menu entry in various Context Menu's.
  6124. :return:
  6125. """
  6126. self.defaults.report_usage("obj_move()")
  6127. self.move_tool.run(toggle=False)
  6128. def on_fileopengerber(self, signal, name=None):
  6129. """
  6130. File menu callback for opening a Gerber.
  6131. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6132. :param name:
  6133. :return: None
  6134. """
  6135. self.defaults.report_usage("on_fileopengerber")
  6136. App.log.debug("on_fileopengerber()")
  6137. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6138. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6139. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6140. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6141. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6142. "*.mil);;" \
  6143. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6144. "Allegro Files (*.art);;" \
  6145. "Mentor Files (*.pho *.gdo);;" \
  6146. "All Files (*.*)"
  6147. if name is None:
  6148. try:
  6149. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6150. directory=self.get_last_folder(),
  6151. filter=_filter_)
  6152. except TypeError:
  6153. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6154. filenames = [str(filename) for filename in filenames]
  6155. else:
  6156. filenames = [name]
  6157. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6158. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6159. _("Opening Gerber file.")),
  6160. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6161. color=QtGui.QColor("gray"))
  6162. if len(filenames) == 0:
  6163. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6164. else:
  6165. for filename in filenames:
  6166. if filename != '':
  6167. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6168. def on_fileopenexcellon(self, signal, name=None):
  6169. """
  6170. File menu callback for opening an Excellon file.
  6171. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6172. :param name:
  6173. :return: None
  6174. """
  6175. self.defaults.report_usage("on_fileopenexcellon")
  6176. App.log.debug("on_fileopenexcellon()")
  6177. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6178. "All Files (*.*)"
  6179. if name is None:
  6180. try:
  6181. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6182. directory=self.get_last_folder(),
  6183. filter=_filter_)
  6184. except TypeError:
  6185. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6186. filenames = [str(filename) for filename in filenames]
  6187. else:
  6188. filenames = [str(name)]
  6189. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6190. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6191. _("Opening Excellon file.")),
  6192. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6193. color=QtGui.QColor("gray"))
  6194. if len(filenames) == 0:
  6195. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6196. else:
  6197. for filename in filenames:
  6198. if filename != '':
  6199. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6200. def on_fileopengcode(self, signal, name=None):
  6201. """
  6202. File menu call back for opening gcode.
  6203. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6204. :param name:
  6205. :return:
  6206. """
  6207. self.defaults.report_usage("on_fileopengcode")
  6208. App.log.debug("on_fileopengcode()")
  6209. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6210. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6211. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6212. "All Files (*.*)"
  6213. if name is None:
  6214. try:
  6215. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6216. directory=self.get_last_folder(),
  6217. filter=_filter_)
  6218. except TypeError:
  6219. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6220. filenames = [str(filename) for filename in filenames]
  6221. else:
  6222. filenames = [name]
  6223. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6224. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6225. _("Opening G-Code file.")),
  6226. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6227. color=QtGui.QColor("gray"))
  6228. if len(filenames) == 0:
  6229. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6230. else:
  6231. for filename in filenames:
  6232. if filename != '':
  6233. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6234. def on_file_openproject(self, signal):
  6235. """
  6236. File menu callback for opening a project.
  6237. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6238. :return: None
  6239. """
  6240. self.defaults.report_usage("on_file_openproject")
  6241. App.log.debug("on_file_openproject()")
  6242. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6243. try:
  6244. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6245. directory=self.get_last_folder(), filter=_filter_)
  6246. except TypeError:
  6247. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6248. # The Qt methods above will return a QString which can cause problems later.
  6249. # So far json.dump() will fail to serialize it.
  6250. # TODO: Improve the serialization methods and remove this fix.
  6251. filename = str(filename)
  6252. if filename == "":
  6253. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6254. else:
  6255. # self.worker_task.emit({'fcn': self.open_project,
  6256. # 'params': [filename]})
  6257. # The above was failing because open_project() is not
  6258. # thread safe. The new_project()
  6259. self.open_project(filename)
  6260. def on_fileopenhpgl2(self, signal, name=None):
  6261. """
  6262. File menu callback for opening a HPGL2.
  6263. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6264. :param name:
  6265. :return: None
  6266. """
  6267. self.defaults.report_usage("on_fileopenhpgl2")
  6268. App.log.debug("on_fileopenhpgl2()")
  6269. _filter_ = "HPGL2 Files (*.plt);;" \
  6270. "All Files (*.*)"
  6271. if name is None:
  6272. try:
  6273. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6274. directory=self.get_last_folder(),
  6275. filter=_filter_)
  6276. except TypeError:
  6277. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6278. filenames = [str(filename) for filename in filenames]
  6279. else:
  6280. filenames = [name]
  6281. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6282. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6283. _("Opening HPGL2 file.")),
  6284. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6285. color=QtGui.QColor("gray"))
  6286. if len(filenames) == 0:
  6287. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6288. else:
  6289. for filename in filenames:
  6290. if filename != '':
  6291. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6292. def on_file_openconfig(self, signal):
  6293. """
  6294. File menu callback for opening a config file.
  6295. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6296. :return: None
  6297. """
  6298. self.defaults.report_usage("on_file_openconfig")
  6299. App.log.debug("on_file_openconfig()")
  6300. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6301. try:
  6302. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6303. directory=self.data_path, filter=_filter_)
  6304. except TypeError:
  6305. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6306. filter=_filter_)
  6307. if filename == "":
  6308. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6309. else:
  6310. self.open_config_file(filename)
  6311. def on_file_exportsvg(self):
  6312. """
  6313. Callback for menu item File->Export SVG.
  6314. :return: None
  6315. """
  6316. self.defaults.report_usage("on_file_exportsvg")
  6317. App.log.debug("on_file_exportsvg()")
  6318. obj = self.collection.get_active()
  6319. if obj is None:
  6320. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6321. msg = _("Please Select a Geometry object to export")
  6322. msgbox = QtWidgets.QMessageBox()
  6323. msgbox.setInformativeText(msg)
  6324. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6325. msgbox.setDefaultButton(bt_ok)
  6326. msgbox.exec_()
  6327. return
  6328. # Check for more compatible types and add as required
  6329. if (not isinstance(obj, GeometryObject)
  6330. and not isinstance(obj, GerberObject)
  6331. and not isinstance(obj, CNCJobObject)
  6332. and not isinstance(obj, ExcellonObject)):
  6333. msg = '[ERROR_NOTCL] %s' % \
  6334. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6335. msgbox = QtWidgets.QMessageBox()
  6336. msgbox.setInformativeText(msg)
  6337. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6338. msgbox.setDefaultButton(bt_ok)
  6339. msgbox.exec_()
  6340. return
  6341. name = obj.options["name"]
  6342. _filter = "SVG File (*.svg);;All Files (*.*)"
  6343. try:
  6344. filename, _f = FCFileSaveDialog.get_saved_filename(
  6345. caption=_("Export SVG"),
  6346. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6347. filter=_filter)
  6348. except TypeError:
  6349. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6350. filename = str(filename)
  6351. if filename == "":
  6352. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6353. return
  6354. else:
  6355. self.export_svg(name, filename)
  6356. if self.defaults["global_open_style"] is False:
  6357. self.file_opened.emit("SVG", filename)
  6358. self.file_saved.emit("SVG", filename)
  6359. def on_file_exportpng(self):
  6360. self.defaults.report_usage("on_file_exportpng")
  6361. App.log.debug("on_file_exportpng()")
  6362. self.date = str(datetime.today()).rpartition('.')[0]
  6363. self.date = ''.join(c for c in self.date if c not in ':-')
  6364. self.date = self.date.replace(' ', '_')
  6365. if self.is_legacy is False:
  6366. image = _screenshot()
  6367. data = np.asarray(image)
  6368. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6369. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6370. return
  6371. filter_ = "PNG File (*.png);;All Files (*.*)"
  6372. try:
  6373. filename, _f = FCFileSaveDialog.get_saved_filename(
  6374. caption=_("Export PNG Image"),
  6375. directory=self.get_last_save_folder() + '/png_' + self.date,
  6376. filter=filter_)
  6377. except TypeError:
  6378. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6379. filename = str(filename)
  6380. if filename == "":
  6381. self.inform.emit(_("Cancelled."))
  6382. return
  6383. else:
  6384. if self.is_legacy is False:
  6385. write_png(filename, data)
  6386. else:
  6387. self.plotcanvas.figure.savefig(filename)
  6388. if self.defaults["global_open_style"] is False:
  6389. self.file_opened.emit("png", filename)
  6390. self.file_saved.emit("png", filename)
  6391. def on_file_savegerber(self):
  6392. """
  6393. Callback for menu item in Project context menu.
  6394. :return: None
  6395. """
  6396. self.defaults.report_usage("on_file_savegerber")
  6397. App.log.debug("on_file_savegerber()")
  6398. obj = self.collection.get_active()
  6399. if obj is None:
  6400. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6401. return
  6402. # Check for more compatible types and add as required
  6403. if not isinstance(obj, GerberObject):
  6404. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6405. return
  6406. name = self.collection.get_active().options["name"]
  6407. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6408. try:
  6409. filename, _f = FCFileSaveDialog.get_saved_filename(
  6410. caption="Save Gerber source file",
  6411. directory=self.get_last_save_folder() + '/' + name,
  6412. filter=_filter)
  6413. except TypeError:
  6414. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6415. filename = str(filename)
  6416. if filename == "":
  6417. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6418. return
  6419. else:
  6420. self.save_source_file(name, filename)
  6421. if self.defaults["global_open_style"] is False:
  6422. self.file_opened.emit("Gerber", filename)
  6423. self.file_saved.emit("Gerber", filename)
  6424. def on_file_savescript(self):
  6425. """
  6426. Callback for menu item in Project context menu.
  6427. :return: None
  6428. """
  6429. self.defaults.report_usage("on_file_savescript")
  6430. App.log.debug("on_file_savescript()")
  6431. obj = self.collection.get_active()
  6432. if obj is None:
  6433. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6434. return
  6435. # Check for more compatible types and add as required
  6436. if not isinstance(obj, ScriptObject):
  6437. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6438. return
  6439. name = self.collection.get_active().options["name"]
  6440. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6441. try:
  6442. filename, _f = FCFileSaveDialog.get_saved_filename(
  6443. caption="Save Script source file",
  6444. directory=self.get_last_save_folder() + '/' + name,
  6445. filter=_filter)
  6446. except TypeError:
  6447. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6448. filename = str(filename)
  6449. if filename == "":
  6450. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6451. return
  6452. else:
  6453. self.save_source_file(name, filename)
  6454. if self.defaults["global_open_style"] is False:
  6455. self.file_opened.emit("Script", filename)
  6456. self.file_saved.emit("Script", filename)
  6457. def on_file_savedocument(self):
  6458. """
  6459. Callback for menu item in Project context menu.
  6460. :return: None
  6461. """
  6462. self.defaults.report_usage("on_file_savedocument")
  6463. App.log.debug("on_file_savedocument()")
  6464. obj = self.collection.get_active()
  6465. if obj is None:
  6466. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6467. return
  6468. # Check for more compatible types and add as required
  6469. if not isinstance(obj, ScriptObject):
  6470. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6471. return
  6472. name = self.collection.get_active().options["name"]
  6473. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6474. try:
  6475. filename, _f = FCFileSaveDialog.get_saved_filename(
  6476. caption="Save Document source file",
  6477. directory=self.get_last_save_folder() + '/' + name,
  6478. filter=_filter)
  6479. except TypeError:
  6480. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6481. filename = str(filename)
  6482. if filename == "":
  6483. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6484. return
  6485. else:
  6486. self.save_source_file(name, filename)
  6487. if self.defaults["global_open_style"] is False:
  6488. self.file_opened.emit("Document", filename)
  6489. self.file_saved.emit("Document", filename)
  6490. def on_file_saveexcellon(self):
  6491. """
  6492. Callback for menu item in project context menu.
  6493. :return: None
  6494. """
  6495. self.defaults.report_usage("on_file_saveexcellon")
  6496. App.log.debug("on_file_saveexcellon()")
  6497. obj = self.collection.get_active()
  6498. if obj is None:
  6499. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6500. return
  6501. # Check for more compatible types and add as required
  6502. if not isinstance(obj, ExcellonObject):
  6503. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6504. return
  6505. name = self.collection.get_active().options["name"]
  6506. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6507. try:
  6508. filename, _f = FCFileSaveDialog.get_saved_filename(
  6509. caption=_("Save Excellon source file"),
  6510. directory=self.get_last_save_folder() + '/' + name,
  6511. filter=_filter)
  6512. except TypeError:
  6513. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6514. filename = str(filename)
  6515. if filename == "":
  6516. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6517. return
  6518. else:
  6519. self.save_source_file(name, filename)
  6520. if self.defaults["global_open_style"] is False:
  6521. self.file_opened.emit("Excellon", filename)
  6522. self.file_saved.emit("Excellon", filename)
  6523. def on_file_exportexcellon(self):
  6524. """
  6525. Callback for menu item File->Export->Excellon.
  6526. :return: None
  6527. """
  6528. self.defaults.report_usage("on_file_exportexcellon")
  6529. App.log.debug("on_file_exportexcellon()")
  6530. obj = self.collection.get_active()
  6531. if obj is None:
  6532. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6533. return
  6534. # Check for more compatible types and add as required
  6535. if not isinstance(obj, ExcellonObject):
  6536. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6537. return
  6538. name = self.collection.get_active().options["name"]
  6539. _filter = self.defaults["excellon_save_filters"]
  6540. try:
  6541. filename, _f = FCFileSaveDialog.get_saved_filename(
  6542. caption=_("Export Excellon"),
  6543. directory=self.get_last_save_folder() + '/' + name,
  6544. filter=_filter)
  6545. except TypeError:
  6546. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6547. filename = str(filename)
  6548. if filename == "":
  6549. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6550. return
  6551. else:
  6552. used_extension = filename.rpartition('.')[2]
  6553. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6554. self.export_excellon(name, filename)
  6555. if self.defaults["global_open_style"] is False:
  6556. self.file_opened.emit("Excellon", filename)
  6557. self.file_saved.emit("Excellon", filename)
  6558. def on_file_exportgerber(self):
  6559. """
  6560. Callback for menu item File->Export->Gerber.
  6561. :return: None
  6562. """
  6563. self.defaults.report_usage("on_file_exportgerber")
  6564. App.log.debug("on_file_exportgerber()")
  6565. obj = self.collection.get_active()
  6566. if obj is None:
  6567. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6568. return
  6569. # Check for more compatible types and add as required
  6570. if not isinstance(obj, GerberObject):
  6571. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6572. return
  6573. name = self.collection.get_active().options["name"]
  6574. _filter_ = self.defaults['gerber_save_filters']
  6575. try:
  6576. filename, _f = FCFileSaveDialog.get_saved_filename(
  6577. caption=_("Export Gerber"),
  6578. directory=self.get_last_save_folder() + '/' + name,
  6579. filter=_filter_)
  6580. except TypeError:
  6581. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6582. filename = str(filename)
  6583. if filename == "":
  6584. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6585. return
  6586. else:
  6587. used_extension = filename.rpartition('.')[2]
  6588. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6589. self.export_gerber(name, filename)
  6590. if self.defaults["global_open_style"] is False:
  6591. self.file_opened.emit("Gerber", filename)
  6592. self.file_saved.emit("Gerber", filename)
  6593. def on_file_exportdxf(self):
  6594. """
  6595. Callback for menu item File->Export DXF.
  6596. :return: None
  6597. """
  6598. self.defaults.report_usage("on_file_exportdxf")
  6599. App.log.debug("on_file_exportdxf()")
  6600. obj = self.collection.get_active()
  6601. if obj is None:
  6602. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6603. msg = _("Please Select a Geometry object to export")
  6604. msgbox = QtWidgets.QMessageBox()
  6605. msgbox.setInformativeText(msg)
  6606. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6607. msgbox.setDefaultButton(bt_ok)
  6608. msgbox.exec_()
  6609. return
  6610. # Check for more compatible types and add as required
  6611. if not isinstance(obj, GeometryObject):
  6612. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6613. msgbox = QtWidgets.QMessageBox()
  6614. msgbox.setInformativeText(msg)
  6615. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6616. msgbox.setDefaultButton(bt_ok)
  6617. msgbox.exec_()
  6618. return
  6619. name = self.collection.get_active().options["name"]
  6620. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6621. try:
  6622. filename, _f = FCFileSaveDialog.get_saved_filename(
  6623. caption=_("Export DXF"),
  6624. directory=self.get_last_save_folder() + '/' + name,
  6625. filter=_filter_)
  6626. except TypeError:
  6627. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6628. filename = str(filename)
  6629. if filename == "":
  6630. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6631. return
  6632. else:
  6633. self.export_dxf(name, filename)
  6634. if self.defaults["global_open_style"] is False:
  6635. self.file_opened.emit("DXF", filename)
  6636. self.file_saved.emit("DXF", filename)
  6637. def on_file_importsvg(self, type_of_obj):
  6638. """
  6639. Callback for menu item File->Import SVG.
  6640. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6641. :type type_of_obj: str
  6642. :return: None
  6643. """
  6644. self.defaults.report_usage("on_file_importsvg")
  6645. App.log.debug("on_file_importsvg()")
  6646. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6647. try:
  6648. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6649. directory=self.get_last_folder(), filter=_filter_)
  6650. except TypeError:
  6651. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6652. filter=_filter_)
  6653. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6654. type_of_obj = "geometry"
  6655. filenames = [str(filename) for filename in filenames]
  6656. if len(filenames) == 0:
  6657. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6658. else:
  6659. for filename in filenames:
  6660. if filename != '':
  6661. self.worker_task.emit({'fcn': self.import_svg,
  6662. 'params': [filename, type_of_obj]})
  6663. def on_file_importdxf(self, type_of_obj):
  6664. """
  6665. Callback for menu item File->Import DXF.
  6666. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6667. :type type_of_obj: str
  6668. :return: None
  6669. """
  6670. self.defaults.report_usage("on_file_importdxf")
  6671. App.log.debug("on_file_importdxf()")
  6672. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6673. try:
  6674. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6675. directory=self.get_last_folder(),
  6676. filter=_filter_)
  6677. except TypeError:
  6678. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6679. filter=_filter_)
  6680. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6681. type_of_obj = "geometry"
  6682. filenames = [str(filename) for filename in filenames]
  6683. if len(filenames) == 0:
  6684. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6685. else:
  6686. for filename in filenames:
  6687. if filename != '':
  6688. self.worker_task.emit({'fcn': self.import_dxf,
  6689. 'params': [filename, type_of_obj]})
  6690. # ###############################################################################################################
  6691. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6692. # ###############################################################################################################
  6693. def init_code_editor(self, name):
  6694. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6695. # add the tab if it was closed
  6696. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6697. self.text_editor_tab.setObjectName('text_editor_tab')
  6698. # delete the absolute and relative position and messages in the infobar
  6699. self.ui.position_label.setText("")
  6700. self.ui.rel_position_label.setText("")
  6701. # first clear previous text in text editor (if any)
  6702. self.text_editor_tab.code_editor.clear()
  6703. self.text_editor_tab.code_editor.setReadOnly(False)
  6704. self.toggle_codeeditor = True
  6705. self.text_editor_tab.code_editor.completer_enable = False
  6706. self.text_editor_tab.buttonRun.hide()
  6707. # make sure to keep a reference to the code editor
  6708. self.reference_code_editor = self.text_editor_tab.code_editor
  6709. # Switch plot_area to CNCJob tab
  6710. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6711. def on_view_source(self):
  6712. """
  6713. Called when the user wants to see the source file of the selected object
  6714. :return:
  6715. """
  6716. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6717. self.proc_container.view.set_busy(_("Loading..."))
  6718. try:
  6719. obj = self.collection.get_active()
  6720. except Exception as e:
  6721. log.debug("App.on_view_source() --> %s" % str(e))
  6722. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6723. return 'fail'
  6724. if obj is None:
  6725. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6726. return 'fail'
  6727. flt = "All Files (*.*)"
  6728. if obj.kind == 'gerber':
  6729. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6730. elif obj.kind == 'excellon':
  6731. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6732. elif obj.kind == 'cncjob':
  6733. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6734. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6735. # add the tab if it was closed
  6736. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6737. self.source_editor_tab.setObjectName('source_editor_tab')
  6738. # delete the absolute and relative position and messages in the infobar
  6739. self.ui.position_label.setText("")
  6740. self.ui.rel_position_label.setText("")
  6741. # first clear previous text in text editor (if any)
  6742. self.source_editor_tab.code_editor.clear()
  6743. self.source_editor_tab.code_editor.setReadOnly(False)
  6744. self.source_editor_tab.code_editor.completer_enable = False
  6745. self.source_editor_tab.buttonRun.hide()
  6746. # Switch plot_area to CNCJob tab
  6747. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6748. try:
  6749. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6750. except TypeError:
  6751. pass
  6752. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6753. try:
  6754. self.source_editor_tab.buttonSave.clicked.disconnect()
  6755. except TypeError:
  6756. pass
  6757. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6758. # then append the text from GCode to the text editor
  6759. if obj.kind == 'cncjob':
  6760. try:
  6761. file = obj.export_gcode(
  6762. preamble=self.defaults["cncjob_prepend"],
  6763. postamble=self.defaults["cncjob_append"],
  6764. to_file=True)
  6765. if file == 'fail':
  6766. return 'fail'
  6767. except AttributeError:
  6768. self.inform.emit('[WARNING_NOTCL] %s' %
  6769. _("There is no selected object for which to see it's source file code."))
  6770. return 'fail'
  6771. else:
  6772. try:
  6773. file = StringIO(obj.source_file)
  6774. except (AttributeError, TypeError):
  6775. self.inform.emit('[WARNING_NOTCL] %s' %
  6776. _("There is no selected object for which to see it's source file code."))
  6777. return 'fail'
  6778. self.source_editor_tab.t_frame.hide()
  6779. try:
  6780. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6781. # for line in file:
  6782. # QtWidgets.QApplication.processEvents()
  6783. # proc_line = str(line).strip('\n')
  6784. # self.source_editor_tab.code_editor.append(proc_line)
  6785. except Exception as e:
  6786. log.debug('App.on_view_source() -->%s' % str(e))
  6787. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6788. return
  6789. self.source_editor_tab.handleTextChanged()
  6790. self.source_editor_tab.t_frame.show()
  6791. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6792. self.proc_container.view.set_idle()
  6793. # self.ui.show()
  6794. def on_toggle_code_editor(self):
  6795. self.defaults.report_usage("on_toggle_code_editor()")
  6796. if self.toggle_codeeditor is False:
  6797. self.init_code_editor(name=_("Code Editor"))
  6798. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6799. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6800. self.text_editor_tab.buttonSave.clicked.disconnect()
  6801. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6802. else:
  6803. for idx in range(self.ui.plot_tab_area.count()):
  6804. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6805. self.ui.plot_tab_area.closeTab(idx)
  6806. break
  6807. self.toggle_codeeditor = False
  6808. def on_code_editor_close(self):
  6809. self.toggle_codeeditor = False
  6810. def goto_text_line(self):
  6811. """
  6812. Will scroll a text to the specified text line.
  6813. :return: None
  6814. """
  6815. dia_box = Dialog_box(title=_("Go to Line ..."),
  6816. label=_("Line:"),
  6817. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6818. initial_text='')
  6819. try:
  6820. line = int(dia_box.location) - 1
  6821. except (ValueError, TypeError):
  6822. line = 0
  6823. if dia_box.ok:
  6824. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6825. # at the top of the window
  6826. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6827. # get the document() of the TextEditor
  6828. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6829. # create a Text Cursor based on the searched line
  6830. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6831. # set cursor of the code editor with the cursor at the searcehd line
  6832. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6833. def on_filenewscript(self, silent=False):
  6834. """
  6835. Will create a new script file and open it in the Code Editor
  6836. :param silent: if True will not display status messages
  6837. :param name: if specified will be the name of the new script
  6838. :param text: pass a source file to the newly created script to be loaded in it
  6839. :return: None
  6840. """
  6841. if silent is False:
  6842. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6843. # delete the absolute and relative position and messages in the infobar
  6844. self.ui.position_label.setText("")
  6845. self.ui.rel_position_label.setText("")
  6846. self.new_script_object()
  6847. # script_text = script_obj.source_file
  6848. #
  6849. # self.proc_container.view.set_busy(_("Loading..."))
  6850. # script_obj.script_editor_tab.t_frame.hide()
  6851. #
  6852. # script_obj.script_editor_tab.t_frame.show()
  6853. # self.proc_container.view.set_idle()
  6854. def on_fileopenscript(self, name=None, silent=False):
  6855. """
  6856. Will open a Tcl script file into the Code Editor
  6857. :param silent: if True will not display status messages
  6858. :param name: name of a Tcl script file to open
  6859. :return: None
  6860. """
  6861. self.defaults.report_usage("on_fileopenscript")
  6862. App.log.debug("on_fileopenscript()")
  6863. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6864. "All Files (*.*)"
  6865. if name:
  6866. filenames = [name]
  6867. else:
  6868. try:
  6869. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6870. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6871. except TypeError:
  6872. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6873. if len(filenames) == 0:
  6874. if silent is False:
  6875. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6876. else:
  6877. for filename in filenames:
  6878. if filename != '':
  6879. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6880. def on_fileopenscript_example(self, name=None, silent=False):
  6881. """
  6882. Will open a Tcl script file into the Code Editor
  6883. :param silent: if True will not display status messages
  6884. :param name: name of a Tcl script file to open
  6885. :return:
  6886. """
  6887. self.defaults.report_usage("on_fileopenscript_example")
  6888. log.debug("on_fileopenscript_example()")
  6889. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6890. "All Files (*.*)"
  6891. # test if the app was frozen and choose the path for the configuration file
  6892. if getattr(sys, "frozen", False) is True:
  6893. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6894. else:
  6895. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6896. if name:
  6897. filenames = [name]
  6898. else:
  6899. try:
  6900. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6901. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6902. except TypeError:
  6903. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6904. if len(filenames) == 0:
  6905. if silent is False:
  6906. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6907. else:
  6908. for filename in filenames:
  6909. if filename != '':
  6910. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6911. def on_filerunscript(self, name=None, silent=False):
  6912. """
  6913. File menu callback for loading and running a TCL script.
  6914. :param silent: if True will not display status messages
  6915. :param name: name of a Tcl script file to be run by FlatCAM
  6916. :return: None
  6917. """
  6918. self.defaults.report_usage("on_filerunscript")
  6919. App.log.debug("on_file_runscript()")
  6920. if name:
  6921. filename = name
  6922. if self.cmd_line_headless != 1:
  6923. self.splash.showMessage('%s: %ssec\n%s' %
  6924. (_("Canvas initialization started.\n"
  6925. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6926. _("Executing ScriptObject file.")
  6927. ),
  6928. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6929. color=QtGui.QColor("gray"))
  6930. else:
  6931. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6932. "All Files (*.*)"
  6933. try:
  6934. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6935. directory=self.get_last_folder(), filter=_filter_)
  6936. except TypeError:
  6937. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6938. # The Qt methods above will return a QString which can cause problems later.
  6939. # So far json.dump() will fail to serialize it.
  6940. filename = str(filename)
  6941. if filename == "":
  6942. if silent is False:
  6943. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6944. else:
  6945. if self.cmd_line_headless != 1:
  6946. if self.ui.shell_dock.isHidden():
  6947. self.ui.shell_dock.show()
  6948. try:
  6949. with open(filename, "r") as tcl_script:
  6950. cmd_line_shellfile_content = tcl_script.read()
  6951. if self.cmd_line_headless != 1:
  6952. self.shell.exec_command(cmd_line_shellfile_content)
  6953. else:
  6954. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6955. if silent is False:
  6956. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6957. except Exception as e:
  6958. log.debug("App.on_filerunscript() -> %s" % str(e))
  6959. sys.exit(2)
  6960. def on_file_saveproject(self, silent=False):
  6961. """
  6962. Callback for menu item File->Save Project. Saves the project to
  6963. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6964. if set to None. The project is saved by calling ``self.save_project()``.
  6965. :param silent: if True will not display status messages
  6966. :return: None
  6967. """
  6968. self.defaults.report_usage("on_file_saveproject")
  6969. if self.project_filename is None:
  6970. self.on_file_saveprojectas()
  6971. else:
  6972. self.worker_task.emit({'fcn': self.save_project,
  6973. 'params': [self.project_filename, silent]})
  6974. if self.defaults["global_open_style"] is False:
  6975. self.file_opened.emit("project", self.project_filename)
  6976. self.file_saved.emit("project", self.project_filename)
  6977. self.set_ui_title(name=self.project_filename)
  6978. self.should_we_save = False
  6979. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6980. """
  6981. Callback for menu item File->Save Project As... Opens a file
  6982. chooser and saves the project to the given file via
  6983. ``self.save_project()``.
  6984. :param make_copy if to be create a copy of the project; boolean
  6985. :param use_thread: if to be run in a separate thread; boolean
  6986. :param quit_action: if to be followed by quiting the application; boolean
  6987. :return: None
  6988. """
  6989. self.defaults.report_usage("on_file_saveprojectas")
  6990. self.date = str(datetime.today()).rpartition('.')[0]
  6991. self.date = ''.join(c for c in self.date if c not in ':-')
  6992. self.date = self.date.replace(' ', '_')
  6993. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6994. try:
  6995. filename, _f = FCFileSaveDialog.get_saved_filename(
  6996. caption=_("Save Project As ..."),
  6997. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6998. proj=_("Project")),
  6999. filter=filter_
  7000. )
  7001. except TypeError:
  7002. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  7003. filename = str(filename)
  7004. if filename == '':
  7005. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7006. return
  7007. if use_thread is True:
  7008. self.worker_task.emit({'fcn': self.save_project,
  7009. 'params': [filename, quit_action]})
  7010. else:
  7011. self.save_project(filename, quit_action)
  7012. # self.save_project(filename)
  7013. if self.defaults["global_open_style"] is False:
  7014. self.file_opened.emit("project", filename)
  7015. self.file_saved.emit("project", filename)
  7016. if not make_copy:
  7017. self.project_filename = filename
  7018. self.set_ui_title(name=self.project_filename)
  7019. self.should_we_save = False
  7020. def on_file_save_objects_pdf(self, use_thread=True):
  7021. self.date = str(datetime.today()).rpartition('.')[0]
  7022. self.date = ''.join(c for c in self.date if c not in ':-')
  7023. self.date = self.date.replace(' ', '_')
  7024. try:
  7025. obj_selection = self.collection.get_selected()
  7026. if len(obj_selection) == 1:
  7027. obj_name = str(obj_selection[0].options['name'])
  7028. else:
  7029. obj_name = _("FlatCAM objects print")
  7030. except AttributeError as err:
  7031. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7032. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7033. return
  7034. if not obj_selection:
  7035. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7036. return
  7037. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7038. try:
  7039. filename, _f = FCFileSaveDialog.get_saved_filename(
  7040. caption=_("Save Object as PDF ..."),
  7041. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7042. obj_name=obj_name,
  7043. date=self.date),
  7044. filter=filter_
  7045. )
  7046. except TypeError:
  7047. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7048. filename = str(filename)
  7049. if filename == '':
  7050. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7051. return
  7052. if use_thread is True:
  7053. self.proc_container.new(_("Printing PDF ... Please wait."))
  7054. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7055. else:
  7056. self.save_pdf(filename, obj_selection)
  7057. # self.save_project(filename)
  7058. if self.defaults["global_open_style"] is False:
  7059. self.file_opened.emit("pdf", filename)
  7060. self.file_saved.emit("pdf", filename)
  7061. def save_pdf(self, file_name, obj_selection):
  7062. p_size = self.defaults['global_workspaceT']
  7063. orientation = self.defaults['global_workspace_orientation']
  7064. color = 'black'
  7065. transparency_level = 1.0
  7066. self.pagesize = {}
  7067. self.pagesize.update(
  7068. {
  7069. 'Bounds': None,
  7070. 'A0': (841 * mm, 1189 * mm),
  7071. 'A1': (594 * mm, 841 * mm),
  7072. 'A2': (420 * mm, 594 * mm),
  7073. 'A3': (297 * mm, 420 * mm),
  7074. 'A4': (210 * mm, 297 * mm),
  7075. 'A5': (148 * mm, 210 * mm),
  7076. 'A6': (105 * mm, 148 * mm),
  7077. 'A7': (74 * mm, 105 * mm),
  7078. 'A8': (52 * mm, 74 * mm),
  7079. 'A9': (37 * mm, 52 * mm),
  7080. 'A10': (26 * mm, 37 * mm),
  7081. 'B0': (1000 * mm, 1414 * mm),
  7082. 'B1': (707 * mm, 1000 * mm),
  7083. 'B2': (500 * mm, 707 * mm),
  7084. 'B3': (353 * mm, 500 * mm),
  7085. 'B4': (250 * mm, 353 * mm),
  7086. 'B5': (176 * mm, 250 * mm),
  7087. 'B6': (125 * mm, 176 * mm),
  7088. 'B7': (88 * mm, 125 * mm),
  7089. 'B8': (62 * mm, 88 * mm),
  7090. 'B9': (44 * mm, 62 * mm),
  7091. 'B10': (31 * mm, 44 * mm),
  7092. 'C0': (917 * mm, 1297 * mm),
  7093. 'C1': (648 * mm, 917 * mm),
  7094. 'C2': (458 * mm, 648 * mm),
  7095. 'C3': (324 * mm, 458 * mm),
  7096. 'C4': (229 * mm, 324 * mm),
  7097. 'C5': (162 * mm, 229 * mm),
  7098. 'C6': (114 * mm, 162 * mm),
  7099. 'C7': (81 * mm, 114 * mm),
  7100. 'C8': (57 * mm, 81 * mm),
  7101. 'C9': (40 * mm, 57 * mm),
  7102. 'C10': (28 * mm, 40 * mm),
  7103. # American paper sizes
  7104. 'LETTER': (8.5 * inch, 11 * inch),
  7105. 'LEGAL': (8.5 * inch, 14 * inch),
  7106. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7107. # From https://en.wikipedia.org/wiki/Paper_size
  7108. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7109. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7110. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7111. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7112. 'LEDGER': (17 * inch, 11 * inch),
  7113. }
  7114. )
  7115. exported_svg = []
  7116. for obj in obj_selection:
  7117. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7118. scale_factor_x=None, scale_factor_y=None,
  7119. skew_factor_x=None, skew_factor_y=None,
  7120. mirror=None)
  7121. if obj.kind.lower() == 'gerber':
  7122. # color = self.defaults["gerber_plot_fill"][:-2]
  7123. color = obj.fill_color[:-2]
  7124. elif obj.kind.lower() == 'excellon':
  7125. color = '#C40000'
  7126. elif obj.kind.lower() == 'geometry':
  7127. color = self.defaults["global_draw_color"]
  7128. # Change the attributes of the exported SVG
  7129. # We don't need stroke-width
  7130. # We set opacity to maximum
  7131. # We set the colour to WHITE
  7132. root = ET.fromstring(svg_obj)
  7133. for child in root:
  7134. child.set('fill', str(color))
  7135. child.set('opacity', str(transparency_level))
  7136. child.set('stroke', str(color))
  7137. exported_svg.append(ET.tostring(root))
  7138. xmin = Inf
  7139. ymin = Inf
  7140. xmax = -Inf
  7141. ymax = -Inf
  7142. for obj in obj_selection:
  7143. try:
  7144. gxmin, gymin, gxmax, gymax = obj.bounds()
  7145. xmin = min([xmin, gxmin])
  7146. ymin = min([ymin, gymin])
  7147. xmax = max([xmax, gxmax])
  7148. ymax = max([ymax, gymax])
  7149. except Exception as e:
  7150. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7151. # Determine bounding area for svg export
  7152. bounds = [xmin, ymin, xmax, ymax]
  7153. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7154. # This contain the measure units
  7155. uom = obj_selection[0].units.lower()
  7156. # Define a boundary around SVG of about 1.0mm (~39mils)
  7157. if uom in "mm":
  7158. boundary = 1.0
  7159. else:
  7160. boundary = 0.0393701
  7161. # Convert everything to strings for use in the xml doc
  7162. svgwidth = str(size[0] + (2 * boundary))
  7163. svgheight = str(size[1] + (2 * boundary))
  7164. minx = str(bounds[0] - boundary)
  7165. miny = str(bounds[1] + boundary + size[1])
  7166. # Add a SVG Header and footer to the svg output from shapely
  7167. # The transform flips the Y Axis so that everything renders
  7168. # properly within svg apps such as inkscape
  7169. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7170. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7171. svg_header += 'width="' + svgwidth + uom + '" '
  7172. svg_header += 'height="' + svgheight + uom + '" '
  7173. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7174. svg_header += '>'
  7175. svg_header += '<g transform="scale(1,-1)">'
  7176. svg_footer = '</g> </svg>'
  7177. svg_elem = str(svg_header)
  7178. for svg_item in exported_svg:
  7179. svg_elem += str(svg_item)
  7180. svg_elem += str(svg_footer)
  7181. # Parse the xml through a xml parser just to add line feeds
  7182. # and to make it look more pretty for the output
  7183. doc = parse_xml_string(svg_elem)
  7184. doc_final = doc.toprettyxml()
  7185. try:
  7186. if self.defaults['units'].upper() == 'IN':
  7187. unit = inch
  7188. else:
  7189. unit = mm
  7190. doc_final = StringIO(doc_final)
  7191. drawing = svg2rlg(doc_final)
  7192. if p_size == 'Bounds':
  7193. renderPDF.drawToFile(drawing, file_name)
  7194. else:
  7195. if orientation == 'p':
  7196. page_size = portrait(self.pagesize[p_size])
  7197. else:
  7198. page_size = landscape(self.pagesize[p_size])
  7199. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7200. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7201. renderPDF.draw(drawing, my_canvas, 0, 0)
  7202. my_canvas.save()
  7203. except Exception as e:
  7204. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7205. return 'fail'
  7206. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7207. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7208. """
  7209. Exports a Geometry Object to an SVG file.
  7210. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7211. :param filename: Path to the SVG file to save to.
  7212. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7213. :return:
  7214. """
  7215. self.defaults.report_usage("export_svg()")
  7216. if filename is None:
  7217. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7218. is not None else self.defaults["global_last_folder"]
  7219. self.log.debug("export_svg()")
  7220. try:
  7221. obj = self.collection.get_by_name(str(obj_name))
  7222. except Exception:
  7223. # TODO: The return behavior has not been established... should raise exception?
  7224. return "Could not retrieve object: %s" % obj_name
  7225. with self.proc_container.new(_("Exporting SVG")) as proc:
  7226. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7227. # Determine bounding area for svg export
  7228. bounds = obj.bounds()
  7229. size = obj.size()
  7230. # Convert everything to strings for use in the xml doc
  7231. svgwidth = str(size[0])
  7232. svgheight = str(size[1])
  7233. minx = str(bounds[0])
  7234. miny = str(bounds[1] - size[1])
  7235. uom = obj.units.lower()
  7236. # Add a SVG Header and footer to the svg output from shapely
  7237. # The transform flips the Y Axis so that everything renders
  7238. # properly within svg apps such as inkscape
  7239. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7240. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7241. svg_header += 'width="' + svgwidth + uom + '" '
  7242. svg_header += 'height="' + svgheight + uom + '" '
  7243. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7244. svg_header += '<g transform="scale(1,-1)">'
  7245. svg_footer = '</g> </svg>'
  7246. svg_elem = svg_header + exported_svg + svg_footer
  7247. # Parse the xml through a xml parser just to add line feeds
  7248. # and to make it look more pretty for the output
  7249. svgcode = parse_xml_string(svg_elem)
  7250. svgcode = svgcode.toprettyxml()
  7251. try:
  7252. with open(filename, 'w') as fp:
  7253. fp.write(svgcode)
  7254. except PermissionError:
  7255. self.inform.emit('[WARNING] %s' %
  7256. _("Permission denied, saving not possible.\n"
  7257. "Most likely another app is holding the file open and not accessible."))
  7258. return 'fail'
  7259. if self.defaults["global_open_style"] is False:
  7260. self.file_opened.emit("SVG", filename)
  7261. self.file_saved.emit("SVG", filename)
  7262. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7263. def save_source_file(self, obj_name, filename, use_thread=True):
  7264. """
  7265. Exports a FlatCAM Object to an Gerber/Excellon file.
  7266. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7267. :param filename: Path to the Gerber file to save to.
  7268. :param use_thread: if to be run in a separate thread
  7269. :return:
  7270. """
  7271. self.defaults.report_usage("save source file()")
  7272. if filename is None:
  7273. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7274. is not None else self.defaults["global_last_folder"]
  7275. self.log.debug("save source file()")
  7276. obj = self.collection.get_by_name(obj_name)
  7277. file_string = StringIO(obj.source_file)
  7278. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7279. if file_string.getvalue() == '':
  7280. self.inform.emit('[ERROR_NOTCL] %s' %
  7281. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7282. return 'fail'
  7283. try:
  7284. with open(filename, 'w') as file:
  7285. file.writelines('G04*\n')
  7286. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7287. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7288. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7289. file.writelines('G04 Created on : %s*\n' % time_string)
  7290. for line in file_string:
  7291. file.writelines(line)
  7292. except PermissionError:
  7293. self.inform.emit('[WARNING] %s' %
  7294. _("Permission denied, saving not possible.\n"
  7295. "Most likely another app is holding the file open and not accessible."))
  7296. return 'fail'
  7297. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7298. """
  7299. Exports a Excellon Object to an Excellon file.
  7300. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7301. :param filename: Path to the Excellon file to save to.
  7302. :param local_use:
  7303. :param use_thread: if to be run in a separate thread
  7304. :return:
  7305. """
  7306. self.defaults.report_usage("export_excellon()")
  7307. if filename is None:
  7308. if self.defaults["global_last_save_folder"]:
  7309. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7310. else:
  7311. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7312. self.log.debug("export_excellon()")
  7313. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7314. self.defaults["excellon_exp_decimals"]
  7315. )
  7316. if local_use is None:
  7317. try:
  7318. obj = self.collection.get_by_name(str(obj_name))
  7319. except Exception:
  7320. return "Could not retrieve object: %s" % obj_name
  7321. else:
  7322. obj = local_use
  7323. if not isinstance(obj, ExcellonObject):
  7324. self.inform.emit('[ERROR_NOTCL] %s' %
  7325. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7326. return
  7327. # updated units
  7328. eunits = self.defaults["excellon_exp_units"]
  7329. ewhole = self.defaults["excellon_exp_integer"]
  7330. efract = self.defaults["excellon_exp_decimals"]
  7331. ezeros = self.defaults["excellon_exp_zeros"]
  7332. eformat = self.defaults["excellon_exp_format"]
  7333. slot_type = self.defaults["excellon_exp_slot_type"]
  7334. fc_units = self.defaults['units'].upper()
  7335. if fc_units == 'MM':
  7336. factor = 1 if eunits == 'METRIC' else 0.03937
  7337. else:
  7338. factor = 25.4 if eunits == 'METRIC' else 1
  7339. def make_excellon():
  7340. try:
  7341. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7342. header = 'M48\n'
  7343. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7344. (str(self.version), str(self.version_date))
  7345. header += ';Filename: %s' % str(obj_name) + '\n'
  7346. header += ';Created on : %s' % time_str + '\n'
  7347. if eformat == 'dec':
  7348. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7349. header += eunits + '\n'
  7350. for tool in obj.tools:
  7351. if eunits == 'METRIC':
  7352. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7353. tool=str(tool),
  7354. dec=2)
  7355. else:
  7356. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7357. tool=str(tool),
  7358. dec=4)
  7359. else:
  7360. if ezeros == 'LZ':
  7361. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7362. form='ndec', e_zeros='LZ', factor=factor,
  7363. slot_type=slot_type)
  7364. header += '%s,%s\n' % (eunits, 'LZ')
  7365. header += format_exc
  7366. for tool in obj.tools:
  7367. if eunits == 'METRIC':
  7368. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7369. tool=str(tool),
  7370. dec=2)
  7371. else:
  7372. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7373. tool=str(tool),
  7374. dec=4)
  7375. else:
  7376. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7377. form='ndec', e_zeros='TZ', factor=factor,
  7378. slot_type=slot_type)
  7379. header += '%s,%s\n' % (eunits, 'TZ')
  7380. header += format_exc
  7381. for tool in obj.tools:
  7382. if eunits == 'METRIC':
  7383. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7384. tool=str(tool),
  7385. dec=2)
  7386. else:
  7387. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7388. tool=str(tool),
  7389. dec=4)
  7390. header += '%\n'
  7391. footer = 'M30\n'
  7392. exported_excellon = header
  7393. exported_excellon += excellon_code
  7394. exported_excellon += footer
  7395. if local_use is None:
  7396. try:
  7397. with open(filename, 'w') as fp:
  7398. fp.write(exported_excellon)
  7399. except PermissionError:
  7400. self.inform.emit('[WARNING] %s' %
  7401. _("Permission denied, saving not possible.\n"
  7402. "Most likely another app is holding the file open and not accessible."))
  7403. return 'fail'
  7404. if self.defaults["global_open_style"] is False:
  7405. self.file_opened.emit("Excellon", filename)
  7406. self.file_saved.emit("Excellon", filename)
  7407. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7408. else:
  7409. return exported_excellon
  7410. except Exception as e:
  7411. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7412. return 'fail'
  7413. if use_thread is True:
  7414. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7415. def job_thread_exc(app_obj):
  7416. ret = make_excellon()
  7417. if ret == 'fail':
  7418. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7419. return
  7420. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7421. else:
  7422. eret = make_excellon()
  7423. if eret == 'fail':
  7424. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7425. return 'fail'
  7426. if local_use is not None:
  7427. return eret
  7428. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7429. """
  7430. Exports a Gerber Object to an Gerber file.
  7431. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7432. :param filename: Path to the Gerber file to save to.
  7433. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7434. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7435. :param use_thread: if to be run in a separate thread
  7436. :return:
  7437. """
  7438. self.defaults.report_usage("export_gerber()")
  7439. if filename is None:
  7440. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7441. is not None else self.defaults["global_last_folder"]
  7442. self.log.debug("export_gerber()")
  7443. if local_use is None:
  7444. try:
  7445. obj = self.collection.get_by_name(str(obj_name))
  7446. except Exception:
  7447. return "Could not retrieve object: %s" % obj_name
  7448. else:
  7449. obj = local_use
  7450. # updated units
  7451. gunits = self.defaults["gerber_exp_units"]
  7452. gwhole = self.defaults["gerber_exp_integer"]
  7453. gfract = self.defaults["gerber_exp_decimals"]
  7454. gzeros = self.defaults["gerber_exp_zeros"]
  7455. fc_units = self.defaults['units'].upper()
  7456. if fc_units == 'MM':
  7457. factor = 1 if gunits == 'MM' else 0.03937
  7458. else:
  7459. factor = 25.4 if gunits == 'MM' else 1
  7460. def make_gerber():
  7461. try:
  7462. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7463. header = 'G04*\n'
  7464. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7465. (str(self.version), str(self.version_date))
  7466. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7467. header += 'G04 Created on : %s*' % time_str + '\n'
  7468. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7469. header += "%MO{units}*%\n".format(units=gunits)
  7470. for apid in obj.apertures:
  7471. if obj.apertures[apid]['type'] == 'C':
  7472. header += "%ADD{apid}{type},{size}*%\n".format(
  7473. apid=str(apid),
  7474. type='C',
  7475. size=(factor * obj.apertures[apid]['size'])
  7476. )
  7477. elif obj.apertures[apid]['type'] == 'R':
  7478. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7479. apid=str(apid),
  7480. type='R',
  7481. width=(factor * obj.apertures[apid]['width']),
  7482. height=(factor * obj.apertures[apid]['height'])
  7483. )
  7484. elif obj.apertures[apid]['type'] == 'O':
  7485. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7486. apid=str(apid),
  7487. type='O',
  7488. width=(factor * obj.apertures[apid]['width']),
  7489. height=(factor * obj.apertures[apid]['height'])
  7490. )
  7491. header += '\n'
  7492. # obsolete units but some software may need it
  7493. if gunits == 'IN':
  7494. header += 'G70*\n'
  7495. else:
  7496. header += 'G71*\n'
  7497. # Absolute Mode
  7498. header += 'G90*\n'
  7499. header += 'G01*\n'
  7500. # positive polarity
  7501. header += '%LPD*%\n'
  7502. footer = 'M02*\n'
  7503. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7504. exported_gerber = header
  7505. exported_gerber += gerber_code
  7506. exported_gerber += footer
  7507. if local_use is None:
  7508. try:
  7509. with open(filename, 'w') as fp:
  7510. fp.write(exported_gerber)
  7511. except PermissionError:
  7512. self.inform.emit('[WARNING] %s' %
  7513. _("Permission denied, saving not possible.\n"
  7514. "Most likely another app is holding the file open and not accessible."))
  7515. return 'fail'
  7516. if self.defaults["global_open_style"] is False:
  7517. self.file_opened.emit("Gerber", filename)
  7518. self.file_saved.emit("Gerber", filename)
  7519. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7520. else:
  7521. return exported_gerber
  7522. except Exception as e:
  7523. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7524. return 'fail'
  7525. if use_thread is True:
  7526. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7527. def job_thread_grb(app_obj):
  7528. ret = make_gerber()
  7529. if ret == 'fail':
  7530. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7531. return
  7532. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7533. else:
  7534. gret = make_gerber()
  7535. if gret == 'fail':
  7536. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7537. return 'fail'
  7538. if local_use is not None:
  7539. return gret
  7540. def export_dxf(self, obj_name, filename, use_thread=True):
  7541. """
  7542. Exports a Geometry Object to an DXF file.
  7543. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7544. :param filename: Path to the DXF file to save to.
  7545. :param use_thread: if to be run in a separate thread
  7546. :return:
  7547. """
  7548. self.defaults.report_usage("export_dxf()")
  7549. if filename is None:
  7550. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7551. is not None else self.defaults["global_last_folder"]
  7552. self.log.debug("export_dxf()")
  7553. try:
  7554. obj = self.collection.get_by_name(str(obj_name))
  7555. except Exception:
  7556. # TODO: The return behavior has not been established... should raise exception?
  7557. return "Could not retrieve object: %s" % obj_name
  7558. def make_dxf():
  7559. try:
  7560. dxf_code = obj.export_dxf()
  7561. dxf_code.saveas(filename)
  7562. if self.defaults["global_open_style"] is False:
  7563. self.file_opened.emit("DXF", filename)
  7564. self.file_saved.emit("DXF", filename)
  7565. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7566. except Exception:
  7567. return 'fail'
  7568. if use_thread is True:
  7569. with self.proc_container.new(_("Exporting DXF")) as proc:
  7570. def job_thread_exc(app_obj):
  7571. ret_dxf_val = make_dxf()
  7572. if ret_dxf_val == 'fail':
  7573. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7574. return
  7575. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7576. else:
  7577. ret = make_dxf()
  7578. if ret == 'fail':
  7579. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7580. return
  7581. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7582. """
  7583. Adds a new Geometry Object to the projects and populates
  7584. it with shapes extracted from the SVG file.
  7585. :param plot: If True then the resulting object will be plotted on canvas
  7586. :param filename: Path to the SVG file.
  7587. :param geo_type: Type of FlatCAM object that will be created from SVG
  7588. :param outname: The name given to the resulting FlatCAM object
  7589. :return:
  7590. """
  7591. self.defaults.report_usage("import_svg()")
  7592. log.debug("App.import_svg()")
  7593. obj_type = ""
  7594. if geo_type is None or geo_type == "geometry":
  7595. obj_type = "geometry"
  7596. elif geo_type == "gerber":
  7597. obj_type = "gerber"
  7598. else:
  7599. self.inform.emit('[ERROR_NOTCL] %s' %
  7600. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7601. return
  7602. units = self.defaults['units'].upper()
  7603. def obj_init(geo_obj, app_obj):
  7604. geo_obj.import_svg(filename, obj_type, units=units)
  7605. geo_obj.multigeo = False
  7606. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7607. with self.proc_container.new(_("Importing SVG")) as proc:
  7608. # Object name
  7609. name = outname or filename.split('/')[-1].split('\\')[-1]
  7610. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7611. if ret == 'fail':
  7612. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7613. return 'fail'
  7614. # Register recent file
  7615. self.file_opened.emit("svg", filename)
  7616. # GUI feedback
  7617. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7618. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7619. """
  7620. Adds a new Geometry Object to the projects and populates
  7621. it with shapes extracted from the DXF file.
  7622. :param filename: Path to the DXF file.
  7623. :param geo_type: Type of FlatCAM object that will be created from DXF
  7624. :param outname: Name for the imported Geometry
  7625. :param plot: If True then the resulting object will be plotted on canvas
  7626. :return:
  7627. """
  7628. self.defaults.report_usage("import_dxf()")
  7629. obj_type = ""
  7630. if geo_type is None or geo_type == "geometry":
  7631. obj_type = "geometry"
  7632. elif geo_type == "gerber":
  7633. obj_type = geo_type
  7634. else:
  7635. self.inform.emit('[ERROR_NOTCL] %s' %
  7636. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7637. return
  7638. units = self.defaults['units'].upper()
  7639. def obj_init(geo_obj, app_obj):
  7640. geo_obj.import_dxf(filename, obj_type, units=units)
  7641. geo_obj.multigeo = False
  7642. with self.proc_container.new(_("Importing DXF")):
  7643. # Object name
  7644. name = outname or filename.split('/')[-1].split('\\')[-1]
  7645. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7646. if ret == 'fail':
  7647. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7648. return 'fail'
  7649. # Register recent file
  7650. self.file_opened.emit("dxf", filename)
  7651. # GUI feedback
  7652. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7653. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7654. """
  7655. Opens a Gerber file, parses it and creates a new object for
  7656. it in the program. Thread-safe.
  7657. :param outname: Name of the resulting object. None causes the
  7658. name to be that of the file. Str.
  7659. :param filename: Gerber file filename
  7660. :type filename: str
  7661. :param plot: boolean, to plot or not the resulting object
  7662. :param from_tcl: True if run from Tcl Shell
  7663. :return: None
  7664. """
  7665. # How the object should be initialized
  7666. def obj_init(gerber_obj, app_obj):
  7667. assert isinstance(gerber_obj, GerberObject), \
  7668. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7669. # Opening the file happens here
  7670. try:
  7671. gerber_obj.parse_file(filename)
  7672. except IOError:
  7673. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7674. return "fail"
  7675. except ParseError as err:
  7676. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7677. app_obj.log.error(str(err))
  7678. return "fail"
  7679. except Exception as e:
  7680. log.debug("App.open_gerber() --> %s" % str(e))
  7681. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7682. msg += traceback.format_exc()
  7683. app_obj.inform.emit(msg)
  7684. return "fail"
  7685. if gerber_obj.is_empty():
  7686. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7687. _("Object is not Gerber file or empty. Aborting object creation."))
  7688. return "fail"
  7689. App.log.debug("open_gerber()")
  7690. with self.proc_container.new(_("Opening Gerber")):
  7691. # Object name
  7692. name = outname or filename.split('/')[-1].split('\\')[-1]
  7693. # # ## Object creation # ##
  7694. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7695. if ret_val == 'fail':
  7696. if from_tcl:
  7697. filename = self.defaults['global_tcl_path'] + '/' + name
  7698. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7699. if ret_val == 'fail':
  7700. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7701. return 'fail'
  7702. # Register recent file
  7703. self.file_opened.emit("gerber", filename)
  7704. # GUI feedback
  7705. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7706. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7707. """
  7708. Opens an Excellon file, parses it and creates a new object for
  7709. it in the program. Thread-safe.
  7710. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7711. :param filename: Excellon file filename
  7712. :type filename: str
  7713. :param plot: boolean, to plot or not the resulting object
  7714. :param from_tcl: True if run from Tcl Shell
  7715. :return: None
  7716. """
  7717. App.log.debug("open_excellon()")
  7718. # How the object should be initialized
  7719. def obj_init(excellon_obj, app_obj):
  7720. try:
  7721. ret = excellon_obj.parse_file(filename=filename)
  7722. if ret == "fail":
  7723. log.debug("Excellon parsing failed.")
  7724. self.inform.emit('[ERROR_NOTCL] %s' %
  7725. _("This is not Excellon file."))
  7726. return "fail"
  7727. except IOError:
  7728. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7729. (_("Cannot open file"), filename))
  7730. log.debug("Could not open Excellon object.")
  7731. return "fail"
  7732. except Exception:
  7733. msg = '[ERROR_NOTCL] %s' % \
  7734. _("An internal error has occurred. See shell.\n")
  7735. msg += traceback.format_exc()
  7736. app_obj.inform.emit(msg)
  7737. return "fail"
  7738. ret = excellon_obj.create_geometry()
  7739. if ret == 'fail':
  7740. log.debug("Could not create geometry for Excellon object.")
  7741. return "fail"
  7742. for tool in excellon_obj.tools:
  7743. if excellon_obj.tools[tool]['solid_geometry']:
  7744. return
  7745. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7746. return "fail"
  7747. with self.proc_container.new(_("Opening Excellon.")):
  7748. # Object name
  7749. name = outname or filename.split('/')[-1].split('\\')[-1]
  7750. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7751. if ret_val == 'fail':
  7752. if from_tcl:
  7753. filename = self.defaults['global_tcl_path'] + '/' + name
  7754. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7755. if ret_val == 'fail':
  7756. self.inform.emit('[ERROR_NOTCL] %s' %
  7757. _('Open Excellon file failed. Probable not an Excellon file.'))
  7758. return
  7759. # Register recent file
  7760. self.file_opened.emit("excellon", filename)
  7761. # GUI feedback
  7762. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7763. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7764. """
  7765. Opens a G-gcode file, parses it and creates a new object for
  7766. it in the program. Thread-safe.
  7767. :param filename: G-code file filename
  7768. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7769. :param force_parsing:
  7770. :param plot: If True plot the object on canvas
  7771. :param from_tcl: True if run from Tcl Shell
  7772. :return: None
  7773. """
  7774. App.log.debug("open_gcode()")
  7775. # How the object should be initialized
  7776. def obj_init(job_obj, app_obj_):
  7777. """
  7778. :param job_obj: the resulting object
  7779. :type app_obj_: App
  7780. """
  7781. assert isinstance(app_obj_, App), \
  7782. "Initializer expected App, got %s" % type(app_obj_)
  7783. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7784. try:
  7785. f = open(filename)
  7786. gcode = f.read()
  7787. f.close()
  7788. except IOError:
  7789. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7790. return "fail"
  7791. job_obj.gcode = gcode
  7792. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7793. if gcode_ret == "fail":
  7794. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7795. return "fail"
  7796. job_obj.create_geometry()
  7797. with self.proc_container.new(_("Opening G-Code.")):
  7798. # Object name
  7799. name = outname or filename.split('/')[-1].split('\\')[-1]
  7800. # New object creation and file processing
  7801. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7802. if ret_val == 'fail':
  7803. if from_tcl:
  7804. filename = self.defaults['global_tcl_path'] + '/' + name
  7805. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7806. if ret_val == 'fail':
  7807. self.inform.emit('[ERROR_NOTCL] %s' %
  7808. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7809. "Try to load it from File menu.\n "
  7810. "Attempting to create a FlatCAM CNCJob Object from "
  7811. "G-Code file failed during processing"))
  7812. return "fail"
  7813. # Register recent file
  7814. self.file_opened.emit("cncjob", filename)
  7815. # GUI feedback
  7816. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7817. def open_hpgl2(self, filename, outname=None):
  7818. """
  7819. Opens a HPGL2 file, parses it and creates a new object for
  7820. it in the program. Thread-safe.
  7821. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7822. :param filename: HPGL2 file filename
  7823. :return: None
  7824. """
  7825. filename = filename
  7826. # How the object should be initialized
  7827. def obj_init(geo_obj, app_obj):
  7828. assert isinstance(geo_obj, GeometryObject), \
  7829. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7830. # Opening the file happens here
  7831. obj = HPGL2(self)
  7832. try:
  7833. HPGL2.parse_file(obj, filename)
  7834. except IOError:
  7835. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7836. return "fail"
  7837. except ParseError as err:
  7838. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7839. app_obj.log.error(str(err))
  7840. return "fail"
  7841. except Exception as e:
  7842. log.debug("App.open_hpgl2() --> %s" % str(e))
  7843. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7844. msg += traceback.format_exc()
  7845. app_obj.inform.emit(msg)
  7846. return "fail"
  7847. geo_obj.multigeo = True
  7848. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7849. geo_obj.tools = deepcopy(obj.tools)
  7850. geo_obj.source_file = deepcopy(obj.source_file)
  7851. del obj
  7852. if not geo_obj.solid_geometry:
  7853. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7854. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7855. return "fail"
  7856. App.log.debug("open_hpgl2()")
  7857. with self.proc_container.new(_("Opening HPGL2")):
  7858. # Object name
  7859. name = outname or filename.split('/')[-1].split('\\')[-1]
  7860. # # ## Object creation # ##
  7861. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7862. if ret == 'fail':
  7863. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7864. return 'fail'
  7865. # Register recent file
  7866. self.file_opened.emit("geometry", filename)
  7867. # GUI feedback
  7868. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7869. def open_script(self, filename, outname=None, silent=False):
  7870. """
  7871. Opens a Script file, parses it and creates a new object for
  7872. it in the program. Thread-safe.
  7873. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7874. :param filename: Script file filename
  7875. :param silent: If True there will be no messages printed to StatusBar
  7876. :return: None
  7877. """
  7878. def obj_init(script_obj, app_obj):
  7879. assert isinstance(script_obj, ScriptObject), \
  7880. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7881. if silent is False:
  7882. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7883. try:
  7884. script_obj.parse_file(filename)
  7885. except IOError:
  7886. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7887. return "fail"
  7888. except ParseError as err:
  7889. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7890. app_obj.log.error(str(err))
  7891. return "fail"
  7892. except Exception as e:
  7893. log.debug("App.open_script() -> %s" % str(e))
  7894. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7895. msg += traceback.format_exc()
  7896. app_obj.inform.emit(msg)
  7897. return "fail"
  7898. App.log.debug("open_script()")
  7899. with self.proc_container.new(_("Opening TCL Script...")):
  7900. # Object name
  7901. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7902. # Object creation
  7903. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7904. if ret_val == 'fail':
  7905. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7906. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7907. if ret_val == 'fail':
  7908. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7909. return 'fail'
  7910. # Register recent file
  7911. self.file_opened.emit("script", filename)
  7912. # GUI feedback
  7913. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7914. def open_config_file(self, filename, run_from_arg=None):
  7915. """
  7916. Loads a config file from the specified file.
  7917. :param filename: Name of the file from which to load.
  7918. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7919. :return: None
  7920. """
  7921. App.log.debug("Opening config file: " + filename)
  7922. if run_from_arg:
  7923. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7924. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7925. _("Opening FlatCAM Config file.")),
  7926. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7927. color=QtGui.QColor("gray"))
  7928. # # add the tab if it was closed
  7929. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7930. # # first clear previous text in text editor (if any)
  7931. # self.ui.text_editor_tab.code_editor.clear()
  7932. #
  7933. # # Switch plot_area to CNCJob tab
  7934. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7935. # close the Code editor if already open
  7936. if self.toggle_codeeditor:
  7937. self.on_toggle_code_editor()
  7938. self.on_toggle_code_editor()
  7939. try:
  7940. if filename:
  7941. f = QtCore.QFile(filename)
  7942. if f.open(QtCore.QIODevice.ReadOnly):
  7943. stream = QtCore.QTextStream(f)
  7944. code_edited = stream.readAll()
  7945. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7946. f.close()
  7947. except IOError:
  7948. App.log.error("Failed to open config file: %s" % filename)
  7949. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7950. (_("Failed to open config file"), filename))
  7951. return
  7952. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7953. """
  7954. Loads a project from the specified file.
  7955. 1) Loads and parses file
  7956. 2) Registers the file as recently opened.
  7957. 3) Calls on_file_new()
  7958. 4) Updates options
  7959. 5) Calls new_object() with the object's from_dict() as init method.
  7960. 6) Calls plot_all() if plot=True
  7961. :param filename: Name of the file from which to load.
  7962. :param run_from_arg: True if run for arguments
  7963. :param plot: If True plot all objects in the project
  7964. :param cli: Run from command line
  7965. :param from_tcl: True if run from Tcl Sehll
  7966. :return: None
  7967. """
  7968. App.log.debug("Opening project: " + filename)
  7969. # block autosaving while a project is loaded
  7970. self.block_autosave = True
  7971. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7972. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7973. if cli is None:
  7974. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7975. if run_from_arg:
  7976. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7977. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7978. _("Opening FlatCAM Project file.")),
  7979. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7980. color=QtGui.QColor("gray"))
  7981. # Open and parse an uncompressed Project file
  7982. try:
  7983. f = open(filename, 'r')
  7984. except IOError:
  7985. if from_tcl:
  7986. name = filename.split('/')[-1].split('\\')[-1]
  7987. filename = self.defaults['global_tcl_path'] + '/' + name
  7988. try:
  7989. f = open(filename, 'r')
  7990. except IOError:
  7991. log.error("Failed to open project file: %s" % filename)
  7992. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7993. return
  7994. else:
  7995. log.error("Failed to open project file: %s" % filename)
  7996. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7997. return
  7998. try:
  7999. d = json.load(f, object_hook=dict2obj)
  8000. except Exception as e:
  8001. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8002. (filename, str(e)))
  8003. f.close()
  8004. # Open and parse a compressed Project file
  8005. try:
  8006. with lzma.open(filename) as f:
  8007. file_content = f.read().decode('utf-8')
  8008. d = json.loads(file_content, object_hook=dict2obj)
  8009. except Exception as e:
  8010. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8011. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8012. return
  8013. # Clear the current project
  8014. # # NOT THREAD SAFE # ##
  8015. if run_from_arg is True:
  8016. pass
  8017. elif cli is True:
  8018. self.delete_selection_shape()
  8019. else:
  8020. self.on_file_new()
  8021. # Project options
  8022. self.options.update(d['options'])
  8023. self.project_filename = filename
  8024. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8025. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8026. if cli is None:
  8027. self.set_screen_units(self.options["units"])
  8028. # Re create objects
  8029. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8030. for obj in d['objs']:
  8031. try:
  8032. def obj_init(obj_inst, app_inst):
  8033. obj_inst.from_dict(obj)
  8034. App.log.debug("Recreating from opened project an %s object: %s" %
  8035. (obj['kind'].capitalize(), obj['options']['name']))
  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="{} {}: {}".format(_("Loading Project ... restoring"),
  8040. obj['kind'].upper(),
  8041. obj['options']['name']
  8042. )
  8043. )
  8044. self.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8045. except Exception as e:
  8046. print('App.open_project() --> ' + str(e))
  8047. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8048. self.should_we_save = False
  8049. self.file_opened.emit("project", filename)
  8050. # restore autosaving after a project was loaded
  8051. self.block_autosave = False
  8052. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8053. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8054. if cli is None:
  8055. self.set_ui_title(name=self.project_filename)
  8056. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8057. def plot_all(self, fit_view=True, use_thread=True):
  8058. """
  8059. Re-generates all plots from all objects.
  8060. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8061. :param use_thread: if True will use threading for plotting the objects
  8062. :return: None
  8063. """
  8064. self.log.debug("Plot_all()")
  8065. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8066. for plot_obj in self.collection.get_list():
  8067. def worker_task(obj):
  8068. with self.proc_container.new("Plotting"):
  8069. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8070. if fit_view is True:
  8071. self.object_plotted.emit(obj)
  8072. if use_thread is True:
  8073. # Send to worker
  8074. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8075. else:
  8076. worker_task(plot_obj)
  8077. def register_folder(self, filename):
  8078. """
  8079. Register the last folder used by the app to open something
  8080. :param filename: the last folder is extracted from the filename
  8081. :return: None
  8082. """
  8083. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8084. def register_save_folder(self, filename):
  8085. """
  8086. Register the last folder used by the app to save something
  8087. :param filename: the last folder is extracted from the filename
  8088. :return: None
  8089. """
  8090. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8091. # def set_progress_bar(self, percentage, text=""):
  8092. # """
  8093. # Set a progress bar to a value (percentage)
  8094. #
  8095. # :param percentage: Value set to the progressbar
  8096. # :param text: Not used
  8097. # :return: None
  8098. # """
  8099. # self.ui.progress_bar.setValue(int(percentage))
  8100. def setup_recent_items(self):
  8101. """
  8102. Setup a dictionary with the recent files accessed, organized by type
  8103. :return:
  8104. """
  8105. icons = {
  8106. "gerber": self.resource_location + "/flatcam_icon16.png",
  8107. "excellon": self.resource_location + "/drill16.png",
  8108. 'geometry': self.resource_location + "/geometry16.png",
  8109. "cncjob": self.resource_location + "/cnc16.png",
  8110. "script": self.resource_location + "/script_new24.png",
  8111. "document": self.resource_location + "/notes16_1.png",
  8112. "project": self.resource_location + "/project16.png",
  8113. "svg": self.resource_location + "/geometry16.png",
  8114. "dxf": self.resource_location + "/dxf16.png",
  8115. "pdf": self.resource_location + "/pdf32.png",
  8116. "image": self.resource_location + "/image16.png"
  8117. }
  8118. try:
  8119. image_opener = self.image_tool.import_image
  8120. except AttributeError:
  8121. image_opener = None
  8122. openers = {
  8123. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8124. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8125. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8126. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8127. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8128. "document": None,
  8129. 'project': self.open_project,
  8130. 'svg': self.import_svg,
  8131. 'dxf': self.import_dxf,
  8132. 'image': image_opener,
  8133. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8134. }
  8135. # Open recent file for files
  8136. try:
  8137. f = open(self.data_path + '/recent.json')
  8138. except IOError:
  8139. App.log.error("Failed to load recent item list.")
  8140. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8141. return
  8142. try:
  8143. self.recent = json.load(f)
  8144. except json.errors.JSONDecodeError:
  8145. App.log.error("Failed to parse recent item list.")
  8146. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8147. f.close()
  8148. return
  8149. f.close()
  8150. # Open recent file for projects
  8151. try:
  8152. fp = open(self.data_path + '/recent_projects.json')
  8153. except IOError:
  8154. App.log.error("Failed to load recent project item list.")
  8155. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8156. return
  8157. try:
  8158. self.recent_projects = json.load(fp)
  8159. except json.errors.JSONDecodeError:
  8160. App.log.error("Failed to parse recent project item list.")
  8161. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8162. fp.close()
  8163. return
  8164. fp.close()
  8165. # Closure needed to create callbacks in a loop.
  8166. # Otherwise late binding occurs.
  8167. def make_callback(func, fname):
  8168. def opener():
  8169. func(fname)
  8170. return opener
  8171. def reset_recent_files():
  8172. # Reset menu
  8173. self.ui.recent.clear()
  8174. self.recent = []
  8175. try:
  8176. ff = open(self.data_path + '/recent.json', 'w')
  8177. except IOError:
  8178. App.log.error("Failed to open recent items file for writing.")
  8179. return
  8180. json.dump(self.recent, ff)
  8181. def reset_recent_projects():
  8182. # Reset menu
  8183. self.ui.recent_projects.clear()
  8184. self.recent_projects = []
  8185. try:
  8186. frp = open(self.data_path + '/recent_projects.json', 'w')
  8187. except IOError:
  8188. App.log.error("Failed to open recent projects items file for writing.")
  8189. return
  8190. json.dump(self.recent, frp)
  8191. # Reset menu
  8192. self.ui.recent.clear()
  8193. self.ui.recent_projects.clear()
  8194. # Create menu items for projects
  8195. for recent in self.recent_projects:
  8196. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8197. if recent['kind'] == 'project':
  8198. try:
  8199. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8200. # Attach callback
  8201. o = make_callback(openers[recent["kind"]], recent['filename'])
  8202. action.triggered.connect(o)
  8203. self.ui.recent_projects.addAction(action)
  8204. except KeyError:
  8205. App.log.error("Unsupported file type: %s" % recent["kind"])
  8206. # Last action in Recent Files menu is one that Clear the content
  8207. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8208. (_("Clear Recent projects")), self)
  8209. clear_action_proj.triggered.connect(reset_recent_projects)
  8210. self.ui.recent_projects.addSeparator()
  8211. self.ui.recent_projects.addAction(clear_action_proj)
  8212. # Create menu items for files
  8213. for recent in self.recent:
  8214. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8215. if recent['kind'] != 'project':
  8216. try:
  8217. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8218. # Attach callback
  8219. o = make_callback(openers[recent["kind"]], recent['filename'])
  8220. action.triggered.connect(o)
  8221. self.ui.recent.addAction(action)
  8222. except KeyError:
  8223. App.log.error("Unsupported file type: %s" % recent["kind"])
  8224. # Last action in Recent Files menu is one that Clear the content
  8225. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8226. (_("Clear Recent files")), self)
  8227. clear_action.triggered.connect(reset_recent_files)
  8228. self.ui.recent.addSeparator()
  8229. self.ui.recent.addAction(clear_action)
  8230. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8231. # self.ui.menufilerecent.set_submenu(recent_menu)
  8232. # recent_menu.show_all()
  8233. # self.ui.recent.show()
  8234. self.log.debug("Recent items list has been populated.")
  8235. def setup_component_editor(self):
  8236. """
  8237. Default text for the Selected tab when is not taken by the Object UI.
  8238. :return:
  8239. """
  8240. # label = QtWidgets.QLabel("Choose an item from Project")
  8241. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8242. sel_title = QtWidgets.QTextEdit(
  8243. _('<b>Shortcut Key List</b>'))
  8244. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8245. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8246. f_settings = QSettings("Open Source", "FlatCAM")
  8247. if f_settings.contains("notebook_font_size"):
  8248. fsize = f_settings.value('notebook_font_size', type=int)
  8249. else:
  8250. fsize = 12
  8251. tsize = fsize + int(fsize / 2)
  8252. # selected_text = (_('''
  8253. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8254. # </p>
  8255. #
  8256. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8257. # The normal flow when working in FlatCAM is the following:</span></p>
  8258. #
  8259. # <ol>
  8260. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8261. # file into
  8262. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8263. # even dragging and dropping the files on the GUI.<br />
  8264. # <br />
  8265. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8266. # drop of the
  8267. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8268. # &nbsp;</li>
  8269. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8270. # and then
  8271. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8272. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8273. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8274. # <br />
  8275. # If the selection of the object is done on the canvas by single click instead, and the
  8276. # <strong>SELECTED TAB</strong>
  8277. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8278. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8279. # it even if it was out of focus.<br />
  8280. # <br />
  8281. # You can change the parameters in this screen and the flow direction is like this:<br />
  8282. # <br />
  8283. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8284. # <strong> Geometry Object
  8285. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8286. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8287. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8288. # </ol>
  8289. #
  8290. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8291. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8292. # <strong>F3</strong>.</span></p>
  8293. #
  8294. # ''').format(fsize=fsize, tsize=tsize))
  8295. selected_text = '''
  8296. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8297. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8298. {s1}</span></p>
  8299. <ol>
  8300. <li><span style="font-size:{fsize}px">{s2}<br />
  8301. <br />
  8302. {s3}</span><br />
  8303. &nbsp;</li>
  8304. <li><span style="font-size:{fsize}px">{s4}<br />
  8305. &nbsp;</li>
  8306. <br />
  8307. <li><span style="font-size:{fsize}px">{s5}<br />
  8308. &nbsp;</li>
  8309. <br />
  8310. <li><span style="font-size:{fsize}px">{s6}<br />
  8311. <br />
  8312. {s7}</span></li>
  8313. </ol>
  8314. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8315. '''.format(
  8316. title=_("Selected Tab - Choose an Item from Project Tab"),
  8317. subtitle=_("Details"),
  8318. s1=_("The normal flow when working in FlatCAM is the following:"),
  8319. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8320. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8321. "files on the GUI."),
  8322. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8323. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8324. "actions offered within the app."),
  8325. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8326. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8327. "SELECTED TAB will be updated with the object properties according to its kind: "
  8328. "Gerber, Excellon, Geometry or CNCJob object."),
  8329. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8330. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8331. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8332. "the SELECTED TAB and populate it even if it was out of focus."),
  8333. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8334. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8335. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8336. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8337. "(again, done in SELECTED TAB) --> Save GCode."),
  8338. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8339. "or through its own key shortcut: <b>F3</b>."),
  8340. tsize=tsize,
  8341. fsize=fsize
  8342. )
  8343. sel_title.setText(selected_text)
  8344. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8345. self.ui.selected_scroll_area.setWidget(sel_title)
  8346. def setup_obj_classes(self):
  8347. """
  8348. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8349. class.
  8350. :return: None
  8351. """
  8352. FlatCAMObj.app = self
  8353. ObjectCollection.app = self
  8354. Gerber.app = self
  8355. Excellon.app = self
  8356. Geometry.app = self
  8357. CNCjob.app = self
  8358. FCProcess.app = self
  8359. FCProcessContainer.app = self
  8360. OptionsGroupUI.app = self
  8361. def version_check(self):
  8362. """
  8363. Checks for the latest version of the program. Alerts the
  8364. user if theirs is outdated. This method is meant to be run
  8365. in a separate thread.
  8366. :return: None
  8367. """
  8368. self.log.debug("version_check()")
  8369. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8370. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8371. App.version_url,
  8372. str(self.defaults['global_serial']),
  8373. str(self.version),
  8374. str(self.os),
  8375. urllib.parse.urlencode(self.defaults["global_stats"])
  8376. )
  8377. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8378. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8379. # urllib.parse.urlencode(self.defaults["global_stats"])
  8380. else:
  8381. # no_stats dict; just so it won't break things on website
  8382. no_ststs_dict = {}
  8383. no_ststs_dict["global_ststs"] = {}
  8384. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8385. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8386. App.log.debug("Checking for updates @ %s" % full_url)
  8387. # ## Get the data
  8388. try:
  8389. f = urllib.request.urlopen(full_url)
  8390. except Exception:
  8391. # App.log.warning("Failed checking for latest version. Could not connect.")
  8392. self.log.warning("Failed checking for latest version. Could not connect.")
  8393. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8394. return
  8395. try:
  8396. data = json.load(f)
  8397. except Exception as e:
  8398. App.log.error("Could not parse information about latest version.")
  8399. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8400. App.log.debug("json.load(): %s" % str(e))
  8401. f.close()
  8402. return
  8403. f.close()
  8404. # ## Latest version?
  8405. if self.version >= data["version"]:
  8406. App.log.debug("FlatCAM is up to date!")
  8407. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8408. return
  8409. App.log.debug("Newer version available.")
  8410. self.message.emit(
  8411. _("Newer Version Available"),
  8412. '%s<br><br>><b>%s</b><br>%s' % (
  8413. _("There is a newer version of FlatCAM available for download:"),
  8414. str(data["name"]),
  8415. str(data["message"])
  8416. ),
  8417. _("info")
  8418. )
  8419. def on_plotcanvas_setup(self, container=None):
  8420. """
  8421. This is doing the setup for the plot area (canvas).
  8422. :param container: QT Widget where to install the canvas
  8423. :return: None
  8424. """
  8425. if container:
  8426. plot_container = container
  8427. else:
  8428. plot_container = self.ui.right_layout
  8429. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8430. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8431. self.is_legacy = True
  8432. self.defaults["global_graphic_engine"] = "2D"
  8433. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8434. else:
  8435. try:
  8436. self.plotcanvas = PlotCanvas(plot_container, self)
  8437. except Exception as er:
  8438. msg_txt = traceback.format_exc()
  8439. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8440. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8441. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8442. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8443. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8444. msg += msg_txt
  8445. self.inform.emit(msg)
  8446. return 'fail'
  8447. # So it can receive key presses
  8448. self.plotcanvas.native.setFocus()
  8449. if self.is_legacy is False:
  8450. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8451. # Set the mouse button for panning
  8452. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8453. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8454. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8455. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8456. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8457. # Keys over plot enabled
  8458. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8459. if self.defaults['global_cursor_type'] == 'small':
  8460. self.app_cursor = self.plotcanvas.new_cursor()
  8461. else:
  8462. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8463. if self.ui.grid_snap_btn.isChecked():
  8464. self.app_cursor.enabled = True
  8465. else:
  8466. self.app_cursor.enabled = False
  8467. if self.is_legacy is False:
  8468. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8469. else:
  8470. # will use the default Matplotlib axes
  8471. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8472. def on_zoom_fit(self, event):
  8473. """
  8474. Callback for zoom-fit request. This can be either from the corresponding
  8475. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8476. with axes limits from the geometry bounds of all objects.
  8477. :param event: Ignored.
  8478. :return: None
  8479. """
  8480. if self.is_legacy is False:
  8481. self.plotcanvas.fit_view()
  8482. else:
  8483. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8484. width = xmax - xmin
  8485. height = ymax - ymin
  8486. xmin -= 0.05 * width
  8487. xmax += 0.05 * width
  8488. ymin -= 0.05 * height
  8489. ymax += 0.05 * height
  8490. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8491. def on_zoom_in(self):
  8492. """
  8493. Callback for zoom-in request.
  8494. :return:
  8495. """
  8496. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8497. def on_zoom_out(self):
  8498. """
  8499. Callback for zoom-out request.
  8500. :return:
  8501. """
  8502. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8503. def disable_all_plots(self):
  8504. self.defaults.report_usage("disable_all_plots()")
  8505. self.disable_plots(self.collection.get_list())
  8506. self.inform.emit('[success] %s' %
  8507. _("All plots disabled."))
  8508. def disable_other_plots(self):
  8509. self.defaults.report_usage("disable_other_plots()")
  8510. self.disable_plots(self.collection.get_non_selected())
  8511. self.inform.emit('[success] %s' %
  8512. _("All non selected plots disabled."))
  8513. def enable_all_plots(self):
  8514. self.defaults.report_usage("enable_all_plots()")
  8515. self.enable_plots(self.collection.get_list())
  8516. self.inform.emit('[success] %s' %
  8517. _("All plots enabled."))
  8518. def on_enable_sel_plots(self):
  8519. log.debug("App.on_enable_sel_plot()")
  8520. object_list = self.collection.get_selected()
  8521. self.enable_plots(objects=object_list)
  8522. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8523. def on_disable_sel_plots(self):
  8524. log.debug("App.on_disable_sel_plot()")
  8525. # self.inform.emit(_("Disabling plots ..."))
  8526. object_list = self.collection.get_selected()
  8527. self.disable_plots(objects=object_list)
  8528. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8529. def enable_plots(self, objects):
  8530. """
  8531. Enable plots
  8532. :param objects: list of Objects to be enabled
  8533. :return:
  8534. """
  8535. log.debug("Enabling plots ...")
  8536. # self.inform.emit(_("Working ..."))
  8537. for obj in objects:
  8538. if obj.options['plot'] is False:
  8539. obj.options.set_change_callback(lambda x: None)
  8540. obj.options['plot'] = True
  8541. try:
  8542. # only the Gerber obj has on_plot_cb_click() method
  8543. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8544. # disable this cb while disconnected,
  8545. # in case the operation takes time the user is not allowed to change it
  8546. obj.ui.plot_cb.setDisabled(True)
  8547. except AttributeError:
  8548. pass
  8549. obj.set_form_item("plot")
  8550. try:
  8551. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8552. obj.ui.plot_cb.setDisabled(False)
  8553. except AttributeError:
  8554. pass
  8555. obj.options.set_change_callback(obj.on_options_change)
  8556. def worker_task(objs):
  8557. with self.proc_container.new(_("Enabling plots ...")):
  8558. for plot_obj in objs:
  8559. # obj.options['plot'] = True
  8560. if isinstance(plot_obj, CNCJobObject):
  8561. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8562. else:
  8563. plot_obj.plot(visible=True)
  8564. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8565. # self.plots_updated.emit()
  8566. def disable_plots(self, objects):
  8567. """
  8568. Disables plots
  8569. :param objects: list of Objects to be disabled
  8570. :return:
  8571. """
  8572. # if no objects selected then do nothing
  8573. if not self.collection.get_selected():
  8574. return
  8575. log.debug("Disabling plots ...")
  8576. # self.inform.emit(_("Working ..."))
  8577. for obj in objects:
  8578. if obj.options['plot'] is True:
  8579. obj.options.set_change_callback(lambda x: None)
  8580. obj.options['plot'] = False
  8581. try:
  8582. # only the Gerber obj has on_plot_cb_click() method
  8583. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8584. obj.ui.plot_cb.setDisabled(True)
  8585. except AttributeError:
  8586. pass
  8587. obj.set_form_item("plot")
  8588. try:
  8589. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8590. obj.ui.plot_cb.setDisabled(False)
  8591. except AttributeError:
  8592. pass
  8593. obj.options.set_change_callback(obj.on_options_change)
  8594. try:
  8595. self.delete_selection_shape()
  8596. except Exception as e:
  8597. log.debug("App.disable_plots() --> %s" % str(e))
  8598. # self.plots_updated.emit()
  8599. def worker_task(objs):
  8600. with self.proc_container.new(_("Disabling plots ...")):
  8601. for plot_obj in objs:
  8602. # obj.options['plot'] = True
  8603. if isinstance(plot_obj, CNCJobObject):
  8604. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8605. else:
  8606. plot_obj.plot(visible=False)
  8607. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8608. def toggle_plots(self, objects):
  8609. """
  8610. Toggle plots visibility
  8611. :param objects: list of Objects for which to be toggled the visibility
  8612. :return: None
  8613. """
  8614. # if no objects selected then do nothing
  8615. if not self.collection.get_selected():
  8616. return
  8617. log.debug("Toggling plots ...")
  8618. self.inform.emit(_("Working ..."))
  8619. for obj in objects:
  8620. if obj.options['plot'] is False:
  8621. obj.options['plot'] = True
  8622. else:
  8623. obj.options['plot'] = False
  8624. self.plots_updated.emit()
  8625. def clear_plots(self):
  8626. """
  8627. Clear the plots
  8628. :return: None
  8629. """
  8630. objects = self.collection.get_list()
  8631. for obj in objects:
  8632. obj.clear(obj == objects[-1])
  8633. # Clear pool to free memory
  8634. self.clear_pool()
  8635. def on_set_color_action_triggered(self):
  8636. """
  8637. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8638. :return:
  8639. """
  8640. new_color = self.defaults['gerber_plot_fill']
  8641. clicked_action = self.sender()
  8642. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8643. act_name = clicked_action.text()
  8644. sel_obj_list = self.collection.get_selected()
  8645. if not sel_obj_list:
  8646. return
  8647. # a default value, I just chose this one
  8648. alpha_level = 'BF'
  8649. for sel_obj in sel_obj_list:
  8650. if sel_obj.kind == 'excellon':
  8651. alpha_level = str(hex(
  8652. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8653. elif sel_obj.kind == 'gerber':
  8654. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8655. elif sel_obj.kind == 'geometry':
  8656. alpha_level = 'FF'
  8657. else:
  8658. log.debug(
  8659. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8660. continue
  8661. sel_obj.alpha_level = alpha_level
  8662. if act_name == _('Red'):
  8663. new_color = '#FF0000' + alpha_level
  8664. if act_name == _('Blue'):
  8665. new_color = '#0000FF' + alpha_level
  8666. if act_name == _('Yellow'):
  8667. new_color = '#FFDF00' + alpha_level
  8668. if act_name == _('Green'):
  8669. new_color = '#00FF00' + alpha_level
  8670. if act_name == _('Purple'):
  8671. new_color = '#FF00FF' + alpha_level
  8672. if act_name == _('Brown'):
  8673. new_color = '#A52A2A' + alpha_level
  8674. if act_name == _('White'):
  8675. new_color = '#FFFFFF' + alpha_level
  8676. if act_name == _('Black'):
  8677. new_color = '#000000' + alpha_level
  8678. if act_name == _('Custom'):
  8679. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8680. c_dialog = QtWidgets.QColorDialog()
  8681. plot_fill_color = c_dialog.getColor(initial=new_color)
  8682. if plot_fill_color.isValid() is False:
  8683. return
  8684. new_color = str(plot_fill_color.name()) + alpha_level
  8685. if act_name == _("Default"):
  8686. for sel_obj in sel_obj_list:
  8687. if sel_obj.kind == 'excellon':
  8688. new_color = self.defaults['excellon_plot_fill']
  8689. new_line_color = self.defaults['excellon_plot_line']
  8690. elif sel_obj.kind == 'gerber':
  8691. new_color = self.defaults['gerber_plot_fill']
  8692. new_line_color = self.defaults['gerber_plot_line']
  8693. elif sel_obj.kind == 'geometry':
  8694. new_color = self.defaults['geometry_plot_line']
  8695. new_line_color = self.defaults['geometry_plot_line']
  8696. else:
  8697. log.debug(
  8698. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8699. continue
  8700. sel_obj.fill_color = new_color
  8701. sel_obj.outline_color = new_line_color
  8702. sel_obj.shapes.redraw(
  8703. update_colors=(new_color, new_line_color)
  8704. )
  8705. return
  8706. if act_name == _("Opacity"):
  8707. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8708. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8709. if ok_button:
  8710. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8711. for sel_obj in sel_obj_list:
  8712. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8713. sel_obj.shapes.redraw(
  8714. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8715. )
  8716. return
  8717. new_line_color = color_variant(new_color[:7], 0.7)
  8718. if act_name == _("White"):
  8719. new_line_color = color_variant("#dedede", 0.7)
  8720. for sel_obj in sel_obj_list:
  8721. sel_obj.fill_color = new_color
  8722. sel_obj.outline_color = new_line_color
  8723. sel_obj.shapes.redraw(
  8724. update_colors=(new_color, new_line_color)
  8725. )
  8726. def generate_cnc_job(self, objects):
  8727. """
  8728. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8729. :param objects: Selected objects in the Project Tab
  8730. :return:
  8731. """
  8732. self.defaults.report_usage("generate_cnc_job()")
  8733. # for obj in objects:
  8734. # obj.generatecncjob()
  8735. for obj in objects:
  8736. obj.on_generatecnc_button_click()
  8737. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8738. """
  8739. Saves the current project to the specified file.
  8740. :param filename: Name of the file in which to save.
  8741. :type filename: str
  8742. :param quit_action: if the project saving will be followed by an app quit; boolean
  8743. :param silent: if True will not display status messages
  8744. :param from_tcl True is run from Tcl Shell
  8745. :return: None
  8746. """
  8747. self.log.debug("save_project()")
  8748. self.save_in_progress = True
  8749. with self.proc_container.new(_("Saving FlatCAM Project")):
  8750. # Capture the latest changes
  8751. # Current object
  8752. try:
  8753. current_object = self.collection.get_active()
  8754. if current_object:
  8755. current_object.read_form()
  8756. except Exception as e:
  8757. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8758. pass
  8759. # Serialize the whole project
  8760. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8761. "options": self.options,
  8762. "version": self.version}
  8763. if self.defaults["global_save_compressed"] is True:
  8764. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8765. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8766. # # Write
  8767. f.write(g)
  8768. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8769. else:
  8770. # Open file
  8771. try:
  8772. f = open(filename, 'w')
  8773. except IOError:
  8774. App.log.error("Failed to open file for saving: %s", filename)
  8775. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8776. return
  8777. # Write
  8778. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8779. f.close()
  8780. # verification of the saved project
  8781. # Open and parse
  8782. try:
  8783. saved_f = open(filename, 'r')
  8784. except IOError:
  8785. if silent is False:
  8786. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8787. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8788. return
  8789. try:
  8790. saved_d = json.load(saved_f, object_hook=dict2obj)
  8791. except Exception:
  8792. if silent is False:
  8793. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8794. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8795. f.close()
  8796. return
  8797. saved_f.close()
  8798. if silent is False:
  8799. if 'version' in saved_d:
  8800. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8801. else:
  8802. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8803. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8804. tb_settings = QSettings("Open Source", "FlatCAM")
  8805. lock_state = self.ui.lock_action.isChecked()
  8806. tb_settings.setValue('toolbar_lock', lock_state)
  8807. # This will write the setting to the platform specific storage.
  8808. del tb_settings
  8809. # if quit:
  8810. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8811. # t.start()
  8812. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8813. def start_delayed_quit(self, delay, filename, should_quit=None):
  8814. """
  8815. :param delay: period of checking if project file size is more than zero; in seconds
  8816. :param filename: the name of the project file to be checked periodically for size more than zero
  8817. :param should_quit: if the task finished will be followed by an app quit; boolean
  8818. :return:
  8819. """
  8820. to_quit = should_quit
  8821. self.save_timer = QtCore.QTimer()
  8822. self.save_timer.setInterval(delay)
  8823. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8824. self.save_timer.start()
  8825. def check_project_file_size(self, filename, should_quit=None):
  8826. """
  8827. :param filename: the name of the project file to be checked periodically for size more than zero
  8828. :param should_quit: will quit the app if True; boolean
  8829. :return:
  8830. """
  8831. try:
  8832. if os.stat(filename).st_size > 0:
  8833. self.save_in_progress = False
  8834. self.save_timer.stop()
  8835. if should_quit:
  8836. self.app_quit.emit()
  8837. except Exception:
  8838. traceback.print_exc()
  8839. def save_project_auto(self):
  8840. """
  8841. Called periodically to save the project.
  8842. 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
  8843. # progress.
  8844. :return:
  8845. """
  8846. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8847. self.on_file_saveproject()
  8848. def save_project_auto_update(self):
  8849. """
  8850. Update the auto save time interval value.
  8851. :return:
  8852. """
  8853. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8854. try:
  8855. if self.autosave_timer.isActive():
  8856. self.autosave_timer.stop()
  8857. except Exception:
  8858. pass
  8859. if self.defaults['global_autosave'] is True:
  8860. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8861. self.autosave_timer.start()
  8862. def on_options_app2project(self):
  8863. """
  8864. Callback for Options->Transfer Options->App=>Project. Copies options
  8865. from application defaults to project defaults.
  8866. :return: None
  8867. """
  8868. self.defaults.report_usage("on_options_app2project")
  8869. self.preferencesUiManager.defaults_read_form()
  8870. self.options.update(self.defaults)
  8871. def toggle_shell(self):
  8872. """
  8873. Toggle shell: if is visible close it, if it is closed then open it
  8874. :return: None
  8875. """
  8876. self.defaults.report_usage("toggle_shell()")
  8877. if self.ui.shell_dock.isVisible():
  8878. self.ui.shell_dock.hide()
  8879. self.plotcanvas.native.setFocus()
  8880. else:
  8881. self.ui.shell_dock.show()
  8882. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8883. # self.shell._edit.setFocus()
  8884. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8885. # HACK - simulate a mouse click - alternative
  8886. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8887. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8888. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8889. # no_km)
  8890. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8891. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8892. # no_km)
  8893. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8894. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8895. """
  8896. Shows a message on the FlatCAM Shell
  8897. :param msg: Message to display.
  8898. :param show: Opens the shell.
  8899. :param error: Shows the message as an error.
  8900. :param warning: Shows the message as an warning.
  8901. :param success: Shows the message as an success.
  8902. :param selected: Indicate that something was selected on canvas
  8903. :return: None
  8904. """
  8905. if show:
  8906. self.ui.shell_dock.show()
  8907. try:
  8908. if error:
  8909. self.shell.append_error(msg + "\n")
  8910. elif warning:
  8911. self.shell.append_warning(msg + "\n")
  8912. elif success:
  8913. self.shell.append_success(msg + "\n")
  8914. elif selected:
  8915. self.shell.append_selected(msg + "\n")
  8916. else:
  8917. self.shell.append_output(msg + "\n")
  8918. except AttributeError:
  8919. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8920. class ArgsThread(QtCore.QObject):
  8921. open_signal = pyqtSignal(list)
  8922. start = pyqtSignal()
  8923. stop = pyqtSignal()
  8924. if sys.platform == 'win32':
  8925. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8926. else:
  8927. address = ('/tmp/testipc', 'AF_UNIX')
  8928. def __init__(self):
  8929. super(ArgsThread, self).__init__()
  8930. self.listener = None
  8931. self.thread_exit = False
  8932. self.start.connect(self.run)
  8933. self.stop.connect(self.close_listener)
  8934. def my_loop(self, address):
  8935. try:
  8936. self.listener = Listener(*address)
  8937. while self.thread_exit is False:
  8938. conn = self.listener.accept()
  8939. self.serve(conn)
  8940. except socket.error:
  8941. try:
  8942. conn = Client(*address)
  8943. conn.send(sys.argv)
  8944. conn.send('close')
  8945. # close the current instance only if there are args
  8946. if len(sys.argv) > 1:
  8947. try:
  8948. self.listener.close()
  8949. except Exception:
  8950. pass
  8951. sys.exit()
  8952. except ConnectionRefusedError:
  8953. if sys.platform == 'win32':
  8954. pass
  8955. else:
  8956. os.system('rm /tmp/testipc')
  8957. self.listener = Listener(*address)
  8958. while True:
  8959. conn = self.listener.accept()
  8960. self.serve(conn)
  8961. def serve(self, conn):
  8962. while self.thread_exit is False:
  8963. msg = conn.recv()
  8964. if msg == 'close':
  8965. break
  8966. self.open_signal.emit(msg)
  8967. conn.close()
  8968. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8969. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8970. @pyqtSlot()
  8971. def run(self):
  8972. self.my_loop(self.address)
  8973. @pyqtSlot()
  8974. def close_listener(self):
  8975. self.thread_exit = True
  8976. self.listener.close()
  8977. # end of file