FlatCAMApp.py 487 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import shutil
  16. from datetime import datetime
  17. import time
  18. import ctypes
  19. import traceback
  20. from PyQt5.QtCore import pyqtSlot, Qt
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Diverse
  37. from FlatCAMCommon import LoudDict, color_variant
  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.992
  138. version_date = "2020/05/01"
  139. beta = True
  140. engine = '3D'
  141. # current date now
  142. date = str(datetime.today()).rpartition('.')[0]
  143. date = ''.join(c for c in date if c not in ':-')
  144. date = date.replace(' ', '_')
  145. # ###############################################################################################################
  146. # ############################################ URLS's ###########################################################
  147. # ###############################################################################################################
  148. # URL for update checks and statistics
  149. version_url = "http://flatcam.org/version"
  150. # App URL
  151. app_url = "http://flatcam.org"
  152. # Manual URL
  153. manual_url = "http://flatcam.org/manual/index.html"
  154. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  155. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  156. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  157. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  158. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  159. # this variable will hold the project status
  160. # if True it will mean that the project was modified and not saved
  161. should_we_save = False
  162. # flag is True if saving action has been triggered
  163. save_in_progress = False
  164. # ###############################################################################################################
  165. # ####################################### APP Signals ######################################################
  166. # ###############################################################################################################
  167. # Inform the user
  168. # Handled by:
  169. # * App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal(str)
  171. app_quit = QtCore.pyqtSignal()
  172. # General purpose background task
  173. worker_task = QtCore.pyqtSignal(dict)
  174. # File opened
  175. # Handled by:
  176. # * register_folder()
  177. # * register_recent()
  178. # Note: Setting the parameters to unicode does not seem
  179. # to have an effect. Then are received as Qstring
  180. # anyway.
  181. # File type and filename
  182. file_opened = QtCore.pyqtSignal(str, str)
  183. # File type and filename
  184. file_saved = QtCore.pyqtSignal(str, str)
  185. # Percentage of progress
  186. progress = QtCore.pyqtSignal(int)
  187. plots_updated = QtCore.pyqtSignal()
  188. # Emitted by new_object() and passes the new object as argument, plot flag.
  189. # on_object_created() adds the object to the collection, plots on appropriate flag
  190. # and emits new_object_available.
  191. object_created = QtCore.pyqtSignal(object, bool, bool)
  192. # Emitted when a object has been changed (like scaled, mirrored)
  193. object_changed = QtCore.pyqtSignal(object)
  194. # Emitted after object has been plotted.
  195. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  196. object_plotted = QtCore.pyqtSignal(object)
  197. # Emitted when a new object has been added or deleted from/to the collection
  198. object_status_changed = QtCore.pyqtSignal(object, str, str)
  199. message = QtCore.pyqtSignal(str, str, str)
  200. # Emmited when shell command is finished(one command only)
  201. shell_command_finished = QtCore.pyqtSignal(object)
  202. # Emitted when multiprocess pool has been recreated
  203. pool_recreated = QtCore.pyqtSignal(object)
  204. # Emitted when an unhandled exception happens
  205. # in the worker task.
  206. thread_exception = QtCore.pyqtSignal(object)
  207. # used to signal that there are arguments for the app
  208. args_at_startup = QtCore.pyqtSignal(list)
  209. # a reusable signal to replot a list of objects
  210. # should be disconnected after use so it can be reused
  211. replot_signal = pyqtSignal(list)
  212. # signal emitted when jumping
  213. jump_signal = pyqtSignal(tuple)
  214. # signal emitted when jumping
  215. locate_signal = pyqtSignal(tuple, str)
  216. # close app signal
  217. close_app_signal = pyqtSignal()
  218. # will perform the cleanup operation after a Graceful Exit
  219. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  220. # graphic residues behind
  221. cleanup = pyqtSignal()
  222. def __init__(self, user_defaults=True):
  223. """
  224. Starts the application.
  225. :return: app
  226. :rtype: App
  227. """
  228. App.log.info("FlatCAM Starting...")
  229. self.main_thread = QtWidgets.QApplication.instance().thread()
  230. # ############################################################################################################
  231. # ################# Setup the listening thread for another instance launching with args ######################
  232. # ############################################################################################################
  233. if sys.platform == 'win32' or sys.platform == 'linux':
  234. # make sure the thread is stored by using a self. otherwise it's garbage collected
  235. self.th = QtCore.QThread()
  236. self.th.start(priority=QtCore.QThread.LowestPriority)
  237. self.new_launch = ArgsThread()
  238. self.new_launch.open_signal[list].connect(self.on_startup_args)
  239. self.new_launch.moveToThread(self.th)
  240. self.new_launch.start.emit()
  241. # ############################################################################################################
  242. # # ######################################## OS-specific #####################################################
  243. # ############################################################################################################
  244. portable = False
  245. # Folder for user settings.
  246. if sys.platform == 'win32':
  247. if platform.architecture()[0] == '32bit':
  248. App.log.debug("Win32!")
  249. else:
  250. App.log.debug("Win64!")
  251. # #######################################################################################################
  252. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  253. # #######################################################################################################
  254. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  255. try:
  256. with open(config_file, 'r'):
  257. pass
  258. except FileNotFoundError:
  259. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  260. try:
  261. with open(config_file, 'r') as f:
  262. try:
  263. for line in f:
  264. param = str(line).replace('\n', '').rpartition('=')
  265. if param[0] == 'portable':
  266. try:
  267. portable = eval(param[2])
  268. except NameError:
  269. portable = False
  270. if param[0] == 'headless':
  271. if param[2].lower() == 'true':
  272. self.cmd_line_headless = 1
  273. else:
  274. self.cmd_line_headless = None
  275. except Exception as e:
  276. log.debug('App.__init__() -->%s' % str(e))
  277. return
  278. except FileNotFoundError as e:
  279. log.debug(str(e))
  280. pass
  281. if portable is False:
  282. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  283. else:
  284. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  285. self.os = 'windows'
  286. else: # Linux/Unix/MacOS
  287. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  288. self.os = 'unix'
  289. # ############################################################################################################
  290. # ################################# Setup folders and files ##################################################
  291. # ############################################################################################################
  292. if not os.path.exists(self.data_path):
  293. os.makedirs(self.data_path)
  294. App.log.debug('Created data folder: ' + self.data_path)
  295. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  296. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  297. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  298. if not os.path.exists(self.preprocessorpaths):
  299. os.makedirs(self.preprocessorpaths)
  300. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  301. # create geo_tools_db.FlatDB file if there is none
  302. try:
  303. f = open(self.data_path + '/geo_tools_db.FlatDB')
  304. f.close()
  305. except IOError:
  306. App.log.debug('Creating empty geo_tool_db.FlatDB')
  307. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  308. json.dump({}, f)
  309. f.close()
  310. # create current_defaults.FlatConfig file if there is none
  311. try:
  312. f = open(self.data_path + '/current_defaults.FlatConfig')
  313. f.close()
  314. except IOError:
  315. App.log.debug('Creating empty current_defaults.FlatConfig')
  316. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  317. json.dump({}, f)
  318. f.close()
  319. # Write factory_defaults.FlatConfig file to disk
  320. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  321. # create a recent files json file if there is none
  322. try:
  323. f = open(self.data_path + '/recent.json')
  324. f.close()
  325. except IOError:
  326. App.log.debug('Creating empty recent.json')
  327. f = open(self.data_path + '/recent.json', 'w')
  328. json.dump([], f)
  329. f.close()
  330. # create a recent projects json file if there is none
  331. try:
  332. fp = open(self.data_path + '/recent_projects.json')
  333. fp.close()
  334. except IOError:
  335. App.log.debug('Creating empty recent_projects.json')
  336. fp = open(self.data_path + '/recent_projects.json', 'w')
  337. json.dump([], fp)
  338. fp.close()
  339. # Application directory. CHDIR to it. Otherwise, trying to load
  340. # GUI icons will fail as their path is relative.
  341. # This will fail under cx_freeze ...
  342. self.app_home = os.path.dirname(os.path.realpath(__file__))
  343. App.log.debug("Application path is " + self.app_home)
  344. App.log.debug("Started in " + os.getcwd())
  345. # cx_freeze workaround
  346. if os.path.isfile(self.app_home):
  347. self.app_home = os.path.dirname(self.app_home)
  348. os.chdir(self.app_home)
  349. # ############################################################################################################
  350. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  351. # ############################################################################################################
  352. self.defaults = FlatCAMDefaults()
  353. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  354. if user_defaults:
  355. self.defaults.load(filename=current_defaults_path)
  356. if self.defaults['units'] == 'MM':
  357. self.decimals = int(self.defaults['decimals_metric'])
  358. else:
  359. self.decimals = int(self.defaults['decimals_inch'])
  360. if self.defaults["global_gray_icons"] is False:
  361. self.resource_location = 'assets/resources'
  362. else:
  363. self.resource_location = 'assets/resources/dark_resources'
  364. self.current_units = self.defaults['units']
  365. # ###########################################################################################################
  366. # #################################### SETUP OBJECT CLASSES #################################################
  367. # ###########################################################################################################
  368. self.setup_obj_classes()
  369. # ###########################################################################################################
  370. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  371. # ###########################################################################################################
  372. self.pool = Pool()
  373. # ###########################################################################################################
  374. # ###################################### Setting the Splash Screen ##########################################
  375. # ###########################################################################################################
  376. splash_settings = QSettings("Open Source", "FlatCAM")
  377. if splash_settings.contains("splash_screen"):
  378. show_splash = splash_settings.value("splash_screen")
  379. else:
  380. splash_settings.setValue('splash_screen', 1)
  381. # This will write the setting to the platform specific storage.
  382. del splash_settings
  383. show_splash = 1
  384. if show_splash and self.cmd_line_headless != 1:
  385. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  386. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  387. # self.splash.setMask(splash_pix.mask())
  388. # move splashscreen to the current monitor
  389. desktop = QtWidgets.QApplication.desktop()
  390. screen = desktop.screenNumber(QtGui.QCursor.pos())
  391. current_screen_center = desktop.availableGeometry(screen).center()
  392. self.splash.move(current_screen_center - self.splash.rect().center())
  393. self.splash.show()
  394. self.splash.showMessage(_("FlatCAM is initializing ..."),
  395. alignment=Qt.AlignBottom | Qt.AlignLeft,
  396. color=QtGui.QColor("gray"))
  397. else:
  398. show_splash = 0
  399. # ###########################################################################################################
  400. # ######################################### Initialize GUI ##################################################
  401. # ###########################################################################################################
  402. # FlatCAM colors used in plotting
  403. self.FC_light_green = '#BBF268BF'
  404. self.FC_dark_green = '#006E20BF'
  405. self.FC_light_blue = '#a5a5ffbf'
  406. self.FC_dark_blue = '#0000ffbf'
  407. QtCore.QObject.__init__(self)
  408. self.ui = FlatCAMGUI(self)
  409. self.on_grid_snap_triggered(state=True)
  410. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  411. if theme_settings.contains("theme"):
  412. theme = theme_settings.value('theme', type=str)
  413. else:
  414. theme = 'white'
  415. if self.defaults["global_cursor_color_enabled"]:
  416. self.cursor_color_3D = self.defaults["global_cursor_color"]
  417. else:
  418. if theme == 'white':
  419. self.cursor_color_3D = 'black'
  420. else:
  421. self.cursor_color_3D = 'gray'
  422. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  423. self.ui.final_save.connect(self.final_save)
  424. # restore the toolbar view
  425. self.restore_toolbar_view()
  426. # restore the GUI geometry
  427. self.restore_main_win_geom()
  428. # set FlatCAM units in the Status bar
  429. self.set_screen_units(self.defaults['units'])
  430. # ###########################################################################################################
  431. # ########################################### AUTOSAVE SETUP ################################################
  432. # ###########################################################################################################
  433. self.block_autosave = False
  434. self.autosave_timer = QtCore.QTimer(self)
  435. self.save_project_auto_update()
  436. self.autosave_timer.timeout.connect(self.save_project_auto)
  437. # ###########################################################################################################
  438. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  439. # ###########################################################################################################
  440. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  441. inform=self.inform)
  442. self.preferencesUiManager.defaults_write_form()
  443. # When the self.defaults dictionary changes will update the Preferences GUI forms
  444. self.defaults.set_change_callback(self.on_defaults_dict_change)
  445. # ###########################################################################################################
  446. # ##################################### FIRST RUN SECTION ###################################################
  447. # ################################ It's done only once after install #####################################
  448. # ###########################################################################################################
  449. if self.defaults["first_run"] is True:
  450. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  451. initial_lay = 'minimal'
  452. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  453. # Set the combobox in Preferences to the current layout
  454. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  455. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  456. # after the first run, this object should be False
  457. self.defaults["first_run"] = False
  458. self.preferencesUiManager.save_defaults(silent=True)
  459. # ###########################################################################################################
  460. # ############################################ Data #########################################################
  461. # ###########################################################################################################
  462. self.recent = []
  463. self.recent_projects = []
  464. self.clipboard = QtWidgets.QApplication.clipboard()
  465. self.project_filename = None
  466. self.toggle_units_ignore = False
  467. # ###########################################################################################################
  468. # #################################### LOAD PREPROCESSORS ###################################################
  469. # ###########################################################################################################
  470. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  471. # the preprocessor file
  472. self.preprocessors = load_preprocessors(self)
  473. # make sure that always the 'default' preprocessor is the first item in the dictionary
  474. if 'default' in self.preprocessors.keys():
  475. new_ppp_dict = {}
  476. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  477. default_pp = self.preprocessors.pop('default')
  478. new_ppp_dict['default'] = default_pp
  479. # then add the rest of the keys
  480. for name, val_class in self.preprocessors.items():
  481. new_ppp_dict[name] = val_class
  482. # and now put back the ordered dict with 'default' key first
  483. self.preprocessors = new_ppp_dict
  484. for name in list(self.preprocessors.keys()):
  485. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  486. if name.partition('_')[0] == 'Paste':
  487. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  488. continue
  489. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  490. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  491. if name == 'hpgl':
  492. continue
  493. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  494. # ###########################################################################################################
  495. # ########################################## LOAD LANGUAGES ################################################
  496. # ###########################################################################################################
  497. self.languages = fcTranslate.load_languages()
  498. for name in sorted(self.languages.values()):
  499. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  500. # ###########################################################################################################
  501. # ####################################### APPLY APP LANGUAGE ################################################
  502. # ###########################################################################################################
  503. ret_val = fcTranslate.apply_language('strings')
  504. if ret_val == "no language":
  505. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  506. log.debug("Could not find the Language files. The App strings are missing.")
  507. else:
  508. # make the current language the current selection on the language combobox
  509. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  510. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  511. # ###########################################################################################################
  512. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  513. # ###########################################################################################################
  514. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  515. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  516. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  517. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  518. self.defaults.propagate_defaults()
  519. # ###########################################################################################################
  520. # ######################################## UPDATE THE OPTIONS ###############################################
  521. # ###########################################################################################################
  522. self.options = LoudDict()
  523. # -----------------------------------------------------------------------------------------------------------
  524. # Update the self.options from the self.defaults
  525. # The self.defaults holds the application defaults while the self.options holds the object defaults
  526. # -----------------------------------------------------------------------------------------------------------
  527. # Copy app defaults to project options
  528. for def_key, def_val in self.defaults.items():
  529. self.options[def_key] = deepcopy(def_val)
  530. self.preferencesUiManager.show_preferences_gui()
  531. # ### End of Data ####
  532. # ###########################################################################################################
  533. # #################################### SETUP OBJECT COLLECTION ##############################################
  534. # ###########################################################################################################
  535. self.collection = ObjectCollection(self)
  536. self.ui.project_tab_layout.addWidget(self.collection.view)
  537. # ### Adjust tabs width ## ##
  538. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  539. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  540. self.collection.view.setMinimumWidth(290)
  541. self.log.debug("Finished creating Object Collection.")
  542. # ###########################################################################################################
  543. # ######################################## SETUP Plot Area ##################################################
  544. # ###########################################################################################################
  545. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  546. if self.defaults["global_graphic_engine"] == '3D':
  547. self.is_legacy = False
  548. else:
  549. self.is_legacy = True
  550. # Event signals disconnect id holders
  551. self.mp = None
  552. self.mm = None
  553. self.mr = None
  554. self.mdc = None
  555. self.mp_zc = None
  556. self.kp = None
  557. # Matplotlib axis
  558. self.axes = None
  559. if show_splash:
  560. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  561. "Canvas initialization started."),
  562. alignment=Qt.AlignBottom | Qt.AlignLeft,
  563. color=QtGui.QColor("gray"))
  564. start_plot_time = time.time() # debug
  565. self.plotcanvas = None
  566. self.app_cursor = None
  567. self.hover_shapes = None
  568. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  569. # setup the PlotCanvas
  570. self.on_plotcanvas_setup()
  571. end_plot_time = time.time()
  572. self.used_time = end_plot_time - start_plot_time
  573. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  574. if show_splash:
  575. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  576. "Canvas initialization started.\n"
  577. "Canvas initialization finished in"), '%.2f' % self.used_time),
  578. alignment=Qt.AlignBottom | Qt.AlignLeft,
  579. color=QtGui.QColor("gray"))
  580. self.ui.splitter.setStretchFactor(1, 2)
  581. # ###########################################################################################################
  582. # ############################################### SYS TRAY ##################################################
  583. # ###########################################################################################################
  584. if self.defaults["global_systray_icon"]:
  585. self.parent_w = QtWidgets.QWidget()
  586. if self.cmd_line_headless == 1:
  587. self.trayIcon = FlatCAMSystemTray(app=self,
  588. icon=QtGui.QIcon(self.resource_location +
  589. '/flatcam_icon32_green.png'),
  590. headless=True,
  591. parent=self.parent_w)
  592. else:
  593. self.trayIcon = FlatCAMSystemTray(app=self,
  594. icon=QtGui.QIcon(self.resource_location +
  595. '/flatcam_icon32_green.png'),
  596. parent=self.parent_w)
  597. # ###########################################################################################################
  598. # ############################################### Worker SETUP ##############################################
  599. # ###########################################################################################################
  600. if self.defaults["global_worker_number"]:
  601. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  602. else:
  603. self.workers = WorkerStack(workers_number=2)
  604. self.worker_task.connect(self.workers.add_task)
  605. self.log.debug("Finished creating Workers crew.")
  606. # ###########################################################################################################
  607. # ############################################# Activity Monitor ###########################################
  608. # ###########################################################################################################
  609. self.activity_view = FlatCAMActivityView(app=self)
  610. self.ui.infobar.addWidget(self.activity_view)
  611. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  612. # ###########################################################################################################
  613. # ############################################# Signal handling #############################################
  614. # ###########################################################################################################
  615. # ########################################## Custom signals ################################################
  616. # signal for displaying messages in status bar
  617. self.inform.connect(self.info)
  618. # signal to be called when the app is quiting
  619. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  620. self.message.connect(self.message_dialog)
  621. # self.progress.connect(self.set_progress_bar)
  622. # signals that are emitted when object state changes
  623. self.object_created.connect(self.on_object_created)
  624. self.object_changed.connect(self.on_object_changed)
  625. self.object_plotted.connect(self.on_object_plotted)
  626. self.plots_updated.connect(self.on_plots_updated)
  627. # signals emitted when file state change
  628. self.file_opened.connect(self.register_recent)
  629. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  630. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  631. # ########################################## Standard signals ###############################################
  632. # ### Menu
  633. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  634. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  635. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  636. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  637. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  638. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  639. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  640. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  641. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  642. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  643. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  644. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  645. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  646. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  647. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  648. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  649. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  650. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  651. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  652. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  653. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  654. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  655. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  656. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  657. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  658. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  659. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  660. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  661. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  662. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  663. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  664. self.ui.menufile_exit.triggered.connect(self.final_save)
  665. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  666. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  667. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  668. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  669. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  670. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  671. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  672. self.ui.menueditdelete.triggered.connect(self.on_delete)
  673. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  674. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  675. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  676. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  677. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  678. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  679. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  680. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  681. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  682. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  683. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  684. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  685. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  686. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  687. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  688. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  689. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  690. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  691. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  692. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  693. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  694. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  695. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  696. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  697. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  698. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  699. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  700. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  701. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  702. self.ui.menuview_replot.triggered.connect(self.plot_all)
  703. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  704. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  705. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  706. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  707. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  708. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  709. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  710. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  711. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  712. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  713. self.ui.menuhelp_about.triggered.connect(self.on_about)
  714. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  715. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  716. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  717. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  718. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  719. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  720. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  721. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  722. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  723. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  724. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  725. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  726. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  727. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  728. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  729. # ToolBar signals
  730. self.connect_toolbar_signals()
  731. # Notebook and Plot Tab Area signals
  732. # make the right click on the notebook tab and plot tab area tab raise a menu
  733. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  734. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  735. self.on_tab_setup_context_menu()
  736. # activate initial state
  737. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  738. # Context Menu
  739. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  740. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  741. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  742. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  743. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  744. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  745. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  746. self.ui.clearplot.triggered.connect(self.clear_plots)
  747. self.ui.replot.triggered.connect(self.plot_all)
  748. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  749. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  750. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  751. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  752. self.ui.popmenu_move.triggered.connect(self.obj_move)
  753. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  754. # Project Context Menu -> Color Setting
  755. for act in self.ui.menuprojectcolor.actions():
  756. act.triggered.connect(self.on_set_color_action_triggered)
  757. # ###########################################################################################################
  758. # #################################### GUI PREFERENCES SIGNALS ##############################################
  759. # ###########################################################################################################
  760. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  761. lambda: self.on_toggle_units(no_pref=False))
  762. # ##################################### Workspace Setting Signals ###########################################
  763. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  764. self.on_workspace_modified)
  765. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  766. self.on_workspace_modified
  767. )
  768. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  769. # ###########################################################################################################
  770. # ######################################## GUI SETTINGS SIGNALS #############################################
  771. # ###########################################################################################################
  772. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  773. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  774. # ######################################## Tools related signals ############################################
  775. # Film Tool
  776. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  777. self.on_film_color_entry)
  778. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  779. self.on_film_color_button)
  780. # QRCode Tool
  781. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  782. self.on_qrcode_fill_color_entry)
  783. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  784. self.on_qrcode_fill_color_button)
  785. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  786. self.on_qrcode_back_color_entry)
  787. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  788. self.on_qrcode_back_color_button)
  789. # portability changed signal
  790. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  791. # Object list
  792. self.collection.view.activated.connect(self.on_row_activated)
  793. self.collection.item_selected.connect(self.on_row_selected)
  794. self.object_status_changed.connect(self.on_collection_updated)
  795. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  796. # Export Excellon parameters.
  797. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  798. self.on_update_exc_export
  799. )
  800. # call it once to make sure it is updated at startup
  801. self.on_update_exc_export(state=self.defaults["excellon_update"])
  802. # when there are arguments at application startup this get launched
  803. self.args_at_startup[list].connect(self.on_startup_args)
  804. # ###########################################################################################################
  805. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  806. # ###########################################################################################################
  807. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  808. lambda: self.restore_extensions(ext_type='excellon'))
  809. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  810. lambda: self.restore_extensions(ext_type='gcode'))
  811. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  812. lambda: self.restore_extensions(ext_type='gerber'))
  813. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  814. lambda: self.delete_all_extensions(ext_type='excellon'))
  815. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  816. lambda: self.delete_all_extensions(ext_type='gcode'))
  817. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  818. lambda: self.delete_all_extensions(ext_type='gerber'))
  819. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  820. lambda: self.add_extension(ext_type='excellon'))
  821. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  822. lambda: self.add_extension(ext_type='gcode'))
  823. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  824. lambda: self.add_extension(ext_type='gerber'))
  825. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  826. lambda: self.del_extension(ext_type='excellon'))
  827. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  828. lambda: self.del_extension(ext_type='gcode'))
  829. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  830. lambda: self.del_extension(ext_type='gerber'))
  831. # connect the 'Apply' buttons from the Preferences/File Associations
  832. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  833. lambda: self.on_register_files(obj_type='excellon'))
  834. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  835. lambda: self.on_register_files(obj_type='gcode'))
  836. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  837. lambda: self.on_register_files(obj_type='gerber'))
  838. # ###########################################################################################################
  839. # ########################################### KEYWORDS SIGNALS ##############################################
  840. # ###########################################################################################################
  841. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  842. lambda: self.restore_extensions(ext_type='keyword'))
  843. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  844. lambda: self.delete_all_extensions(ext_type='keyword'))
  845. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  846. lambda: self.add_extension(ext_type='keyword'))
  847. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  848. lambda: self.del_extension(ext_type='keyword'))
  849. # connect the abort_all_tasks related slots to the related signals
  850. self.proc_container.idle_flag.connect(self.app_is_idle)
  851. # signal emitted when a tab is closed in the Plot Area
  852. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  853. self.ui.grid_snap_btn.triggered.connect(self.on_grid_snap_triggered)
  854. self.ui.snap_infobar_label.clicked.connect(self.on_grid_icon_snap_clicked)
  855. # signal to close the application
  856. self.close_app_signal.connect(self.kill_app)
  857. # ################################# FINISHED CONNECTING SIGNALS #############################################
  858. # ###########################################################################################################
  859. # ###########################################################################################################
  860. # ###########################################################################################################
  861. self.log.debug("Finished connecting Signals.")
  862. # ###########################################################################################################
  863. # ########################################## Other setups ###################################################
  864. # ###########################################################################################################
  865. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  866. # depending on from where those tools are called different actions can be done
  867. self.call_source = 'app'
  868. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  869. self.tool_tab_locked = False
  870. # decide if to show or hide the Notebook side of the screen at startup
  871. if self.defaults["global_project_at_startup"] is True:
  872. self.ui.splitter.setSizes([1, 1])
  873. else:
  874. self.ui.splitter.setSizes([0, 1])
  875. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  876. self.setup_component_editor()
  877. # ###########################################################################################################
  878. # ####################################### Auto-complete KEYWORDS ############################################
  879. # ###########################################################################################################
  880. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  881. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  882. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  883. 'export_exc',
  884. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  885. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  886. 'interiors', 'isolate', 'join_excellon',
  887. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  888. 'mirror', 'ncc',
  889. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  890. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  891. 'options', 'origin',
  892. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  893. 'save', 'save_project',
  894. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  895. 'skew', 'subtract_poly', 'subtract_rectangle',
  896. 'version', 'write_gcode'
  897. ]
  898. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  899. 'Paste_1',
  900. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  901. 'Toolchange_manual', 'True', 'Users',
  902. 'all', 'auto', 'axis',
  903. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  904. 'contour', 'default',
  905. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  906. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  907. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  908. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  909. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  910. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  911. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  912. 'spacing_columns',
  913. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  914. 'toolchange_xy', 'toolchangez', 'travelz',
  915. 'tooldia', 'use_threads', 'value',
  916. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  917. ]
  918. self.tcl_keywords = [
  919. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  920. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  921. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  922. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  923. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  924. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  925. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  926. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  927. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  928. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  929. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  930. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  931. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  932. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  933. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  934. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  935. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  936. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  937. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  938. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  939. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  940. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  941. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  942. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  943. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  944. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  945. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  946. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  947. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  948. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  949. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  950. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  951. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  952. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  953. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  954. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  955. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  956. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  957. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  958. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  959. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  960. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  961. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  962. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  963. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  964. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  965. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  966. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  967. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  968. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  969. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  970. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  971. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  972. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  973. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  974. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  975. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  976. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  977. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  978. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  979. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  980. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  981. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  982. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  983. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  984. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  985. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  986. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  987. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  988. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  989. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  990. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  991. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  992. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  993. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  994. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  995. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  996. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  997. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  998. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  999. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1000. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1001. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1002. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1003. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1004. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1005. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1006. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1007. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1008. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1009. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1010. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1011. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1012. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1013. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1014. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1015. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1016. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1017. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1018. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1019. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1020. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1021. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1022. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1023. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1024. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1025. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1026. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1027. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1028. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1029. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1030. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1031. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1032. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1033. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1034. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1035. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1036. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1037. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1038. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1039. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1040. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1041. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1042. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1043. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1044. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1045. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1046. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1047. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1048. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1049. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1050. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1051. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1052. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1053. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1054. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1055. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1056. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1057. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1058. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1059. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1060. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1061. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1062. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1063. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1064. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1065. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1066. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1067. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1068. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1069. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1070. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1071. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1072. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1073. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1074. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1075. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1076. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1077. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1078. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1079. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1080. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1081. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1082. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1083. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1084. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1085. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1086. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1087. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1088. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1089. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1090. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1091. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1092. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1093. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1094. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1095. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1096. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1097. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1098. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1099. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1100. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1101. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1102. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1103. ]
  1104. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1105. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1106. # ###########################################################################################################
  1107. # ############################################## Shell SETUP ################################################
  1108. # ###########################################################################################################
  1109. self.shell = FCShell(app=self, version=self.version)
  1110. self.ui.shell_dock.setWidget(self.shell)
  1111. self.log.debug("TCL Shell has been initialized.")
  1112. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1113. if self.defaults["global_shell_at_startup"]:
  1114. self.ui.shell_dock.show()
  1115. else:
  1116. self.ui.shell_dock.hide()
  1117. # ###########################################################################################################
  1118. # ########################################## Tools and Plugins ##############################################
  1119. # ###########################################################################################################
  1120. self.dblsidedtool = None
  1121. self.distance_tool = None
  1122. self.distance_min_tool = None
  1123. self.panelize_tool = None
  1124. self.film_tool = None
  1125. self.paste_tool = None
  1126. self.calculator_tool = None
  1127. self.rules_tool = None
  1128. self.sub_tool = None
  1129. self.move_tool = None
  1130. self.cutout_tool = None
  1131. self.ncclear_tool = None
  1132. self.optimal_tool = None
  1133. self.paint_tool = None
  1134. self.transform_tool = None
  1135. self.properties_tool = None
  1136. self.pdf_tool = None
  1137. self.image_tool = None
  1138. self.pcb_wizard_tool = None
  1139. self.cal_exc_tool = None
  1140. self.qrcode_tool = None
  1141. self.copper_thieving_tool = None
  1142. self.fiducial_tool = None
  1143. self.edrills_tool = None
  1144. self.align_objects_tool = None
  1145. self.punch_tool = None
  1146. self.invert_tool = None
  1147. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1148. try:
  1149. self.install_tools()
  1150. except AttributeError as e:
  1151. log.debug("App.__init__() install tools() --> %s" % str(e))
  1152. # ###########################################################################################################
  1153. # ############################################ SETUP RECENT ITEMS ###########################################
  1154. # ###########################################################################################################
  1155. self.setup_recent_items()
  1156. # ###########################################################################################################
  1157. # ######################################### BookMarks Manager ###############################################
  1158. # ###########################################################################################################
  1159. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1160. self.install_bookmarks()
  1161. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1162. # ###########################################################################################################
  1163. # ########################################### Tools Database ################################################
  1164. # ###########################################################################################################
  1165. self.tools_db_tab = None
  1166. # ### System Font Parsing ###
  1167. # self.f_parse = ParseFont(self)
  1168. # self.parse_system_fonts()
  1169. # ###########################################################################################################
  1170. # ######################################### Check for updates ###############################################
  1171. # ###########################################################################################################
  1172. # Separate thread (Not worker)
  1173. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1174. if (self.beta is False or self.beta is None) and \
  1175. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1176. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1177. # self.thr2 = QtCore.QThread()
  1178. self.worker_task.emit({'fcn': self.version_check,
  1179. 'params': []})
  1180. # self.thr2.start(QtCore.QThread.LowPriority)
  1181. # ###########################################################################################################
  1182. # ##################################### Register files with FlatCAM; #######################################
  1183. # ################################### It works only for Windows for now ####################################
  1184. # ###########################################################################################################
  1185. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1186. self.on_register_files()
  1187. # ###########################################################################################################
  1188. # ######################################## Variables for global usage #######################################
  1189. # ###########################################################################################################
  1190. # hold the App units
  1191. self.units = 'MM'
  1192. # coordinates for relative position display
  1193. self.rel_point1 = (0, 0)
  1194. self.rel_point2 = (0, 0)
  1195. # variable to store coordinates
  1196. self.pos = (0, 0)
  1197. self.pos_canvas = (0, 0)
  1198. self.pos_jump = (0, 0)
  1199. # variable to store mouse coordinates
  1200. self.mouse = [0, 0]
  1201. # variable to store the delta positions on cavnas
  1202. self.dx = 0
  1203. self.dy = 0
  1204. # decide if we have a double click or single click
  1205. self.doubleclick = False
  1206. # store here the is_dragging value
  1207. self.event_is_dragging = False
  1208. # variable to store if a command is active (then the var is not None) and which one it is
  1209. self.command_active = None
  1210. # variable to store the status of moving selection action
  1211. # None value means that it's not an selection action
  1212. # True value = a selection from left to right
  1213. # False value = a selection from right to left
  1214. self.selection_type = None
  1215. # List to store the objects that are currently loaded in FlatCAM
  1216. # This list is updated on each object creation or object delete
  1217. self.all_objects_list = []
  1218. self.objects_under_the_click_list = []
  1219. # List to store the objects that are selected
  1220. self.sel_objects_list = []
  1221. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1222. self.key_modifiers = None
  1223. # Variable to hold the status of the axis
  1224. self.toggle_axis = True
  1225. # Variable to hold the status of the grid lines
  1226. self.toggle_grid_lines = True
  1227. # Variable to store the status of the fullscreen event
  1228. self.toggle_fscreen = False
  1229. # Variable to store the status of the code editor
  1230. self.toggle_codeeditor = False
  1231. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1232. self.click_noproject = False
  1233. self.cursor = None
  1234. # Variable to store the GCODE that was edited
  1235. self.gcode_edited = ""
  1236. self.text_editor_tab = None
  1237. # reference for the self.ui.code_editor
  1238. self.reference_code_editor = None
  1239. self.script_code = ''
  1240. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1241. self.tools_db_changed_flag = False
  1242. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1243. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1244. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1245. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1246. 'tsm']
  1247. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1248. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1249. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1250. 'sbp', 'tap', 'xpi']
  1251. self.svg_list = ['svg']
  1252. self.dxf_list = ['dxf']
  1253. self.pdf_list = ['pdf']
  1254. self.prj_list = ['flatprj']
  1255. self.conf_list = ['flatconfig']
  1256. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1257. # flag for polygons not cleared
  1258. self.poly_not_cleared = False
  1259. # VisPy visuals
  1260. self.isHovering = False
  1261. self.notHovering = True
  1262. # Window geometry
  1263. self.x_pos = None
  1264. self.y_pos = None
  1265. self.width = None
  1266. self.height = None
  1267. # when True, the app has to return from any thread
  1268. self.abort_flag = False
  1269. # set the value used in the Windows Title
  1270. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1271. # this holds a widget that is installed in the Plot Area when View Source option is used
  1272. self.source_editor_tab = None
  1273. self.pagesize = {}
  1274. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1275. # VisPy visuals
  1276. if self.is_legacy is False:
  1277. try:
  1278. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1279. except AttributeError:
  1280. self.tool_shapes = None
  1281. else:
  1282. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1283. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1284. # used in the delayed shutdown self.start_delayed_quit() method
  1285. self.save_timer = None
  1286. # ###########################################################################################################
  1287. # ################################## ADDING FlatCAM EDITORS section #########################################
  1288. # ###########################################################################################################
  1289. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1290. # at the first launch of the App , the editors will not be functional.
  1291. try:
  1292. self.geo_editor = FlatCAMGeoEditor(self)
  1293. except AttributeError:
  1294. pass
  1295. try:
  1296. self.exc_editor = FlatCAMExcEditor(self)
  1297. except AttributeError:
  1298. pass
  1299. try:
  1300. self.grb_editor = FlatCAMGrbEditor(self)
  1301. except AttributeError:
  1302. pass
  1303. self.log.debug("Finished adding FlatCAM Editor's.")
  1304. self.set_ui_title(name=_("New Project - Not saved"))
  1305. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1306. current_platform = platform.architecture()[0]
  1307. if current_platform != '64bit':
  1308. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1309. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1310. # ###########################################################################################################
  1311. # ##################################### Finished the CONSTRUCTOR ############################################
  1312. # ###########################################################################################################
  1313. App.log.debug("END of constructor. Releasing control.")
  1314. # ###########################################################################################################
  1315. # ########################################## SHOW GUI #######################################################
  1316. # ###########################################################################################################
  1317. # if the app is not started as headless, show it
  1318. if self.cmd_line_headless != 1:
  1319. if show_splash:
  1320. # finish the splash
  1321. self.splash.finish(self.ui)
  1322. mgui_settings = QSettings("Open Source", "FlatCAM")
  1323. if mgui_settings.contains("maximized_gui"):
  1324. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1325. if maximized_ui is True:
  1326. self.ui.showMaximized()
  1327. else:
  1328. self.ui.show()
  1329. else:
  1330. self.ui.show()
  1331. if self.defaults["global_systray_icon"]:
  1332. self.trayIcon.show()
  1333. else:
  1334. log.warning("******************* RUNNING HEADLESS *******************")
  1335. # ###########################################################################################################
  1336. # ######################################## START-UP ARGUMENTS ###############################################
  1337. # ###########################################################################################################
  1338. # test if the program was started with a script as parameter
  1339. if self.cmd_line_shellvar:
  1340. try:
  1341. cnt = 0
  1342. command_tcl = 0
  1343. for i in self.cmd_line_shellvar.split(','):
  1344. if i is not None:
  1345. # noinspection PyBroadException
  1346. try:
  1347. command_tcl = eval(i)
  1348. except Exception:
  1349. command_tcl = i
  1350. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1351. cnt += 1
  1352. # if there are Windows paths then replace the path separator with a Unix like one
  1353. if sys.platform == 'win32':
  1354. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1355. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1356. except Exception as ext:
  1357. print("ERROR: ", ext)
  1358. sys.exit(2)
  1359. if self.cmd_line_shellfile:
  1360. if self.cmd_line_headless != 1:
  1361. if self.ui.shell_dock.isHidden():
  1362. self.ui.shell_dock.show()
  1363. try:
  1364. with open(self.cmd_line_shellfile, "r") as myfile:
  1365. # if show_splash:
  1366. # self.splash.showMessage('%s: %ssec\n%s' % (
  1367. # _("Canvas initialization started.\n"
  1368. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1369. # _("Executing Tcl Script ...")),
  1370. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1371. # color=QtGui.QColor("gray"))
  1372. cmd_line_shellfile_text = myfile.read()
  1373. if self.cmd_line_headless != 1:
  1374. self.shell.exec_command(cmd_line_shellfile_text)
  1375. else:
  1376. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1377. except Exception as ext:
  1378. print("ERROR: ", ext)
  1379. sys.exit(2)
  1380. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1381. # the path/file_name must be enclosed in quotes if it contain spaces
  1382. if App.args:
  1383. self.args_at_startup.emit(App.args)
  1384. if self.defaults.old_defaults_found is True:
  1385. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1386. "Please reboot the application to update."))
  1387. self.defaults.old_defaults_found = False
  1388. # ######################################### INIT FINISHED #######################################################
  1389. # #################################################################################################################
  1390. # #################################################################################################################
  1391. # #################################################################################################################
  1392. # #################################################################################################################
  1393. # #################################################################################################################
  1394. @staticmethod
  1395. def copy_and_overwrite(from_path, to_path):
  1396. """
  1397. From here:
  1398. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1399. :param from_path: source path
  1400. :param to_path: destination path
  1401. :return: None
  1402. """
  1403. if os.path.exists(to_path):
  1404. shutil.rmtree(to_path)
  1405. try:
  1406. shutil.copytree(from_path, to_path)
  1407. except FileNotFoundError:
  1408. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1409. shutil.copytree(from_new_path, to_path)
  1410. def on_startup_args(self, args, silent=False):
  1411. """
  1412. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1413. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1414. :param args: a list containing the application args at startup
  1415. :return: None
  1416. """
  1417. if args is not None:
  1418. args_to_process = args
  1419. else:
  1420. args_to_process = App.args
  1421. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1422. for argument in args_to_process:
  1423. if '.FlatPrj'.lower() in argument.lower():
  1424. try:
  1425. project_name = str(argument)
  1426. if project_name == "":
  1427. if silent is False:
  1428. self.inform.emit(_("Cancelled."))
  1429. else:
  1430. # self.open_project(project_name)
  1431. run_from_arg = True
  1432. # self.worker_task.emit({'fcn': self.open_project,
  1433. # 'params': [project_name, run_from_arg]})
  1434. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1435. except Exception as e:
  1436. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1437. elif '.FlatConfig'.lower() in argument.lower():
  1438. try:
  1439. file_name = str(argument)
  1440. if file_name == "":
  1441. if silent is False:
  1442. self.inform.emit(_("Open Config file failed."))
  1443. else:
  1444. run_from_arg = True
  1445. # self.worker_task.emit({'fcn': self.open_config_file,
  1446. # 'params': [file_name, run_from_arg]})
  1447. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1448. except Exception as e:
  1449. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1450. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1451. try:
  1452. file_name = str(argument)
  1453. if file_name == "":
  1454. if silent is False:
  1455. self.inform.emit(_("Open Script file failed."))
  1456. else:
  1457. if silent is False:
  1458. self.on_fileopenscript(name=file_name)
  1459. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1460. self.on_filerunscript(name=file_name)
  1461. except Exception as e:
  1462. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1463. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1464. log.debug("App.on_startup_args() --> Quit event.")
  1465. sys.exit()
  1466. elif 'save'.lower() in argument.lower():
  1467. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1468. self.preferencesUiManager.save_defaults()
  1469. else:
  1470. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1471. proc_arg = argument.lower()
  1472. for ext in exc_list:
  1473. proc_ext = ext.replace(' ', '')
  1474. proc_ext = '.%s' % proc_ext
  1475. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1476. file_name = str(argument)
  1477. if file_name == "":
  1478. if silent is False:
  1479. self.inform.emit(_("Open Excellon file failed."))
  1480. else:
  1481. self.on_fileopenexcellon(name=file_name, signal=None)
  1482. return
  1483. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1484. for ext in gco_list:
  1485. proc_ext = ext.replace(' ', '')
  1486. proc_ext = '.%s' % proc_ext
  1487. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1488. file_name = str(argument)
  1489. if file_name == "":
  1490. if silent is False:
  1491. self.inform.emit(_("Open GCode file failed."))
  1492. else:
  1493. self.on_fileopengcode(name=file_name, signal=None)
  1494. return
  1495. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1496. for ext in grb_list:
  1497. proc_ext = ext.replace(' ', '')
  1498. proc_ext = '.%s' % proc_ext
  1499. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1500. file_name = str(argument)
  1501. if file_name == "":
  1502. if silent is False:
  1503. self.inform.emit(_("Open Gerber file failed."))
  1504. else:
  1505. self.on_fileopengerber(name=file_name, signal=None)
  1506. return
  1507. # if it reached here without already returning then the app was registered with a file that it does not
  1508. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1509. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1510. # for arg in args_to_process:
  1511. # if 'FlatCAM.exe' in arg:
  1512. # continue
  1513. # else:
  1514. # sys.exit(2)
  1515. def set_ui_title(self, name):
  1516. """
  1517. Sets the title of the main window.
  1518. :param name: String that store the project path and project name
  1519. :return: None
  1520. """
  1521. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1522. (self.version,
  1523. ('BETA' if self.beta else ''),
  1524. platform.architecture()[0],
  1525. self.engine,
  1526. name)
  1527. )
  1528. def on_app_restart(self):
  1529. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1530. # be left in the SySTray
  1531. try:
  1532. self.trayIcon.hide()
  1533. except Exception:
  1534. pass
  1535. fcTranslate.restart_program(app=self)
  1536. def clear_pool(self):
  1537. """
  1538. Clear the multiprocessing pool and calls garbage collector.
  1539. :return: None
  1540. """
  1541. self.pool.close()
  1542. self.pool = Pool()
  1543. self.pool_recreated.emit(self.pool)
  1544. gc.collect()
  1545. def install_tools(self):
  1546. """
  1547. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1548. Instantiation of the Tools classes.
  1549. The order that the tools are installed is important as they can depend on each other install position.
  1550. :return: None
  1551. """
  1552. self.distance_tool = Distance(self)
  1553. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1554. before=self.ui.menueditorigin,
  1555. separator=False)
  1556. self.distance_min_tool = DistanceMin(self)
  1557. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1558. pos=self.ui.menuedit,
  1559. before=self.ui.menueditorigin,
  1560. separator=True)
  1561. self.dblsidedtool = DblSidedTool(self)
  1562. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1563. self.cal_exc_tool = ToolCalibration(self)
  1564. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1565. before=self.dblsidedtool.menuAction,
  1566. separator=False)
  1567. self.align_objects_tool = AlignObjects(self)
  1568. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1569. self.edrills_tool = ToolExtractDrills(self)
  1570. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1571. self.panelize_tool = Panelize(self)
  1572. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1573. self.film_tool = Film(self)
  1574. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1575. self.paste_tool = SolderPaste(self)
  1576. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1577. self.calculator_tool = ToolCalculator(self)
  1578. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1579. self.sub_tool = ToolSub(self)
  1580. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1581. pos=self.ui.menutool, separator=True)
  1582. self.rules_tool = RulesCheck(self)
  1583. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1584. pos=self.ui.menutool, separator=False)
  1585. self.optimal_tool = ToolOptimal(self)
  1586. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1587. pos=self.ui.menutool, separator=True)
  1588. self.move_tool = ToolMove(self)
  1589. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1590. before=self.ui.menueditorigin, separator=True)
  1591. self.cutout_tool = CutOut(self)
  1592. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1593. before=self.sub_tool.menuAction)
  1594. self.ncclear_tool = NonCopperClear(self)
  1595. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1596. before=self.sub_tool.menuAction, separator=True)
  1597. self.paint_tool = ToolPaint(self)
  1598. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1599. before=self.sub_tool.menuAction, separator=True)
  1600. self.copper_thieving_tool = ToolCopperThieving(self)
  1601. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1602. pos=self.ui.menutool)
  1603. self.fiducial_tool = ToolFiducials(self)
  1604. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1605. pos=self.ui.menutool)
  1606. self.qrcode_tool = QRCode(self)
  1607. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1608. pos=self.ui.menutool)
  1609. self.punch_tool = ToolPunchGerber(self)
  1610. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1611. self.invert_tool = ToolInvertGerber(self)
  1612. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1613. self.transform_tool = ToolTransform(self)
  1614. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1615. pos=self.ui.menuoptions, separator=True)
  1616. self.properties_tool = Properties(self)
  1617. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1618. pos=self.ui.menuoptions)
  1619. self.pdf_tool = ToolPDF(self)
  1620. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1621. pos=self.ui.menufileimport,
  1622. separator=True)
  1623. self.image_tool = ToolImage(self)
  1624. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1625. pos=self.ui.menufileimport,
  1626. separator=True)
  1627. self.pcb_wizard_tool = PcbWizard(self)
  1628. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1629. pos=self.ui.menufileimport)
  1630. self.log.debug("Tools are installed.")
  1631. def remove_tools(self):
  1632. """
  1633. Will remove all the actions in the Tool menu.
  1634. :return: None
  1635. """
  1636. for act in self.ui.menutool.actions():
  1637. self.ui.menutool.removeAction(act)
  1638. def init_tools(self):
  1639. """
  1640. Initialize the Tool tab in the notebook side of the central widget.
  1641. Remove the actions in the Tools menu.
  1642. Instantiate again the FlatCAM tools (plugins).
  1643. All this is required when changing the layout: standard, compact etc.
  1644. :return: None
  1645. """
  1646. log.debug("init_tools()")
  1647. # delete the data currently in the Tools Tab and the Tab itself
  1648. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1649. if widget is not None:
  1650. widget.deleteLater()
  1651. self.ui.notebook.removeTab(2)
  1652. # rebuild the Tools Tab
  1653. self.ui.tool_tab = QtWidgets.QWidget()
  1654. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1655. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1656. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1657. self.ui.tool_scroll_area = VerticalScrollArea()
  1658. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1659. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1660. # first remove all of them
  1661. self.remove_tools()
  1662. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1663. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1664. '&Command Line\tS')
  1665. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1666. # third install all of them
  1667. try:
  1668. self.install_tools()
  1669. except AttributeError:
  1670. pass
  1671. self.log.debug("Tools are initialized.")
  1672. # def parse_system_fonts(self):
  1673. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1674. # 'params': []})
  1675. def connect_toolbar_signals(self):
  1676. """
  1677. Reconnect the signals to the actions in the toolbar.
  1678. This has to be done each time after the FlatCAM tools are removed/installed.
  1679. :return: None
  1680. """
  1681. # Toolbar
  1682. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1683. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1684. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1685. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1686. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1687. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1688. self.ui.replot_btn.triggered.connect(self.plot_all)
  1689. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1690. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1691. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1692. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1693. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1694. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1695. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1696. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1697. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1698. self.ui.delete_btn.triggered.connect(self.on_delete)
  1699. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1700. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1701. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1702. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1703. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1704. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1705. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1706. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1707. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1708. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1709. # Tools Toolbar Signals
  1710. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1711. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1712. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1713. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1714. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1715. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1716. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1717. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1718. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1719. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1720. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1721. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1722. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1723. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1724. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1725. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1726. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1727. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1728. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1729. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1730. def object2editor(self):
  1731. """
  1732. Send the current Geometry or Excellon object (if any) into the it's editor.
  1733. :return: None
  1734. """
  1735. self.defaults.report_usage("object2editor()")
  1736. # disable the objects menu as it may interfere with the Editors
  1737. self.ui.menuobjects.setDisabled(True)
  1738. edited_object = self.collection.get_active()
  1739. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1740. isinstance(edited_object, ExcellonObject):
  1741. pass
  1742. else:
  1743. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1744. return
  1745. if isinstance(edited_object, GeometryObject):
  1746. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1747. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1748. # we set the notebook to hidden
  1749. # self.ui.splitter.setSizes([0, 1])
  1750. if edited_object.multigeo is True:
  1751. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1752. if len(sel_rows) > 1:
  1753. self.inform.emit('[WARNING_NOTCL] %s' %
  1754. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1755. "is not possible.\n"
  1756. "Edit only one geometry at a time."))
  1757. # determine the tool dia of the selected tool
  1758. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1759. # now find the key in the edited_object.tools that has this tooldia
  1760. multi_tool = 1
  1761. for tool in edited_object.tools:
  1762. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1763. multi_tool = tool
  1764. break
  1765. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1766. else:
  1767. self.geo_editor.edit_fcgeometry(edited_object)
  1768. # set call source to the Editor we go into
  1769. self.call_source = 'geo_editor'
  1770. elif isinstance(edited_object, ExcellonObject):
  1771. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1772. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1773. if self.ui.splitter.sizes()[0] == 0:
  1774. self.ui.splitter.setSizes([1, 1])
  1775. self.exc_editor.edit_fcexcellon(edited_object)
  1776. # set call source to the Editor we go into
  1777. self.call_source = 'exc_editor'
  1778. elif isinstance(edited_object, GerberObject):
  1779. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1780. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1781. if self.ui.splitter.sizes()[0] == 0:
  1782. self.ui.splitter.setSizes([1, 1])
  1783. self.grb_editor.edit_fcgerber(edited_object)
  1784. # set call source to the Editor we go into
  1785. self.call_source = 'grb_editor'
  1786. # reset the following variables so the UI is built again after edit
  1787. edited_object.ui_build = False
  1788. edited_object.build_aperture_storage = False
  1789. # make sure that we can't select another object while in Editor Mode:
  1790. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1791. self.ui.project_frame.setDisabled(True)
  1792. # delete any selection shape that might be active as they are not relevant in Editor
  1793. self.delete_selection_shape()
  1794. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1795. self.ui.plot_tab_area.protectTab(0)
  1796. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1797. self.should_we_save = True
  1798. def editor2object(self, cleanup=None):
  1799. """
  1800. Transfers the Geometry or Excellon from it's editor to the current object.
  1801. :return: None
  1802. """
  1803. self.defaults.report_usage("editor2object()")
  1804. # re-enable the objects menu that was disabled on entry in Editor mode
  1805. self.ui.menuobjects.setDisabled(False)
  1806. # do not update a geometry or excellon object unless it comes out of an editor
  1807. if self.call_source != 'app':
  1808. edited_obj = self.collection.get_active()
  1809. if cleanup is None:
  1810. msgbox = QtWidgets.QMessageBox()
  1811. msgbox.setText(_("Do you want to save the edited object?"))
  1812. msgbox.setWindowTitle(_("Close Editor"))
  1813. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1814. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1815. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1816. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1817. msgbox.setDefaultButton(bt_yes)
  1818. msgbox.exec_()
  1819. response = msgbox.clickedButton()
  1820. if response == bt_yes:
  1821. # clean the Tools Tab
  1822. self.ui.tool_scroll_area.takeWidget()
  1823. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1824. self.ui.notebook.setTabText(2, "Tool")
  1825. if isinstance(edited_obj, GeometryObject):
  1826. obj_type = "Geometry"
  1827. if cleanup is None:
  1828. self.geo_editor.update_fcgeometry(edited_obj)
  1829. # self.geo_editor.update_options(edited_obj)
  1830. self.geo_editor.deactivate()
  1831. # restore GUI to the Selected TAB
  1832. # Remove anything else in the GUI
  1833. self.ui.tool_scroll_area.takeWidget()
  1834. # update the geo object options so it is including the bounding box values
  1835. try:
  1836. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1837. edited_obj.options['xmin'] = xmin
  1838. edited_obj.options['ymin'] = ymin
  1839. edited_obj.options['xmax'] = xmax
  1840. edited_obj.options['ymax'] = ymax
  1841. except AttributeError as e:
  1842. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1843. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1844. edited_obj.build_ui()
  1845. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1846. elif isinstance(edited_obj, GerberObject):
  1847. obj_type = "Gerber"
  1848. if cleanup is None:
  1849. self.grb_editor.update_fcgerber()
  1850. self.grb_editor.update_options(edited_obj)
  1851. self.grb_editor.deactivate_grb_editor()
  1852. # delete the old object (the source object) if it was an empty one
  1853. try:
  1854. if len(edited_obj.solid_geometry) == 0:
  1855. old_name = edited_obj.options['name']
  1856. self.collection.set_active(old_name)
  1857. self.collection.delete_active()
  1858. except TypeError:
  1859. # if the solid_geometry is a single Polygon the len() will not work
  1860. # in any case, falling here means that we have something in the solid_geometry, even if only
  1861. # a single Polygon, therefore we pass this
  1862. pass
  1863. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1864. # restore GUI to the Selected TAB
  1865. # Remove anything else in the GUI
  1866. self.ui.selected_scroll_area.takeWidget()
  1867. elif isinstance(edited_obj, ExcellonObject):
  1868. obj_type = "Excellon"
  1869. if cleanup is None:
  1870. self.exc_editor.update_fcexcellon(edited_obj)
  1871. # self.exc_editor.update_options(edited_obj)
  1872. self.exc_editor.deactivate()
  1873. # restore GUI to the Selected TAB
  1874. # Remove anything else in the GUI
  1875. self.ui.tool_scroll_area.takeWidget()
  1876. # delete the old object (the source object) if it was an empty one
  1877. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1878. old_name = edited_obj.options['name']
  1879. self.collection.delete_by_name(name=old_name)
  1880. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1881. else:
  1882. self.inform.emit('[WARNING_NOTCL] %s' %
  1883. _("Select a Gerber, Geometry or Excellon Object to update."))
  1884. return
  1885. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1886. elif response == bt_no:
  1887. # clean the Tools Tab
  1888. self.ui.tool_scroll_area.takeWidget()
  1889. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1890. self.ui.notebook.setTabText(2, "Tool")
  1891. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1892. if isinstance(edited_obj, GeometryObject):
  1893. self.geo_editor.deactivate()
  1894. edited_obj.build_ui()
  1895. elif isinstance(edited_obj, GerberObject):
  1896. self.grb_editor.deactivate_grb_editor()
  1897. edited_obj.build_ui()
  1898. elif isinstance(edited_obj, ExcellonObject):
  1899. self.exc_editor.deactivate()
  1900. edited_obj.build_ui()
  1901. else:
  1902. self.inform.emit('[WARNING_NOTCL] %s' %
  1903. _("Select a Gerber, Geometry or Excellon Object to update."))
  1904. return
  1905. elif response == bt_cancel:
  1906. return
  1907. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1908. # edited_obj.build_ui()
  1909. # Switch notebook to Selected page
  1910. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1911. else:
  1912. if isinstance(edited_obj, GeometryObject):
  1913. self.geo_editor.deactivate()
  1914. elif isinstance(edited_obj, GerberObject):
  1915. self.grb_editor.deactivate_grb_editor()
  1916. elif isinstance(edited_obj, ExcellonObject):
  1917. self.exc_editor.deactivate()
  1918. else:
  1919. self.inform.emit('[WARNING_NOTCL] %s' %
  1920. _("Select a Gerber, Geometry or Excellon Object to update."))
  1921. return
  1922. # if notebook is hidden we show it
  1923. if self.ui.splitter.sizes()[0] == 0:
  1924. self.ui.splitter.setSizes([1, 1])
  1925. # restore the call_source to app
  1926. self.call_source = 'app'
  1927. edited_obj.plot()
  1928. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1929. self.ui.plot_tab_area.protectTab(0)
  1930. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1931. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1932. self.ui.project_frame.setDisabled(False)
  1933. def get_last_folder(self):
  1934. """
  1935. Get the folder path from where the last file was opened.
  1936. :return: String, last opened folder path
  1937. """
  1938. return self.defaults["global_last_folder"]
  1939. def get_last_save_folder(self):
  1940. """
  1941. Get the folder path from where the last file was saved.
  1942. :return: String, last saved folder path
  1943. """
  1944. loc = self.defaults["global_last_save_folder"]
  1945. if loc is None:
  1946. loc = self.defaults["global_last_folder"]
  1947. if loc is None:
  1948. loc = os.path.dirname(__file__)
  1949. return loc
  1950. def info(self, msg):
  1951. """
  1952. Informs the user. Normally on the status bar, optionally
  1953. also on the shell.
  1954. :param msg: Text to write.
  1955. :return: None
  1956. """
  1957. # Type of message in brackets at the beginning of the message.
  1958. match = re.search(r"\[(.*)\](.*)", msg)
  1959. if match:
  1960. level = match.group(1)
  1961. msg_ = match.group(2)
  1962. self.ui.fcinfo.set_status(str(msg_), level=level)
  1963. if level.lower() == "error":
  1964. self.shell_message(msg, error=True, show=True)
  1965. elif level.lower() == "warning":
  1966. self.shell_message(msg, warning=True, show=True)
  1967. elif level.lower() == "error_notcl":
  1968. self.shell_message(msg, error=True, show=False)
  1969. elif level.lower() == "warning_notcl":
  1970. self.shell_message(msg, warning=True, show=False)
  1971. elif level.lower() == "success":
  1972. self.shell_message(msg, success=True, show=False)
  1973. elif level.lower() == "selected":
  1974. self.shell_message(msg, selected=True, show=False)
  1975. else:
  1976. self.shell_message(msg, show=False)
  1977. else:
  1978. self.ui.fcinfo.set_status(str(msg), level="info")
  1979. # make sure that if the message is to clear the infobar with a space
  1980. # is not printed over and over on the shell
  1981. if msg != '':
  1982. self.shell_message(msg)
  1983. def restore_toolbar_view(self):
  1984. """
  1985. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1986. was saved in the defaults dictionary.
  1987. :return: None
  1988. """
  1989. tb = self.defaults["global_toolbar_view"]
  1990. if tb & 1:
  1991. self.ui.toolbarfile.setVisible(True)
  1992. else:
  1993. self.ui.toolbarfile.setVisible(False)
  1994. if tb & 2:
  1995. self.ui.toolbargeo.setVisible(True)
  1996. else:
  1997. self.ui.toolbargeo.setVisible(False)
  1998. if tb & 4:
  1999. self.ui.toolbarview.setVisible(True)
  2000. else:
  2001. self.ui.toolbarview.setVisible(False)
  2002. if tb & 8:
  2003. self.ui.toolbartools.setVisible(True)
  2004. else:
  2005. self.ui.toolbartools.setVisible(False)
  2006. if tb & 16:
  2007. self.ui.exc_edit_toolbar.setVisible(True)
  2008. else:
  2009. self.ui.exc_edit_toolbar.setVisible(False)
  2010. if tb & 32:
  2011. self.ui.geo_edit_toolbar.setVisible(True)
  2012. else:
  2013. self.ui.geo_edit_toolbar.setVisible(False)
  2014. if tb & 64:
  2015. self.ui.grb_edit_toolbar.setVisible(True)
  2016. else:
  2017. self.ui.grb_edit_toolbar.setVisible(False)
  2018. if tb & 128:
  2019. self.ui.snap_toolbar.setVisible(True)
  2020. else:
  2021. self.ui.snap_toolbar.setVisible(False)
  2022. if tb & 256:
  2023. self.ui.toolbarshell.setVisible(True)
  2024. else:
  2025. self.ui.toolbarshell.setVisible(False)
  2026. def on_import_preferences(self):
  2027. """
  2028. Loads the application default settings from a saved file into
  2029. ``self.defaults`` dictionary.
  2030. :return: None
  2031. """
  2032. self.defaults.report_usage("on_import_preferences")
  2033. App.log.debug("App.on_import_preferences()")
  2034. # Show file chooser
  2035. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2036. try:
  2037. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2038. directory=self.data_path,
  2039. filter=filter_)
  2040. except TypeError:
  2041. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2042. filter=filter_)
  2043. filename = str(filename)
  2044. if filename == "":
  2045. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2046. return
  2047. # Load in the defaults from the chosen file
  2048. self.defaults.load(filename=filename)
  2049. self.preferencesUiManager.on_preferences_edited()
  2050. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2051. def on_export_preferences(self):
  2052. """
  2053. Save the defaults dictionary to a file.
  2054. :return: None
  2055. """
  2056. self.defaults.report_usage("on_export_preferences")
  2057. App.log.debug("on_export_preferences()")
  2058. # defaults_file_content = None
  2059. # Show file chooser
  2060. date = str(datetime.today()).rpartition('.')[0]
  2061. date = ''.join(c for c in date if c not in ':-')
  2062. date = date.replace(' ', '_')
  2063. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2064. try:
  2065. filename, _f = FCFileSaveDialog.get_saved_filename(
  2066. caption=_("Export FlatCAM Preferences"),
  2067. directory=self.data_path + '/preferences_' + date,
  2068. filter=filter__
  2069. )
  2070. except TypeError:
  2071. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2072. filename = str(filename)
  2073. if filename == "":
  2074. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2075. return
  2076. # Update options
  2077. self.preferencesUiManager.defaults_read_form()
  2078. self.defaults.propagate_defaults()
  2079. # Save update options
  2080. try:
  2081. self.defaults.write(filename=filename)
  2082. except Exception:
  2083. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2084. return
  2085. if self.defaults["global_open_style"] is False:
  2086. self.file_opened.emit("preferences", filename)
  2087. self.file_saved.emit("preferences", filename)
  2088. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2089. def save_to_file(self, content_to_save, txt_content):
  2090. """
  2091. Save something to a file.
  2092. :return: None
  2093. """
  2094. self.defaults.report_usage("save_to_file")
  2095. App.log.debug("save_to_file()")
  2096. self.date = str(datetime.today()).rpartition('.')[0]
  2097. self.date = ''.join(c for c in self.date if c not in ':-')
  2098. self.date = self.date.replace(' ', '_')
  2099. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2100. path_to_save = self.defaults["global_last_save_folder"] if\
  2101. self.defaults["global_last_save_folder"] is not None else self.data_path
  2102. try:
  2103. filename, _f = FCFileSaveDialog.get_saved_filename(
  2104. caption=_("Save to file"),
  2105. directory=path_to_save + '/file_' + self.date,
  2106. filter=filter__
  2107. )
  2108. except TypeError:
  2109. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2110. filename = str(filename)
  2111. if filename == "":
  2112. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2113. return
  2114. else:
  2115. try:
  2116. with open(filename, 'w') as f:
  2117. ___ = f.read()
  2118. except PermissionError:
  2119. self.inform.emit('[WARNING] %s' %
  2120. _("Permission denied, saving not possible.\n"
  2121. "Most likely another app is holding the file open and not accessible."))
  2122. return
  2123. except IOError:
  2124. App.log.debug('Creating a new file ...')
  2125. f = open(filename, 'w')
  2126. f.close()
  2127. except Exception:
  2128. e = sys.exc_info()[0]
  2129. App.log.error("Could not load the file.")
  2130. App.log.error(str(e))
  2131. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2132. return
  2133. # Save content
  2134. if filename.rpartition('.')[2].lower() == 'html':
  2135. file_content = content_to_save
  2136. else:
  2137. file_content = txt_content
  2138. try:
  2139. with open(filename, "w") as f:
  2140. f.write(file_content)
  2141. except Exception:
  2142. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2143. return
  2144. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2145. def save_geometry(self, x, y, width, height, notebook_width):
  2146. """
  2147. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2148. launch of the application.
  2149. :param x: X position of the main window
  2150. :param y: Y position of the main window
  2151. :param width: width of the main window
  2152. :param height: height of the main window
  2153. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2154. :return: None
  2155. """
  2156. self.defaults["global_def_win_x"] = x
  2157. self.defaults["global_def_win_y"] = y
  2158. self.defaults["global_def_win_w"] = width
  2159. self.defaults["global_def_win_h"] = height
  2160. self.defaults["global_def_notebook_width"] = notebook_width
  2161. self.preferencesUiManager.save_defaults()
  2162. def restore_main_win_geom(self):
  2163. try:
  2164. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2165. self.defaults["global_def_win_y"],
  2166. self.defaults["global_def_win_w"],
  2167. self.defaults["global_def_win_h"])
  2168. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2169. except KeyError as e:
  2170. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2171. def message_dialog(self, title, message, kind="info"):
  2172. """
  2173. Builds and show a custom QMessageBox to be used in FlatCAM.
  2174. :param title: title of the QMessageBox
  2175. :param message: message to be displayed
  2176. :param kind: type of QMessageBox; will display a specific icon.
  2177. :return:
  2178. """
  2179. icon = {"info": QtWidgets.QMessageBox.Information,
  2180. "warning": QtWidgets.QMessageBox.Warning,
  2181. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2182. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2183. dlg.setText(message)
  2184. dlg.exec_()
  2185. def register_recent(self, kind, filename):
  2186. """
  2187. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2188. dictionary.
  2189. :param kind: type of file that was opened
  2190. :param filename: the path and file name for the file that was opened
  2191. :return:
  2192. """
  2193. self.log.debug("register_recent()")
  2194. self.log.debug(" %s" % kind)
  2195. self.log.debug(" %s" % filename)
  2196. record = {'kind': str(kind), 'filename': str(filename)}
  2197. if record in self.recent:
  2198. return
  2199. if record in self.recent_projects:
  2200. return
  2201. if record['kind'] == 'project':
  2202. self.recent_projects.insert(0, record)
  2203. else:
  2204. self.recent.insert(0, record)
  2205. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2206. self.recent.pop()
  2207. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2208. self.recent_projects.pop()
  2209. try:
  2210. f = open(self.data_path + '/recent.json', 'w')
  2211. except IOError:
  2212. App.log.error("Failed to open recent items file for writing.")
  2213. self.inform.emit('[ERROR_NOTCL] %s' %
  2214. _('Failed to open recent files file for writing.'))
  2215. return
  2216. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2217. f.close()
  2218. try:
  2219. fp = open(self.data_path + '/recent_projects.json', 'w')
  2220. except IOError:
  2221. App.log.error("Failed to open recent items file for writing.")
  2222. self.inform.emit('[ERROR_NOTCL] %s' %
  2223. _('Failed to open recent projects file for writing.'))
  2224. return
  2225. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2226. fp.close()
  2227. # Re-build the recent items menu
  2228. self.setup_recent_items()
  2229. def new_object(self, kind, name, initialize, plot=True, autoselected=True):
  2230. """
  2231. Creates a new specialized FlatCAMObj and attaches it to the application,
  2232. this is, updates the GUI accordingly, any other records and plots it.
  2233. This method is thread-safe.
  2234. Notes:
  2235. * If the name is in use, the self.collection will modify it
  2236. when appending it to the collection. There is no need to handle
  2237. name conflicts here.
  2238. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2239. :type kind: str
  2240. :param name: Name for the object.
  2241. :type name: str
  2242. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2243. The function is called with 2 parameters: the new object and the App instance.
  2244. :type initialize: function
  2245. :param plot: If to plot the resulting object
  2246. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2247. self.collection
  2248. :return: None
  2249. :rtype: None
  2250. """
  2251. App.log.debug("new_object()")
  2252. obj_plot = plot
  2253. obj_autoselected = autoselected
  2254. t0 = time.time() # Debug
  2255. # ## Create object
  2256. classdict = {
  2257. "gerber": GerberObject,
  2258. "excellon": ExcellonObject,
  2259. "cncjob": CNCJobObject,
  2260. "geometry": GeometryObject,
  2261. "script": ScriptObject,
  2262. "document": DocumentObject
  2263. }
  2264. App.log.debug("Calling object constructor...")
  2265. # Object creation/instantiation
  2266. obj = classdict[kind](name)
  2267. obj.units = self.options["units"]
  2268. # IMPORTANT
  2269. # The key names in defaults and options dictionary's are not random:
  2270. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2271. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2272. # copied to self.options. After that, below, depending on the type of
  2273. # object that is created, it will strip the name of the object and the underline (if the original key was
  2274. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2275. # "toolchange"
  2276. for option in self.options:
  2277. if option.find(kind + "_") == 0:
  2278. oname = option[len(kind) + 1:]
  2279. obj.options[oname] = self.options[option]
  2280. obj.isHovering = False
  2281. obj.notHovering = True
  2282. # Initialize as per user request
  2283. # User must take care to implement initialize
  2284. # in a thread-safe way as is is likely that we
  2285. # have been invoked in a separate thread.
  2286. t1 = time.time()
  2287. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2288. try:
  2289. return_value = initialize(obj, self)
  2290. except Exception as e:
  2291. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2292. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2293. msg += traceback.format_exc()
  2294. self.inform.emit(msg)
  2295. return "fail"
  2296. t2 = time.time()
  2297. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2298. if return_value == 'fail':
  2299. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2300. return "fail"
  2301. # Check units and convert if necessary
  2302. # This condition CAN be true because initialize() can change obj.units
  2303. if self.options["units"].upper() != obj.units.upper():
  2304. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2305. obj.convert_units(self.options["units"])
  2306. t3 = time.time()
  2307. self.log.debug("%f seconds converting units." % (t3 - t2))
  2308. # Create the bounding box for the object and then add the results to the obj.options
  2309. # But not for Scripts or for Documents
  2310. if kind != 'document' and kind != 'script':
  2311. try:
  2312. xmin, ymin, xmax, ymax = obj.bounds()
  2313. obj.options['xmin'] = xmin
  2314. obj.options['ymin'] = ymin
  2315. obj.options['xmax'] = xmax
  2316. obj.options['ymax'] = ymax
  2317. except Exception as e:
  2318. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2319. return "fail"
  2320. try:
  2321. if kind == 'excellon':
  2322. obj.fill_color = self.defaults["excellon_plot_fill"]
  2323. obj.outline_color = self.defaults["excellon_plot_line"]
  2324. if kind == 'gerber':
  2325. obj.fill_color = self.defaults["gerber_plot_fill"]
  2326. obj.outline_color = self.defaults["gerber_plot_line"]
  2327. except Exception as e:
  2328. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2329. # update the KeyWords list with the name of the file
  2330. self.myKeywords.append(obj.options['name'])
  2331. log.debug("Moving new object back to main thread.")
  2332. # Move the object to the main thread and let the app know that it is available.
  2333. obj.moveToThread(self.main_thread)
  2334. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2335. return obj
  2336. def new_excellon_object(self):
  2337. """
  2338. Creates a new, blank Excellon object.
  2339. :return: None
  2340. """
  2341. self.defaults.report_usage("new_excellon_object()")
  2342. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2343. def new_geometry_object(self):
  2344. """
  2345. Creates a new, blank and single-tool Geometry object.
  2346. :return: None
  2347. """
  2348. self.defaults.report_usage("new_geometry_object()")
  2349. def initialize(obj, app):
  2350. obj.multitool = False
  2351. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2352. def new_gerber_object(self):
  2353. """
  2354. Creates a new, blank Gerber object.
  2355. :return: None
  2356. """
  2357. self.defaults.report_usage("new_gerber_object()")
  2358. def initialize(grb_obj, app):
  2359. grb_obj.multitool = False
  2360. grb_obj.source_file = []
  2361. grb_obj.multigeo = False
  2362. grb_obj.follow = False
  2363. grb_obj.apertures = {}
  2364. grb_obj.solid_geometry = []
  2365. try:
  2366. grb_obj.options['xmin'] = 0
  2367. grb_obj.options['ymin'] = 0
  2368. grb_obj.options['xmax'] = 0
  2369. grb_obj.options['ymax'] = 0
  2370. except KeyError:
  2371. pass
  2372. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2373. def new_script_object(self, name=None, text=None):
  2374. """
  2375. Creates a new, blank TCL Script object.
  2376. :param name: a name for the new object
  2377. :param text: pass a source file to the newly created script to be loaded in it
  2378. :return: None
  2379. """
  2380. self.defaults.report_usage("new_script_object()")
  2381. if text is not None:
  2382. new_source_file = text
  2383. else:
  2384. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2385. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2386. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2387. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2388. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2389. # "ListSys, MillDrills,\n" \
  2390. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2391. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2392. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2393. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2394. # "# SubtractRectangle, Version, WriteGCode\n"
  2395. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2396. '# %s:\n' % _('TCL Tutorial is here') + \
  2397. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2398. '# %s:\n' % _("FlatCAM commands list")
  2399. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2400. "(displayed in Tcl Shell).")
  2401. def initialize(obj, app):
  2402. obj.source_file = deepcopy(new_source_file)
  2403. if name is None:
  2404. outname = 'new_script'
  2405. else:
  2406. outname = name
  2407. self.new_object('script', outname, initialize, plot=False)
  2408. def new_document_object(self):
  2409. """
  2410. Creates a new, blank Document object.
  2411. :return: None
  2412. """
  2413. self.defaults.report_usage("new_document_object()")
  2414. def initialize(obj, app):
  2415. obj.source_file = ""
  2416. self.new_object('document', 'new_document', initialize, plot=False)
  2417. def on_object_created(self, obj, plot, auto_select):
  2418. """
  2419. Event callback for object creation.
  2420. It will add the new object to the collection. After that it will plot the object in a threaded way
  2421. :param obj: The newly created FlatCAM object.
  2422. :param plot: if the newly create object t obe plotted
  2423. :param auto_select: if the newly created object to be autoselected after creation
  2424. :return: None
  2425. """
  2426. t0 = time.time() # DEBUG
  2427. self.log.debug("on_object_created()")
  2428. # The Collection might change the name if there is a collision
  2429. self.collection.append(obj)
  2430. # after adding the object to the collection always update the list of objects that are in the collection
  2431. self.all_objects_list = self.collection.get_list()
  2432. # self.inform.emit('[selected] %s created & selected: %s' %
  2433. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2434. if obj.kind == 'gerber':
  2435. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2436. kind=obj.kind.capitalize(),
  2437. color='green',
  2438. name=str(obj.options['name']), tx=_("created/selected"))
  2439. )
  2440. elif obj.kind == 'excellon':
  2441. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2442. kind=obj.kind.capitalize(),
  2443. color='brown',
  2444. name=str(obj.options['name']), tx=_("created/selected"))
  2445. )
  2446. elif obj.kind == 'cncjob':
  2447. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2448. kind=obj.kind.capitalize(),
  2449. color='blue',
  2450. name=str(obj.options['name']), tx=_("created/selected"))
  2451. )
  2452. elif obj.kind == 'geometry':
  2453. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2454. kind=obj.kind.capitalize(),
  2455. color='red',
  2456. name=str(obj.options['name']), tx=_("created/selected"))
  2457. )
  2458. elif obj.kind == 'script':
  2459. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2460. kind=obj.kind.capitalize(),
  2461. color='orange',
  2462. name=str(obj.options['name']), tx=_("created/selected"))
  2463. )
  2464. elif obj.kind == 'document':
  2465. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2466. kind=obj.kind.capitalize(),
  2467. color='darkCyan',
  2468. name=str(obj.options['name']), tx=_("created/selected"))
  2469. )
  2470. # update the SHELL auto-completer model with the name of the new object
  2471. self.shell._edit.set_model_data(self.myKeywords)
  2472. if auto_select:
  2473. # select the just opened object but deselect the previous ones
  2474. self.collection.set_all_inactive()
  2475. self.collection.set_active(obj.options["name"])
  2476. else:
  2477. self.collection.set_all_inactive()
  2478. # here it is done the object plotting
  2479. def worker_task(t_obj):
  2480. with self.proc_container.new(_("Plotting")):
  2481. if isinstance(t_obj, CNCJobObject):
  2482. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2483. else:
  2484. t_obj.plot()
  2485. t1 = time.time() # DEBUG
  2486. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2487. self.object_plotted.emit(t_obj)
  2488. # Send to worker
  2489. # self.worker.add_task(worker_task, [self])
  2490. if plot is True:
  2491. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2492. def on_object_changed(self, obj):
  2493. """
  2494. Called whenever the geometry of the object was changed in some way.
  2495. This require the update of it's bounding values so it can be the selected on canvas.
  2496. Update the bounding box data from obj.options
  2497. :param obj: the object that was changed
  2498. :return: None
  2499. """
  2500. xmin, ymin, xmax, ymax = obj.bounds()
  2501. obj.options['xmin'] = xmin
  2502. obj.options['ymin'] = ymin
  2503. obj.options['xmax'] = xmax
  2504. obj.options['ymax'] = ymax
  2505. log.debug("Object changed, updating the bounding box data on self.options")
  2506. # delete the old selection shape
  2507. self.delete_selection_shape()
  2508. self.should_we_save = True
  2509. def on_object_plotted(self):
  2510. """
  2511. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2512. :return: None
  2513. """
  2514. self.on_zoom_fit(None)
  2515. def on_about(self):
  2516. """
  2517. Displays the "about" dialog found in the Menu --> Help.
  2518. :return: None
  2519. """
  2520. self.defaults.report_usage("on_about")
  2521. version = self.version
  2522. version_date = self.version_date
  2523. beta = self.beta
  2524. class AboutDialog(QtWidgets.QDialog):
  2525. def __init__(self, app, parent=None):
  2526. QtWidgets.QDialog.__init__(self, parent)
  2527. self.app = app
  2528. # Icon and title
  2529. self.setWindowIcon(parent.app_icon)
  2530. self.setWindowTitle(_("About FlatCAM"))
  2531. self.resize(600, 200)
  2532. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2533. # self.setStyleSheet(
  2534. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2535. # "background-attachment: fixed"
  2536. # )
  2537. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2538. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2539. # palette = QtGui.QPalette()
  2540. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2541. # self.setPalette(palette)
  2542. logo = QtWidgets.QLabel()
  2543. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2544. title = QtWidgets.QLabel(
  2545. "<font size=8><B>FlatCAM</B></font><BR>"
  2546. "{title}<BR>"
  2547. "<BR>"
  2548. "<BR>"
  2549. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2550. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2551. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2552. "<B>{issue}</B></a><BR>".format(
  2553. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2554. devel=_("Development"),
  2555. down=_("DOWNLOAD"),
  2556. issue=_("Issue tracker"))
  2557. )
  2558. title.setOpenExternalLinks(True)
  2559. closebtn = QtWidgets.QPushButton(_("Close"))
  2560. tab_widget = QtWidgets.QTabWidget()
  2561. description_label = QtWidgets.QLabel(
  2562. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2563. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2564. version=version,
  2565. beta=('BETA' if beta else ''),
  2566. date=version_date,
  2567. arch=platform.architecture()[0])
  2568. )
  2569. description_label.setOpenExternalLinks(True)
  2570. lic_lbl_header = QtWidgets.QLabel(
  2571. '%s:<br>%s<br>' % (
  2572. _('Licensed under the MIT license'),
  2573. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2574. "http://www.opensource.org/licenses/mit-license.php</a>"
  2575. )
  2576. )
  2577. lic_lbl_header.setOpenExternalLinks(True)
  2578. lic_lbl_body = QtWidgets.QLabel(
  2579. _(
  2580. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2581. 'of this software and associated documentation files (the "Software"), to deal\n'
  2582. 'in the Software without restriction, including without limitation the rights\n'
  2583. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2584. 'copies of the Software, and to permit persons to whom the Software is\n'
  2585. 'furnished to do so, subject to the following conditions:\n\n'
  2586. 'The above copyright notice and this permission notice shall be included in\n'
  2587. 'all copies or substantial portions of the Software.\n\n'
  2588. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2589. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2590. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2591. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2592. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2593. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2594. 'THE SOFTWARE.'
  2595. )
  2596. )
  2597. attributions_label = QtWidgets.QLabel(
  2598. _(
  2599. 'Some of the icons used are from the following sources:<br>'
  2600. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2601. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2602. 'title="Flaticon">www.flaticon.com</a></div>'
  2603. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2604. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2605. )
  2606. )
  2607. attributions_label.setOpenExternalLinks(True)
  2608. # layouts
  2609. layout1 = QtWidgets.QVBoxLayout()
  2610. layout1_1 = QtWidgets.QHBoxLayout()
  2611. layout1_2 = QtWidgets.QHBoxLayout()
  2612. layout2 = QtWidgets.QHBoxLayout()
  2613. layout3 = QtWidgets.QHBoxLayout()
  2614. self.setLayout(layout1)
  2615. layout1.addLayout(layout1_1)
  2616. layout1.addLayout(layout1_2)
  2617. layout1.addLayout(layout2)
  2618. layout1.addLayout(layout3)
  2619. layout1_1.addStretch()
  2620. layout1_1.addWidget(description_label)
  2621. layout1_2.addWidget(tab_widget)
  2622. self.splash_tab = QtWidgets.QWidget()
  2623. self.splash_tab.setObjectName("splash_about")
  2624. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2625. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2626. tab_widget.addTab(self.splash_tab, _("Splash"))
  2627. self.programmmers_tab = QtWidgets.QWidget()
  2628. self.programmmers_tab.setObjectName("programmers_about")
  2629. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2630. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2631. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2632. self.translators_tab = QtWidgets.QWidget()
  2633. self.translators_tab.setObjectName("translators_about")
  2634. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2635. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2636. tab_widget.addTab(self.translators_tab, _("Translators"))
  2637. self.license_tab = QtWidgets.QWidget()
  2638. self.license_tab.setObjectName("license_about")
  2639. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2640. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2641. tab_widget.addTab(self.license_tab, _("License"))
  2642. self.attributions_tab = QtWidgets.QWidget()
  2643. self.attributions_tab.setObjectName("attributions_about")
  2644. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2645. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2646. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2647. self.splash_tab_layout.addWidget(logo, stretch=0)
  2648. self.splash_tab_layout.addWidget(title, stretch=1)
  2649. pal = QtGui.QPalette()
  2650. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2651. self.prog_grid_lay = QtWidgets.QGridLayout()
  2652. self.prog_grid_lay.setHorizontalSpacing(20)
  2653. self.prog_grid_lay.setColumnStretch(0, 0)
  2654. self.prog_grid_lay.setColumnStretch(2, 1)
  2655. prog_widget = QtWidgets.QWidget()
  2656. prog_widget.setLayout(self.prog_grid_lay)
  2657. prog_scroll = QtWidgets.QScrollArea()
  2658. prog_scroll.setWidget(prog_widget)
  2659. prog_scroll.setWidgetResizable(True)
  2660. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2661. prog_scroll.setPalette(pal)
  2662. self.programmmers_tab_layout.addWidget(prog_scroll)
  2663. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2664. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2665. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2666. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2704. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2705. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2706. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2707. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2708. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2709. self.translator_grid_lay = QtWidgets.QGridLayout()
  2710. self.translator_grid_lay.setColumnStretch(0, 0)
  2711. self.translator_grid_lay.setColumnStretch(1, 0)
  2712. self.translator_grid_lay.setColumnStretch(2, 1)
  2713. self.translator_grid_lay.setColumnStretch(3, 0)
  2714. # trans_widget = QtWidgets.QWidget()
  2715. # trans_widget.setLayout(self.translator_grid_lay)
  2716. # self.translators_tab_layout.addWidget(trans_widget)
  2717. # self.translators_tab_layout.addStretch()
  2718. trans_widget = QtWidgets.QWidget()
  2719. trans_widget.setLayout(self.translator_grid_lay)
  2720. trans_scroll = QtWidgets.QScrollArea()
  2721. trans_scroll.setWidget(trans_widget)
  2722. trans_scroll.setWidgetResizable(True)
  2723. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2724. trans_scroll.setPalette(pal)
  2725. self.translators_tab_layout.addWidget(trans_scroll)
  2726. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2727. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2728. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2729. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 3, 2)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  2750. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  2751. self.translator_grid_lay.setColumnStretch(0, 0)
  2752. self.translators_tab_layout.addStretch()
  2753. self.license_tab_layout.addWidget(lic_lbl_header)
  2754. self.license_tab_layout.addWidget(lic_lbl_body)
  2755. self.license_tab_layout.addStretch()
  2756. self.attributions_tab_layout.addWidget(attributions_label)
  2757. self.attributions_tab_layout.addStretch()
  2758. layout3.addStretch()
  2759. layout3.addWidget(closebtn)
  2760. closebtn.clicked.connect(self.accept)
  2761. AboutDialog(app=self, parent=self.ui).exec_()
  2762. def install_bookmarks(self, book_dict=None):
  2763. """
  2764. Install the bookmarks actions in the Help menu -> Bookmarks
  2765. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2766. :return: None
  2767. """
  2768. if book_dict is None:
  2769. self.defaults["global_bookmarks"].update(
  2770. {
  2771. '1': ['FlatCAM', "http://flatcam.org"],
  2772. '2': ['Backup Site', ""]
  2773. }
  2774. )
  2775. else:
  2776. self.defaults["global_bookmarks"].clear()
  2777. self.defaults["global_bookmarks"].update(book_dict)
  2778. # first try to disconnect if somehow they get connected from elsewhere
  2779. for act in self.ui.menuhelp_bookmarks.actions():
  2780. try:
  2781. act.triggered.disconnect()
  2782. except TypeError:
  2783. pass
  2784. # clear all actions except the last one who is the Bookmark manager
  2785. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2786. pass
  2787. else:
  2788. self.ui.menuhelp_bookmarks.removeAction(act)
  2789. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2790. if self.defaults["global_bookmarks"]:
  2791. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2792. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2793. # the JSON is first making the keys as strings (therefore I have to use strings too
  2794. # or do the conversion :(
  2795. # )
  2796. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2797. # the '10' entry jsut after '1' therefore ordering as strings
  2798. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2799. key=lambda x: int(x[0]))
  2800. for entry, bookmark in sorted_bookmarks:
  2801. title = bookmark[0]
  2802. weblink = bookmark[1]
  2803. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2804. act.setText(title)
  2805. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2806. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2807. if title == 'Backup Site' and weblink == "":
  2808. act.triggered.connect(self.on_backup_site)
  2809. else:
  2810. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2811. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2812. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2813. def on_bookmarks_manager(self):
  2814. """
  2815. Adds the bookmark manager in a Tab in Plot Area
  2816. :return:
  2817. """
  2818. for idx in range(self.ui.plot_tab_area.count()):
  2819. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2820. # there can be only one instance of Bookmark Manager at one time
  2821. return
  2822. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2823. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2824. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2825. # add the tab if it was closed
  2826. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2827. # delete the absolute and relative position and messages in the infobar
  2828. self.ui.position_label.setText("")
  2829. self.ui.rel_position_label.setText("")
  2830. # Switch plot_area to preferences page
  2831. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2832. def on_backup_site(self):
  2833. msgbox = QtWidgets.QMessageBox()
  2834. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2835. "1. FlatCAM.org website is down\n"
  2836. "2. Someone forked FlatCAM project and wants to point\n"
  2837. "to his own website\n\n"
  2838. "If you can't get any informations about FlatCAM beta\n"
  2839. "use the YouTube channel link from the Help menu."))
  2840. msgbox.setWindowTitle(_("Alternative website"))
  2841. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2842. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2843. msgbox.setDefaultButton(bt_yes)
  2844. msgbox.exec_()
  2845. # response = msgbox.clickedButton()
  2846. def on_file_savedefaults(self):
  2847. """
  2848. Callback for menu item File->Save Defaults. Saves application default options
  2849. ``self.defaults`` to current_defaults.FlatConfig.
  2850. :return: None
  2851. """
  2852. self.preferencesUiManager.save_defaults()
  2853. def final_save(self):
  2854. """
  2855. Callback for doing a preferences save to file whenever the application is about to quit.
  2856. If the project has changes, it will ask the user to save the project.
  2857. :return: None
  2858. """
  2859. if self.save_in_progress:
  2860. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2861. return
  2862. if self.should_we_save and self.collection.get_list():
  2863. msgbox = QtWidgets.QMessageBox()
  2864. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2865. "\n"
  2866. "Do you want to Save the project?"))
  2867. msgbox.setWindowTitle(_("Save changes"))
  2868. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2869. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2870. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2871. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2872. msgbox.setDefaultButton(bt_yes)
  2873. msgbox.exec_()
  2874. response = msgbox.clickedButton()
  2875. if response == bt_yes:
  2876. try:
  2877. self.trayIcon.hide()
  2878. except Exception:
  2879. pass
  2880. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2881. elif response == bt_no:
  2882. try:
  2883. self.trayIcon.hide()
  2884. except Exception:
  2885. pass
  2886. self.quit_application()
  2887. elif response == bt_cancel:
  2888. return
  2889. else:
  2890. try:
  2891. self.trayIcon.hide()
  2892. except Exception:
  2893. pass
  2894. self.quit_application()
  2895. def quit_application(self):
  2896. """
  2897. Called (as a pyslot or not) when the application is quit.
  2898. :return: None
  2899. """
  2900. self.preferencesUiManager.save_defaults(silent=True)
  2901. log.debug("App.quit_application() --> App Defaults saved.")
  2902. if self.cmd_line_headless != 1:
  2903. # save app state to file
  2904. stgs = QSettings("Open Source", "FlatCAM")
  2905. stgs.setValue('saved_gui_state', self.ui.saveState())
  2906. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2907. stgs.setValue(
  2908. 'language',
  2909. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2910. )
  2911. stgs.setValue(
  2912. 'notebook_font_size',
  2913. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2914. )
  2915. stgs.setValue(
  2916. 'axis_font_size',
  2917. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2918. )
  2919. stgs.setValue(
  2920. 'textbox_font_size',
  2921. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2922. )
  2923. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2924. stgs.setValue(
  2925. 'machinist',
  2926. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2927. )
  2928. # This will write the setting to the platform specific storage.
  2929. del stgs
  2930. log.debug("App.quit_application() --> App UI state saved.")
  2931. # try to quit the Socket opened by ArgsThread class
  2932. try:
  2933. self.new_launch.thread_exit = True
  2934. self.new_launch.listener.close()
  2935. except Exception as err:
  2936. log.debug("App.quit_application() --> %s" % str(err))
  2937. # try to quit the QThread that run ArgsThread class
  2938. try:
  2939. self.th.terminate()
  2940. except Exception as e:
  2941. log.debug("App.quit_application() --> %s" % str(e))
  2942. # terminate workers
  2943. self.workers.__del__()
  2944. # quit app by signalling for self.kill_app() method
  2945. # self.close_app_signal.emit()
  2946. QtWidgets.qApp.quit()
  2947. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2948. # we use the following command
  2949. minor_v = sys.version_info.minor
  2950. if minor_v < 8:
  2951. sys.exit(0)
  2952. else:
  2953. os._exit(0) # fix to work with Python 3.8
  2954. @staticmethod
  2955. def kill_app():
  2956. # QtCore.QCoreApplication.quit()
  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. sys.exit(0)
  2961. def on_portable_checked(self, state):
  2962. """
  2963. Callback called when the checkbox in Preferences GUI is checked.
  2964. It will set the application as portable by creating the preferences and recent files in the
  2965. 'config' folder found in the FlatCAM installation folder.
  2966. :param state: boolean, the state of the checkbox when clicked/checked
  2967. :return:
  2968. """
  2969. line_no = 0
  2970. data = None
  2971. if sys.platform != 'win32':
  2972. # this won't work in Linux or MacOS
  2973. return
  2974. # test if the app was frozen and choose the path for the configuration file
  2975. if getattr(sys, "frozen", False) is True:
  2976. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2977. else:
  2978. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2979. config_file = current_data_path + '\\configuration.txt'
  2980. try:
  2981. with open(config_file, 'r') as f:
  2982. try:
  2983. data = f.readlines()
  2984. except Exception as e:
  2985. log.debug('App.__init__() -->%s' % str(e))
  2986. return
  2987. except FileNotFoundError:
  2988. pass
  2989. for line in data:
  2990. line = line.strip('\n')
  2991. param = str(line).rpartition('=')
  2992. if param[0] == 'portable':
  2993. break
  2994. line_no += 1
  2995. if state:
  2996. data[line_no] = 'portable=True\n'
  2997. # create the new defauults files
  2998. # create current_defaults.FlatConfig file if there is none
  2999. try:
  3000. f = open(current_data_path + '/current_defaults.FlatConfig')
  3001. f.close()
  3002. except IOError:
  3003. App.log.debug('Creating empty current_defaults.FlatConfig')
  3004. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3005. json.dump({}, f)
  3006. f.close()
  3007. # create factory_defaults.FlatConfig file if there is none
  3008. try:
  3009. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3010. f.close()
  3011. except IOError:
  3012. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3013. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3014. json.dump({}, f)
  3015. f.close()
  3016. try:
  3017. f = open(current_data_path + '/recent.json')
  3018. f.close()
  3019. except IOError:
  3020. App.log.debug('Creating empty recent.json')
  3021. f = open(current_data_path + '/recent.json', 'w')
  3022. json.dump([], f)
  3023. f.close()
  3024. try:
  3025. fp = open(current_data_path + '/recent_projects.json')
  3026. fp.close()
  3027. except IOError:
  3028. App.log.debug('Creating empty recent_projects.json')
  3029. fp = open(current_data_path + '/recent_projects.json', 'w')
  3030. json.dump([], fp)
  3031. fp.close()
  3032. # save the current defaults to the new defaults file
  3033. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3034. else:
  3035. data[line_no] = 'portable=False\n'
  3036. with open(config_file, 'w') as f:
  3037. f.writelines(data)
  3038. def on_register_files(self, obj_type=None):
  3039. """
  3040. Called whenever there is a need to register file extensions with FlatCAM.
  3041. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3042. :param obj_type: the type of object to be register for.
  3043. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3044. :return: None
  3045. """
  3046. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3047. new_reg_path = 'Software\\Classes\\'
  3048. # find if the current user is admin
  3049. try:
  3050. is_admin = os.getuid() == 0
  3051. except AttributeError:
  3052. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3053. if is_admin is True:
  3054. root_path = winreg.HKEY_LOCAL_MACHINE
  3055. else:
  3056. root_path = winreg.HKEY_CURRENT_USER
  3057. # create the keys
  3058. def set_reg(name, root_pth, new_reg_path, value):
  3059. try:
  3060. winreg.CreateKey(root_pth, new_reg_path)
  3061. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3062. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3063. return True
  3064. except WindowsError:
  3065. return False
  3066. # delete key in registry
  3067. def delete_reg(root_pth, reg_path, key_to_del):
  3068. key_to_del_path = reg_path + key_to_del
  3069. try:
  3070. winreg.DeleteKey(root_pth, key_to_del_path)
  3071. return True
  3072. except WindowsError:
  3073. return False
  3074. if obj_type is None or obj_type == 'excellon':
  3075. exc_list = \
  3076. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3077. exc_list = [x for x in exc_list if x != '']
  3078. # register all keys in the Preferences window
  3079. for ext in exc_list:
  3080. new_k = new_reg_path + '.%s' % ext
  3081. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3082. # and unregister those that are no longer in the Preferences windows but are in the file
  3083. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3084. if ext not in exc_list:
  3085. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3086. # now write the updated extensions to the self.defaults
  3087. # new_ext = ''
  3088. # for ext in exc_list:
  3089. # new_ext = new_ext + ext + ', '
  3090. # self.defaults["fa_excellon"] = new_ext
  3091. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3092. if obj_type is None or obj_type == 'gcode':
  3093. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3094. gco_list = [x for x in gco_list if x != '']
  3095. # register all keys in the Preferences window
  3096. for ext in gco_list:
  3097. new_k = new_reg_path + '.%s' % ext
  3098. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3099. # and unregister those that are no longer in the Preferences windows but are in the file
  3100. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3101. if ext not in gco_list:
  3102. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3103. # now write the updated extensions to the self.defaults
  3104. # new_ext = ''
  3105. # for ext in gco_list:
  3106. # new_ext = new_ext + ext + ', '
  3107. # self.defaults["fa_gcode"] = new_ext
  3108. self.inform.emit('[success] %s' %
  3109. _("Selected GCode file extensions registered with FlatCAM."))
  3110. if obj_type is None or obj_type == 'gerber':
  3111. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3112. grb_list = [x for x in grb_list if x != '']
  3113. # register all keys in the Preferences window
  3114. for ext in grb_list:
  3115. new_k = new_reg_path + '.%s' % ext
  3116. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3117. # and unregister those that are no longer in the Preferences windows but are in the file
  3118. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3119. if ext not in grb_list:
  3120. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3121. # now write the updated extensions to the self.defaults
  3122. # new_ext = ''
  3123. # for ext in grb_list:
  3124. # new_ext = new_ext + ext + ', '
  3125. # self.defaults["fa_gerber"] = new_ext
  3126. self.inform.emit('[success] %s' %
  3127. _("Selected Gerber file extensions registered with FlatCAM."))
  3128. def add_extension(self, ext_type):
  3129. """
  3130. Add a file extension to the list for a specific object
  3131. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3132. :return:
  3133. """
  3134. if ext_type == 'excellon':
  3135. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3136. if new_ext == '':
  3137. return
  3138. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3139. if new_ext in old_val:
  3140. return
  3141. old_val.append(new_ext)
  3142. old_val.sort()
  3143. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3144. if ext_type == 'gcode':
  3145. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3146. if new_ext == '':
  3147. return
  3148. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_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_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3154. if ext_type == 'gerber':
  3155. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3156. if new_ext == '':
  3157. return
  3158. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_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_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3164. if ext_type == 'keyword':
  3165. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3166. if new_kw == '':
  3167. return
  3168. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3169. if new_kw in old_val:
  3170. return
  3171. old_val.append(new_kw)
  3172. old_val.sort()
  3173. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3174. # update the self.myKeywords so the model is updated
  3175. self.autocomplete_kw_list = \
  3176. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3177. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3178. self.shell._edit.set_model_data(self.myKeywords)
  3179. def del_extension(self, ext_type):
  3180. """
  3181. Remove a file extension from the list for a specific object
  3182. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3183. :return:
  3184. """
  3185. if ext_type == 'excellon':
  3186. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3187. if new_ext == '':
  3188. return
  3189. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3190. if new_ext not in old_val:
  3191. return
  3192. old_val.remove(new_ext)
  3193. old_val.sort()
  3194. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3195. if ext_type == 'gcode':
  3196. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3197. if new_ext == '':
  3198. return
  3199. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_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_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3205. if ext_type == 'gerber':
  3206. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3207. if new_ext == '':
  3208. return
  3209. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_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_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3215. if ext_type == 'keyword':
  3216. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3217. if new_kw == '':
  3218. return
  3219. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3220. if new_kw not in old_val:
  3221. return
  3222. old_val.remove(new_kw)
  3223. old_val.sort()
  3224. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3225. # update the self.myKeywords so the model is updated
  3226. self.autocomplete_kw_list = \
  3227. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3228. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3229. self.shell._edit.set_model_data(self.myKeywords)
  3230. def restore_extensions(self, ext_type):
  3231. """
  3232. Restore all file extensions associations with FlatCAM, for a specific object
  3233. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3234. :return:
  3235. """
  3236. if ext_type == 'excellon':
  3237. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3238. # for the ability to open Excellon files with .txt extension
  3239. new_exc_list = deepcopy(self.exc_list)
  3240. try:
  3241. new_exc_list.remove('txt')
  3242. except ValueError:
  3243. pass
  3244. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3245. if ext_type == 'gcode':
  3246. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3247. if ext_type == 'gerber':
  3248. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3249. if ext_type == 'keyword':
  3250. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3251. # update the self.myKeywords so the model is updated
  3252. self.autocomplete_kw_list = self.default_keywords
  3253. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3254. self.shell._edit.set_model_data(self.myKeywords)
  3255. def delete_all_extensions(self, ext_type):
  3256. """
  3257. Delete all file extensions associations with FlatCAM, for a specific object
  3258. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3259. :return:
  3260. """
  3261. if ext_type == 'excellon':
  3262. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3263. if ext_type == 'gcode':
  3264. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3265. if ext_type == 'gerber':
  3266. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3267. if ext_type == 'keyword':
  3268. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3269. # update the self.myKeywords so the model is updated
  3270. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3271. self.shell._edit.set_model_data(self.myKeywords)
  3272. def on_edit_join(self, name=None):
  3273. """
  3274. Callback for Edit->Join. Joins the selected geometry objects into
  3275. a new one.
  3276. :return: None
  3277. """
  3278. self.defaults.report_usage("on_edit_join()")
  3279. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3280. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3281. geo_type_set = set()
  3282. objs = self.collection.get_selected()
  3283. if len(objs) < 2:
  3284. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3285. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3286. return 'fail'
  3287. for obj in objs:
  3288. geo_type_set.add(obj.multigeo)
  3289. # if len(geo_type_list) == 1 means that all list elements are the same
  3290. if len(geo_type_set) != 1:
  3291. self.inform.emit('[ERROR] %s' %
  3292. _("Failed join. The Geometry objects are of different types.\n"
  3293. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3294. "convert from one to another and retry joining \n"
  3295. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3296. "the result may not be what was expected. \n"
  3297. "Check the generated GCODE."))
  3298. return
  3299. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3300. if True in geo_type_set:
  3301. def initialize(geo_obj, app):
  3302. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3303. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3304. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3305. for v in geo_obj.tools.values():
  3306. v['data']['name'] = obj_name_multi
  3307. self.new_object("geometry", obj_name_multi, initialize)
  3308. else:
  3309. def initialize(geo_obj, app):
  3310. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3311. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3312. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3313. for v in geo_obj.tools.values():
  3314. v['data']['name'] = obj_name_single
  3315. self.new_object("geometry", obj_name_single, initialize)
  3316. self.should_we_save = True
  3317. def on_edit_join_exc(self):
  3318. """
  3319. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3320. a new Excellon.
  3321. :return: None
  3322. """
  3323. self.defaults.report_usage("on_edit_join_exc()")
  3324. objs = self.collection.get_selected()
  3325. for obj in objs:
  3326. if not isinstance(obj, ExcellonObject):
  3327. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3328. return
  3329. if len(objs) < 2:
  3330. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3331. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3332. return 'fail'
  3333. def initialize(exc_obj, app):
  3334. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3335. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3336. self.new_object("excellon", 'Combo_Excellon', initialize)
  3337. self.should_we_save = True
  3338. def on_edit_join_grb(self):
  3339. """
  3340. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3341. a new Gerber object.
  3342. :return: None
  3343. """
  3344. self.defaults.report_usage("on_edit_join_grb()")
  3345. objs = self.collection.get_selected()
  3346. for obj in objs:
  3347. if not isinstance(obj, GerberObject):
  3348. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3349. return
  3350. if len(objs) < 2:
  3351. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3352. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3353. return 'fail'
  3354. def initialize(grb_obj, app):
  3355. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3356. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3357. self.new_object("gerber", 'Combo_Gerber', initialize)
  3358. self.should_we_save = True
  3359. def on_convert_singlegeo_to_multigeo(self):
  3360. """
  3361. Called for converting a Geometry object from single-geo to multi-geo.
  3362. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3363. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3364. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3365. the solid-geometry of that tool.
  3366. :return: None
  3367. """
  3368. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3369. obj = self.collection.get_active()
  3370. if obj is None:
  3371. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3372. return
  3373. if not isinstance(obj, GeometryObject):
  3374. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3375. return
  3376. obj.multigeo = True
  3377. for tooluid, dict_value in obj.tools.items():
  3378. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3379. if not isinstance(obj.solid_geometry, list):
  3380. obj.solid_geometry = [obj.solid_geometry]
  3381. obj.solid_geometry[:] = []
  3382. obj.plot()
  3383. self.should_we_save = True
  3384. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3385. def on_convert_multigeo_to_singlegeo(self):
  3386. """
  3387. Called for converting a Geometry object from multi-geo to single-geo.
  3388. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3389. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3390. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3391. the solid-geometry of that tool.
  3392. :return: None
  3393. """
  3394. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3395. obj = self.collection.get_active()
  3396. if obj is None:
  3397. self.inform.emit('[ERROR_NOTCL] %s' %
  3398. _("Failed. Select a Geometry Object and try again."))
  3399. return
  3400. if not isinstance(obj, GeometryObject):
  3401. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3402. (_("Expected a GeometryObject, got"), type(obj)))
  3403. return
  3404. obj.multigeo = False
  3405. total_solid_geometry = []
  3406. for tooluid, dict_value in obj.tools.items():
  3407. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3408. # clear the original geometry
  3409. dict_value['solid_geometry'][:] = []
  3410. obj.solid_geometry = deepcopy(total_solid_geometry)
  3411. obj.plot()
  3412. self.should_we_save = True
  3413. self.inform.emit('[success] %s' %
  3414. _("A Geometry object was converted to SingleGeo type."))
  3415. def on_defaults_dict_change(self, field):
  3416. """
  3417. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3418. Edit -> Preferences tab window.
  3419. :param field: the key of the self.defaults dictionary that was changed.
  3420. :return: None
  3421. """
  3422. self.preferencesUiManager.defaults_write_form_field(field=field)
  3423. if field == "units":
  3424. self.set_screen_units(self.defaults['units'])
  3425. def set_screen_units(self, units):
  3426. """
  3427. Set the FlatCAM units on the status bar.
  3428. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3429. :return: None
  3430. """
  3431. self.ui.units_label.setText("[" + units.lower() + "]")
  3432. def on_toggle_units_click(self):
  3433. try:
  3434. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3435. except (TypeError, AttributeError):
  3436. pass
  3437. if self.defaults["units"] == 'MM':
  3438. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3439. else:
  3440. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3441. self.on_toggle_units(no_pref=True)
  3442. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3443. lambda: self.on_toggle_units(no_pref=False))
  3444. def on_toggle_units(self, no_pref=False):
  3445. """
  3446. Callback for the Units radio-button change in the Preferences tab.
  3447. Changes the application's default units adn for the project too.
  3448. If changing the project's units, the change propagates to all of
  3449. the objects in the project.
  3450. :return: None
  3451. """
  3452. self.defaults.report_usage("on_toggle_units")
  3453. if self.toggle_units_ignore:
  3454. return
  3455. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3456. # If option is the same, then ignore
  3457. if new_units == self.defaults["units"].upper():
  3458. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3459. return
  3460. # Options to scale
  3461. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3462. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3463. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3464. "gerber_editor_ma_high",
  3465. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3466. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3467. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3468. "excellon_feedrate_probe", "excellon_milling_dia",
  3469. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3470. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3471. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3472. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3473. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3474. "geometry_extracut_length", "geometry_z_pdepth",
  3475. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3476. 'cncjob_tooldia',
  3477. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3478. "tools_paintnewdia",
  3479. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3480. "tools_nccnewdia", "tools_ncc_offset_value",
  3481. "tools_2sided_drilldia",
  3482. "tools_film_boundary", "tools_film_scale_stroke",
  3483. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3484. "tools_cutout_depthperpass",
  3485. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3486. "tools_panelize_spacing_rows",
  3487. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3488. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3489. "tools_transform_buffer_dis",
  3490. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3491. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3492. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3493. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3494. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3495. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3496. "tools_cr_h2h_val", "tools_cr_dh_val",
  3497. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3498. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3499. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3500. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3501. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3502. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3503. "tools_copper_thieving_mask_clearance",
  3504. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3505. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3506. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3507. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3508. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3509. "tools_invert_margin",
  3510. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3511. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3512. def scale_defaults(sfactor):
  3513. for dim in dimensions:
  3514. if dim == 'gerber_editor_newdim':
  3515. if self.defaults["gerber_editor_newdim"] is None or self.defaults["gerber_editor_newdim"] == '':
  3516. continue
  3517. coordinates = self.defaults["gerber_editor_newdim"].split(",")
  3518. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3519. coords_xy[0] *= sfactor
  3520. coords_xy[1] *= sfactor
  3521. self.defaults['gerber_editor_newdim'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3522. self.decimals, coords_xy[1])
  3523. if dim == 'excellon_toolchangexy':
  3524. if self.defaults["excellon_toolchangexy"] is None or self.defaults["excellon_toolchangexy"] == '':
  3525. continue
  3526. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3527. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3528. coords_xy[0] *= sfactor
  3529. coords_xy[1] *= sfactor
  3530. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3531. self.decimals, coords_xy[1])
  3532. elif dim == 'geometry_toolchangexy':
  3533. if self.defaults["geometry_toolchangexy"] is None or self.defaults["geometry_toolchangexy"] == '':
  3534. continue
  3535. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3536. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3537. coords_xy[0] *= sfactor
  3538. coords_xy[1] *= sfactor
  3539. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3540. self.decimals, coords_xy[1])
  3541. elif dim == 'excellon_endxy':
  3542. if self.defaults["excellon_endxy"] is None or self.defaults["excellon_endxy"] == '':
  3543. continue
  3544. coordinates = self.defaults["excellon_endxy"].split(",")
  3545. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3546. end_coords_xy[0] *= sfactor
  3547. end_coords_xy[1] *= sfactor
  3548. self.defaults['excellon_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3549. self.decimals, end_coords_xy[1])
  3550. elif dim == 'geometry_endxy':
  3551. if self.defaults["geometry_endxy"] is None or self.defaults["geometry_endxy"] == '':
  3552. continue
  3553. coordinates = self.defaults["geometry_endxy"].split(",")
  3554. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3555. end_coords_xy[0] *= sfactor
  3556. end_coords_xy[1] *= sfactor
  3557. self.defaults['geometry_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3558. self.decimals, end_coords_xy[1])
  3559. elif dim == 'geometry_cnctooldia':
  3560. if self.defaults["geometry_cnctooldia"] is None or self.defaults["geometry_cnctooldia"] == '':
  3561. continue
  3562. if type(self.defaults["geometry_cnctooldia"]) is float:
  3563. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  3564. else:
  3565. try:
  3566. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3567. tools_diameters = [eval(a) for a in tools_string if a != '']
  3568. except Exception as e:
  3569. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3570. continue
  3571. self.defaults['geometry_cnctooldia'] = ''
  3572. for t in range(len(tools_diameters)):
  3573. tools_diameters[t] *= sfactor
  3574. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  3575. elif dim == 'tools_ncctools':
  3576. if self.defaults["tools_ncctools"] is None or self.defaults["tools_ncctools"] == '':
  3577. continue
  3578. if type(self.defaults["tools_ncctools"]) == float:
  3579. ncctools = [self.defaults["tools_ncctools"]]
  3580. else:
  3581. try:
  3582. tools_string = self.defaults["tools_ncctools"].split(",")
  3583. ncctools = [eval(a) for a in tools_string if a != '']
  3584. except Exception as e:
  3585. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3586. continue
  3587. self.defaults['tools_ncctools'] = ''
  3588. for t in range(len(ncctools)):
  3589. ncctools[t] *= sfactor
  3590. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  3591. elif dim == 'tools_solderpaste_tools':
  3592. if self.defaults["tools_solderpaste_tools"] is None or \
  3593. self.defaults["tools_solderpaste_tools"] == '':
  3594. continue
  3595. if type(self.defaults["tools_solderpaste_tools"]) == float:
  3596. sptools = [self.defaults["tools_solderpaste_tools"]]
  3597. else:
  3598. try:
  3599. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3600. sptools = [eval(a) for a in tools_string if a != '']
  3601. except Exception as e:
  3602. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3603. continue
  3604. self.defaults['tools_solderpaste_tools'] = ""
  3605. for t in range(len(sptools)):
  3606. sptools[t] *= sfactor
  3607. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  3608. elif dim == 'tools_solderpaste_xy_toolchange':
  3609. if self.defaults["tools_solderpaste_xy_toolchange"] is None or \
  3610. self.defaults["tools_solderpaste_xy_toolchange"] == '':
  3611. continue
  3612. try:
  3613. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3614. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3615. sp_coords[0] *= sfactor
  3616. sp_coords[1] *= sfactor
  3617. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  3618. self.decimals, sp_coords[1])
  3619. except Exception as e:
  3620. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3621. continue
  3622. elif dim == 'tools_cal_toolchange_xy':
  3623. if self.defaults["tools_cal_toolchange_xy"] is None or \
  3624. self.defaults["tools_cal_toolchange_xy"] == '':
  3625. continue
  3626. coordinates = self.defaults["tools_cal_toolchange_xy"].split(",")
  3627. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3628. end_coords_xy[0] *= sfactor
  3629. end_coords_xy[1] *= sfactor
  3630. self.defaults['tools_cal_toolchange_xy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3631. self.decimals, end_coords_xy[1])
  3632. elif dim == 'global_gridx' or dim == 'global_gridy':
  3633. if new_units == 'IN':
  3634. try:
  3635. val = float(self.defaults[dim]) * sfactor
  3636. except Exception as e:
  3637. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3638. continue
  3639. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3640. else:
  3641. try:
  3642. val = float(self.defaults[dim]) * sfactor
  3643. except Exception as e:
  3644. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3645. continue
  3646. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3647. else:
  3648. if self.defaults[dim]:
  3649. try:
  3650. val = float(self.defaults[dim]) * sfactor
  3651. except Exception as e:
  3652. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3653. continue
  3654. self.defaults[dim] = val
  3655. # The scaling factor depending on choice of units.
  3656. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3657. # Changing project units. Warn user.
  3658. msgbox = QtWidgets.QMessageBox()
  3659. msgbox.setWindowTitle(_("Toggle Units"))
  3660. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3661. msgbox.setText(_("Changing the units of the project\n"
  3662. "will scale all objects.\n\n"
  3663. "Do you want to continue?"))
  3664. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3665. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3666. msgbox.setDefaultButton(bt_ok)
  3667. msgbox.exec_()
  3668. response = msgbox.clickedButton()
  3669. if response == bt_ok:
  3670. if no_pref is False:
  3671. self.preferencesUiManager.defaults_read_form()
  3672. scale_defaults(factor)
  3673. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3674. self.defaults["units"] = new_units
  3675. # update the defaults from form, some may assume that the conversion is enough and it's not
  3676. self.on_options_app2project()
  3677. # update the objects
  3678. for obj in self.collection.get_list():
  3679. obj.convert_units(new_units)
  3680. # make that the properties stored in the object are also updated
  3681. self.object_changed.emit(obj)
  3682. # rebuild the object UI
  3683. obj.build_ui()
  3684. # change this only if the workspace is active
  3685. if self.defaults['global_workspace'] is True:
  3686. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3687. # adjust the grid values on the main toolbar
  3688. val_x = float(self.defaults['global_gridx']) * factor
  3689. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3690. current = self.collection.get_active()
  3691. if current is not None:
  3692. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3693. if not isinstance(current, GeometryObject):
  3694. current.to_form()
  3695. # replot all objects
  3696. self.plot_all()
  3697. # set the status labels to reflect the current FlatCAM units
  3698. self.set_screen_units(new_units)
  3699. # signal to the app that we changed the object properties and it shoud save the project
  3700. self.should_we_save = True
  3701. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3702. else:
  3703. # Undo toggling
  3704. self.toggle_units_ignore = True
  3705. if self.defaults['units'].upper() == 'MM':
  3706. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3707. else:
  3708. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3709. self.toggle_units_ignore = False
  3710. # store the grid values so they are not changed in the next step
  3711. val_x = float(self.defaults['global_gridx'])
  3712. val_y = float(self.defaults['global_gridy'])
  3713. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3714. self.preferencesUiManager.defaults_read_form()
  3715. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3716. # in self.defaults from the GUI elements but
  3717. # I don't want it for the grid values, so I update them here
  3718. self.defaults['global_gridx'] = val_x
  3719. self.defaults['global_gridy'] = val_y
  3720. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3721. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3722. def on_fullscreen(self, disable=False):
  3723. self.defaults.report_usage("on_fullscreen()")
  3724. flags = self.ui.windowFlags()
  3725. if self.toggle_fscreen is False and disable is False:
  3726. # self.ui.showFullScreen()
  3727. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3728. a = self.ui.geometry()
  3729. self.x_pos = a.x()
  3730. self.y_pos = a.y()
  3731. self.width = a.width()
  3732. self.height = a.height()
  3733. # set new geometry to full desktop rect
  3734. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3735. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3736. # everything else will not work without this hack. This happen in Windows.
  3737. # https://bugreports.qt.io/browse/QTBUG-41309
  3738. desktop = QtWidgets.QApplication.desktop()
  3739. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3740. rec = desktop.screenGeometry(screen)
  3741. x = rec.x() - 1
  3742. y = rec.y() - 1
  3743. h = rec.height() + 2
  3744. w = rec.width() + 2
  3745. self.ui.setGeometry(x, y, w, h)
  3746. self.ui.show()
  3747. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3748. tb.setVisible(False)
  3749. self.ui.splitter_left.setVisible(False)
  3750. self.toggle_fscreen = True
  3751. elif self.toggle_fscreen is True or disable is True:
  3752. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3753. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3754. self.ui.showNormal()
  3755. self.restore_toolbar_view()
  3756. self.ui.splitter_left.setVisible(True)
  3757. self.toggle_fscreen = False
  3758. def on_toggle_plotarea(self):
  3759. self.defaults.report_usage("on_toggle_plotarea()")
  3760. try:
  3761. name = self.ui.plot_tab_area.widget(0).objectName()
  3762. except AttributeError:
  3763. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3764. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3765. self.ui.plot_tab_area.protectTab(0)
  3766. return
  3767. if name != 'plotarea_tab':
  3768. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3769. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3770. self.ui.plot_tab_area.protectTab(0)
  3771. else:
  3772. self.ui.plot_tab_area.closeTab(0)
  3773. def on_toggle_notebook(self):
  3774. if self.ui.splitter.sizes()[0] == 0:
  3775. self.ui.splitter.setSizes([1, 1])
  3776. self.ui.menu_toggle_nb.setChecked(True)
  3777. else:
  3778. self.ui.splitter.setSizes([0, 1])
  3779. self.ui.menu_toggle_nb.setChecked(False)
  3780. def on_toggle_axis(self):
  3781. self.defaults.report_usage("on_toggle_axis()")
  3782. if self.toggle_axis is False:
  3783. if self.is_legacy is False:
  3784. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3785. parent=self.plotcanvas.view.scene)
  3786. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3787. parent=self.plotcanvas.view.scene)
  3788. else:
  3789. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3790. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3791. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3792. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3793. self.plotcanvas.canvas.draw()
  3794. self.toggle_axis = True
  3795. else:
  3796. if self.is_legacy is False:
  3797. self.plotcanvas.v_line.parent = None
  3798. self.plotcanvas.h_line.parent = None
  3799. else:
  3800. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3801. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3802. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3803. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3804. self.plotcanvas.canvas.draw()
  3805. self.toggle_axis = False
  3806. def on_toggle_grid(self):
  3807. self.defaults.report_usage("on_toggle_grid()")
  3808. self.ui.grid_snap_btn.trigger()
  3809. self.on_grid_snap_triggered(state=True)
  3810. def on_toggle_grid_lines(self):
  3811. self.defaults.report_usage("on_toggle_grd_lines()")
  3812. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3813. if tt_settings.contains("theme"):
  3814. theme = tt_settings.value('theme', type=str)
  3815. else:
  3816. theme = 'white'
  3817. if self.toggle_grid_lines is False:
  3818. if self.is_legacy is False:
  3819. if theme == 'white':
  3820. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3821. else:
  3822. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3823. else:
  3824. self.plotcanvas.axes.grid(True)
  3825. try:
  3826. self.plotcanvas.canvas.draw()
  3827. except IndexError:
  3828. pass
  3829. pass
  3830. self.toggle_grid_lines = True
  3831. else:
  3832. if self.is_legacy is False:
  3833. if theme == 'white':
  3834. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3835. else:
  3836. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3837. else:
  3838. self.plotcanvas.axes.grid(False)
  3839. try:
  3840. self.plotcanvas.canvas.draw()
  3841. except IndexError:
  3842. pass
  3843. self.toggle_grid_lines = False
  3844. if self.is_legacy is False:
  3845. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3846. # - perhaps is a bug in VisPy implementation
  3847. if self.grid_status() is True:
  3848. self.app_cursor.enabled = False
  3849. self.app_cursor.enabled = True
  3850. else:
  3851. self.app_cursor.enabled = True
  3852. self.app_cursor.enabled = False
  3853. def on_update_exc_export(self, state):
  3854. """
  3855. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3856. if the update_excellon_cb checkbox is checked
  3857. :param state: state of the checkbox whose signals is tied to his slot
  3858. :return:
  3859. """
  3860. if state:
  3861. # first try to disconnect
  3862. try:
  3863. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3864. disconnect(self.on_excellon_format_changed)
  3865. except TypeError:
  3866. pass
  3867. try:
  3868. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3869. disconnect(self.on_excellon_format_changed)
  3870. except TypeError:
  3871. pass
  3872. try:
  3873. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3874. disconnect(self.on_excellon_format_changed)
  3875. except TypeError:
  3876. pass
  3877. try:
  3878. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3879. disconnect(self.on_excellon_format_changed)
  3880. except TypeError:
  3881. pass
  3882. try:
  3883. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3884. disconnect(self.on_excellon_zeros_changed)
  3885. except TypeError:
  3886. pass
  3887. try:
  3888. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3889. disconnect(self.on_excellon_zeros_changed)
  3890. except TypeError:
  3891. pass
  3892. # the connect them
  3893. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3894. self.on_excellon_format_changed)
  3895. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3896. self.on_excellon_format_changed)
  3897. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3898. self.on_excellon_format_changed)
  3899. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3900. self.on_excellon_format_changed)
  3901. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3902. self.on_excellon_zeros_changed)
  3903. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3904. self.on_excellon_units_changed)
  3905. else:
  3906. # disconnect the signals
  3907. try:
  3908. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3909. disconnect(self.on_excellon_format_changed)
  3910. except TypeError:
  3911. pass
  3912. try:
  3913. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3914. disconnect(self.on_excellon_format_changed)
  3915. except TypeError:
  3916. pass
  3917. try:
  3918. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3919. disconnect(self.on_excellon_format_changed)
  3920. except TypeError:
  3921. pass
  3922. try:
  3923. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3924. disconnect(self.on_excellon_format_changed)
  3925. except TypeError:
  3926. pass
  3927. try:
  3928. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3929. disconnect(self.on_excellon_zeros_changed)
  3930. except TypeError:
  3931. pass
  3932. try:
  3933. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3934. disconnect(self.on_excellon_zeros_changed)
  3935. except TypeError:
  3936. pass
  3937. def on_excellon_format_changed(self):
  3938. """
  3939. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3940. :return: None
  3941. """
  3942. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3943. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3944. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3945. )
  3946. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3947. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3948. )
  3949. else:
  3950. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3951. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3952. )
  3953. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3954. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3955. )
  3956. def on_excellon_zeros_changed(self):
  3957. """
  3958. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3959. :return: None
  3960. """
  3961. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3962. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3963. )
  3964. def on_excellon_units_changed(self):
  3965. """
  3966. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3967. :return: None
  3968. """
  3969. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3970. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3971. )
  3972. self.on_excellon_format_changed()
  3973. def on_film_color_entry(self):
  3974. self.defaults['tools_film_color'] = \
  3975. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3976. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3977. "background-color:%s;"
  3978. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3979. )
  3980. def on_film_color_button(self):
  3981. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3982. c_dialog = QtWidgets.QColorDialog()
  3983. film_color = c_dialog.getColor(initial=current_color)
  3984. if film_color.isValid() is False:
  3985. return
  3986. # if new color is different then mark that the Preferences are changed
  3987. if film_color != current_color:
  3988. self.preferencesUiManager.on_preferences_edited()
  3989. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3990. "background-color:%s;"
  3991. "border-color: dimgray" % str(film_color.name())
  3992. )
  3993. new_val_sel = str(film_color.name())
  3994. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3995. self.defaults['tools_film_color'] = new_val_sel
  3996. def on_qrcode_fill_color_entry(self):
  3997. self.defaults['tools_qrcode_fill_color'] = \
  3998. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3999. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4000. "background-color:%s;"
  4001. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  4002. )
  4003. def on_qrcode_fill_color_button(self):
  4004. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  4005. c_dialog = QtWidgets.QColorDialog()
  4006. fill_color = c_dialog.getColor(initial=current_color)
  4007. if fill_color.isValid() is False:
  4008. return
  4009. # if new color is different then mark that the Preferences are changed
  4010. if fill_color != current_color:
  4011. self.preferencesUiManager.on_preferences_edited()
  4012. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4013. "background-color:%s;"
  4014. "border-color: dimgray" % str(fill_color.name())
  4015. )
  4016. new_val_sel = str(fill_color.name())
  4017. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  4018. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  4019. def on_qrcode_back_color_entry(self):
  4020. self.defaults['tools_qrcode_back_color'] = \
  4021. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  4022. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4023. "background-color:%s;"
  4024. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  4025. )
  4026. def on_qrcode_back_color_button(self):
  4027. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  4028. c_dialog = QtWidgets.QColorDialog()
  4029. back_color = c_dialog.getColor(initial=current_color)
  4030. if back_color.isValid() is False:
  4031. return
  4032. # if new color is different then mark that the Preferences are changed
  4033. if back_color != current_color:
  4034. self.preferencesUiManager.on_preferences_edited()
  4035. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4036. "background-color:%s;"
  4037. "border-color: dimgray" % str(back_color.name())
  4038. )
  4039. new_val_sel = str(back_color.name())
  4040. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  4041. self.defaults['tools_qrcode_back_color'] = new_val_sel
  4042. def on_tab_rmb_click(self, checked):
  4043. self.ui.notebook.set_detachable(val=checked)
  4044. self.defaults["global_tabs_detachable"] = checked
  4045. self.ui.plot_tab_area.set_detachable(val=checked)
  4046. self.defaults["global_tabs_detachable"] = checked
  4047. def on_tab_setup_context_menu(self):
  4048. initial_checked = self.defaults["global_tabs_detachable"]
  4049. action_name = str(_("Detachable Tabs"))
  4050. action = QtWidgets.QAction(self)
  4051. action.setCheckable(True)
  4052. action.setText(action_name)
  4053. action.setChecked(initial_checked)
  4054. self.ui.notebook.tabBar.addAction(action)
  4055. self.ui.plot_tab_area.tabBar.addAction(action)
  4056. try:
  4057. action.triggered.disconnect()
  4058. except TypeError:
  4059. pass
  4060. action.triggered.connect(self.on_tab_rmb_click)
  4061. def on_deselect_all(self):
  4062. self.collection.set_all_inactive()
  4063. self.delete_selection_shape()
  4064. def on_workspace_modified(self):
  4065. # self.save_defaults(silent=True)
  4066. if self.is_legacy is True:
  4067. self.plotcanvas.delete_workspace()
  4068. self.preferencesUiManager.defaults_read_form()
  4069. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4070. def on_workspace(self):
  4071. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4072. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4073. else:
  4074. self.plotcanvas.delete_workspace()
  4075. self.preferencesUiManager.defaults_read_form()
  4076. # self.save_defaults(silent=True)
  4077. def on_workspace_toggle(self):
  4078. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4079. try:
  4080. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4081. except TypeError:
  4082. pass
  4083. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4084. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4085. self.on_workspace()
  4086. def on_cursor_type(self, val):
  4087. """
  4088. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4089. :return: None
  4090. """
  4091. self.app_cursor.enabled = False
  4092. if val == 'small':
  4093. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4094. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4095. self.app_cursor = self.plotcanvas.new_cursor()
  4096. else:
  4097. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4098. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4099. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4100. if self.ui.grid_snap_btn.isChecked():
  4101. self.app_cursor.enabled = True
  4102. else:
  4103. self.app_cursor.enabled = False
  4104. def on_tool_add_keypress(self):
  4105. # ## Current application units in Upper Case
  4106. self.units = self.defaults['units'].upper()
  4107. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4108. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4109. if notebook_widget_name == 'selected_tab':
  4110. if self.collection.get_active().kind == 'geometry':
  4111. # Tool add works for Geometry only if Advanced is True in Preferences
  4112. if self.defaults["global_app_level"] == 'a':
  4113. tool_add_popup = FCInputDialog(title="New Tool ...",
  4114. text='Enter a Tool Diameter:',
  4115. min=0.0000, max=99.9999, decimals=4)
  4116. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4117. val, ok = tool_add_popup.get_value()
  4118. if ok:
  4119. if float(val) == 0:
  4120. self.inform.emit('[WARNING_NOTCL] %s' %
  4121. _("Please enter a tool diameter with non-zero value, in Float format."))
  4122. return
  4123. self.collection.get_active().on_tool_add(dia=float(val))
  4124. else:
  4125. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4126. else:
  4127. msgbox = QtWidgets.QMessageBox()
  4128. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4129. "Go to Preferences -> General - Show Advanced Options."))
  4130. msgbox.setWindowTitle("Tool adding ...")
  4131. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4132. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4133. msgbox.setDefaultButton(bt_ok)
  4134. msgbox.exec_()
  4135. # work only if the notebook tab on focus is the Tools_Tab
  4136. if notebook_widget_name == 'tool_tab':
  4137. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4138. # and only if the tool is NCC Tool
  4139. if tool_widget == self.ncclear_tool.toolName:
  4140. self.ncclear_tool.on_add_tool_by_key()
  4141. # and only if the tool is Paint Area Tool
  4142. elif tool_widget == self.paint_tool.toolName:
  4143. self.paint_tool.on_add_tool_by_key()
  4144. # and only if the tool is Solder Paste Dispensing Tool
  4145. elif tool_widget == self.paste_tool.toolName:
  4146. self.paste_tool.on_add_tool_by_key()
  4147. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4148. # See description bellow.
  4149. def on_delete_keypress(self):
  4150. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4151. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4152. if notebook_widget_name == 'selected_tab':
  4153. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4154. self.collection.get_active().on_tool_delete()
  4155. # work only if the notebook tab on focus is the Tools_Tab
  4156. elif notebook_widget_name == 'tool_tab':
  4157. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4158. # and only if the tool is NCC Tool
  4159. if tool_widget == self.ncclear_tool.toolName:
  4160. self.ncclear_tool.on_tool_delete()
  4161. # and only if the tool is Paint Tool
  4162. elif tool_widget == self.paint_tool.toolName:
  4163. self.paint_tool.on_tool_delete()
  4164. # and only if the tool is Solder Paste Dispensing Tool
  4165. elif tool_widget == self.paste_tool.toolName:
  4166. self.paste_tool.on_tool_delete()
  4167. else:
  4168. self.on_delete()
  4169. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4170. # some screens you have to be careful where you hover with your mouse.
  4171. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4172. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4173. # Complicated, I know :)
  4174. def on_delete(self, force_deletion=False):
  4175. """
  4176. Delete the currently selected FlatCAMObjs.
  4177. :param force_deletion: used by Tcl command
  4178. :return: None
  4179. """
  4180. self.defaults.report_usage("on_delete()")
  4181. response = None
  4182. bt_ok = None
  4183. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4184. # a geometry object before we update it.
  4185. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4186. and self.grb_editor.editor_active is False:
  4187. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4188. msgbox = QtWidgets.QMessageBox()
  4189. msgbox.setWindowTitle(_("Delete objects"))
  4190. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4191. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4192. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4193. "the selected objects?"))
  4194. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4195. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4196. msgbox.setDefaultButton(bt_ok)
  4197. msgbox.exec_()
  4198. response = msgbox.clickedButton()
  4199. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4200. response = bt_ok
  4201. if response == bt_ok:
  4202. if self.collection.get_active():
  4203. self.log.debug("App.on_delete()")
  4204. for obj_active in self.collection.get_selected():
  4205. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4206. if isinstance(obj_active, GerberObject):
  4207. for el in obj_active.mark_shapes:
  4208. obj_active.mark_shapes[el].clear(update=True)
  4209. obj_active.mark_shapes[el].enabled = False
  4210. # obj_active.mark_shapes[el] = None
  4211. del el
  4212. elif isinstance(obj_active, CNCJobObject):
  4213. try:
  4214. obj_active.text_col.enabled = False
  4215. del obj_active.text_col
  4216. obj_active.annotation.clear(update=True)
  4217. del obj_active.annotation
  4218. except AttributeError as e:
  4219. log.debug(
  4220. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4221. )
  4222. while self.collection.get_selected():
  4223. self.delete_first_selected()
  4224. self.inform.emit('%s...' % _("Object(s) deleted"))
  4225. # make sure that the selection shape is deleted, too
  4226. self.delete_selection_shape()
  4227. else:
  4228. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4229. else:
  4230. self.inform.emit(_("Save the work in Editor and try again ..."))
  4231. def delete_first_selected(self):
  4232. # Keep this for later
  4233. try:
  4234. sel_obj = self.collection.get_active()
  4235. name = sel_obj.options["name"]
  4236. isPlotted = sel_obj.options["plot"]
  4237. except AttributeError:
  4238. self.log.debug("Nothing selected for deletion")
  4239. return
  4240. if self.is_legacy is True:
  4241. # Remove plot only if the object was plotted otherwise delaxes will fail
  4242. if isPlotted:
  4243. try:
  4244. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4245. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4246. except Exception as e:
  4247. log.debug("App.delete_first_selected() --> %s" % str(e))
  4248. self.plotcanvas.auto_adjust_axes()
  4249. # Remove from dictionary
  4250. self.collection.delete_active()
  4251. # Clear form
  4252. self.setup_component_editor()
  4253. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4254. def on_set_origin(self):
  4255. """
  4256. Set the origin to the left mouse click position
  4257. :return: None
  4258. """
  4259. # display the message for the user
  4260. # and ask him to click on the desired position
  4261. self.defaults.report_usage("on_set_origin()")
  4262. def origin_replot():
  4263. def worker_task():
  4264. with self.proc_container.new('%s...' % _("Plotting")):
  4265. for obj in self.collection.get_list():
  4266. obj.plot()
  4267. self.plotcanvas.fit_view()
  4268. if self.is_legacy:
  4269. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4270. else:
  4271. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4272. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4273. self.inform.emit(_('Click to set the origin ...'))
  4274. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4275. # first disconnect it as it may have been used by something else
  4276. try:
  4277. self.replot_signal.disconnect()
  4278. except TypeError:
  4279. pass
  4280. self.replot_signal[list].connect(origin_replot)
  4281. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4282. """
  4283. :param event:
  4284. :param location:
  4285. :param noplot:
  4286. :param use_thread:
  4287. :return:
  4288. """
  4289. noplot_sig = noplot
  4290. def worker_task():
  4291. with self.proc_container.new(_("Setting Origin...")):
  4292. obj_list = self.collection.get_list()
  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. self.inform.emit('[success] %s...' % _('Origin set'))
  4303. for obj in obj_list:
  4304. out_name = obj.options["name"]
  4305. if obj.kind == 'gerber':
  4306. obj.source_file = self.export_gerber(
  4307. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4308. elif obj.kind == 'excellon':
  4309. obj.source_file = self.export_excellon(
  4310. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4311. if noplot_sig is False:
  4312. self.replot_signal.emit([])
  4313. if location is not None:
  4314. if len(location) != 2:
  4315. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4316. return 'fail'
  4317. x, y = location
  4318. if use_thread is True:
  4319. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4320. else:
  4321. worker_task()
  4322. self.should_we_save = True
  4323. return
  4324. if event.button == 1:
  4325. if self.is_legacy is False:
  4326. event_pos = event.pos
  4327. else:
  4328. event_pos = (event.xdata, event.ydata)
  4329. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4330. if self.grid_status():
  4331. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4332. else:
  4333. pos = pos_canvas
  4334. x = 0 - pos[0]
  4335. y = 0 - pos[1]
  4336. if use_thread is True:
  4337. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4338. else:
  4339. worker_task()
  4340. self.should_we_save = True
  4341. def on_move2origin(self, use_thread=True):
  4342. """
  4343. Move selected objects to origin.
  4344. :param use_thread: Control if to use threaded operation. Boolean.
  4345. :return:
  4346. """
  4347. def worker_task():
  4348. with self.proc_container.new(_("Moving to Origin...")):
  4349. obj_list = self.collection.get_selected()
  4350. if not obj_list:
  4351. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4352. return
  4353. xminlist = []
  4354. yminlist = []
  4355. # first get a bounding box to fit all
  4356. for obj in obj_list:
  4357. xmin, ymin, xmax, ymax = obj.bounds()
  4358. xminlist.append(xmin)
  4359. yminlist.append(ymin)
  4360. # get the minimum x,y for all objects selected
  4361. x = min(xminlist)
  4362. y = min(yminlist)
  4363. for obj in obj_list:
  4364. obj.offset((-x, -y))
  4365. self.object_changed.emit(obj)
  4366. # Update the object bounding box options
  4367. a, b, c, d = obj.bounds()
  4368. obj.options['xmin'] = a
  4369. obj.options['ymin'] = b
  4370. obj.options['xmax'] = c
  4371. obj.options['ymax'] = d
  4372. for obj in obj_list:
  4373. obj.plot()
  4374. for obj in obj_list:
  4375. out_name = obj.options["name"]
  4376. if obj.kind == 'gerber':
  4377. obj.source_file = self.export_gerber(
  4378. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4379. elif obj.kind == 'excellon':
  4380. obj.source_file = self.export_excellon(
  4381. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4382. self.inform.emit('[success] %s...' % _('Origin set'))
  4383. if use_thread is True:
  4384. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4385. else:
  4386. worker_task()
  4387. self.should_we_save = True
  4388. def on_jump_to(self, custom_location=None, fit_center=True):
  4389. """
  4390. Jump to a location by setting the mouse cursor location.
  4391. :param custom_location: Jump to a specified point. (x, y) tuple.
  4392. :param fit_center: If to fit view. Boolean.
  4393. :return:
  4394. """
  4395. self.defaults.report_usage("on_jump_to()")
  4396. if not custom_location:
  4397. dia_box_location = None
  4398. try:
  4399. dia_box_location = eval(self.clipboard.text())
  4400. except Exception:
  4401. pass
  4402. if type(dia_box_location) == tuple:
  4403. dia_box_location = str(dia_box_location)
  4404. else:
  4405. dia_box_location = None
  4406. # dia_box = Dialog_box(title=_("Jump to ..."),
  4407. # label=_("Enter the coordinates in format X,Y:"),
  4408. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4409. # initial_text=dia_box_location)
  4410. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4411. label=_("Enter the coordinates in format X,Y:"),
  4412. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4413. initial_text=dia_box_location,
  4414. reference=self.defaults['global_jump_ref'])
  4415. if dia_box.ok is True:
  4416. try:
  4417. location = eval(dia_box.location)
  4418. if not isinstance(location, tuple):
  4419. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4420. return
  4421. if dia_box.reference == 'rel':
  4422. rel_x = self.mouse[0] + location[0]
  4423. rel_y = self.mouse[1] + location[1]
  4424. location = (rel_x, rel_y)
  4425. self.defaults['global_jump_ref'] = dia_box.reference
  4426. except Exception:
  4427. return
  4428. else:
  4429. return
  4430. else:
  4431. location = custom_location
  4432. self.jump_signal.emit(location)
  4433. if fit_center:
  4434. self.plotcanvas.fit_center(loc=location)
  4435. cursor = QtGui.QCursor()
  4436. if self.is_legacy is False:
  4437. # I don't know where those differences come from but they are constant for the current
  4438. # execution of the application and they are multiples of a value around 0.0263mm.
  4439. # In a random way sometimes they are more sometimes they are less
  4440. # if units == 'MM':
  4441. # cal_factor = 0.0263
  4442. # else:
  4443. # cal_factor = 0.0263 / 25.4
  4444. cal_location = (location[0], location[1])
  4445. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4446. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4447. j_pos = (
  4448. int(canvas_origin.x() + round(jump_loc[0])),
  4449. int(canvas_origin.y() + round(jump_loc[1]))
  4450. )
  4451. cursor.setPos(j_pos[0], j_pos[1])
  4452. else:
  4453. # find the canvas origin which is in the top left corner
  4454. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4455. # determine the coordinates for the lowest left point of the canvas
  4456. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4457. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4458. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4459. # canvas) and the point (width, height) is in the top-right location
  4460. loc = self.plotcanvas.axes.transData.transform_point(location)
  4461. j_pos = (
  4462. int(x0 + loc[0]),
  4463. int(y0 - loc[1])
  4464. )
  4465. cursor.setPos(j_pos[0], j_pos[1])
  4466. self.plotcanvas.mouse = [location[0], location[1]]
  4467. if self.defaults["global_cursor_color_enabled"] is True:
  4468. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4469. else:
  4470. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4471. if self.grid_status():
  4472. # Update cursor
  4473. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4474. symbol='++', edge_color=self.cursor_color_3D,
  4475. edge_width=self.defaults["global_cursor_width"],
  4476. size=self.defaults["global_cursor_size"])
  4477. # Set the position label
  4478. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4479. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4480. # Set the relative position label
  4481. dx = location[0] - float(self.rel_point1[0])
  4482. dy = location[1] - float(self.rel_point1[1])
  4483. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4484. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4485. self.inform.emit('[success] %s' % _("Done."))
  4486. return location
  4487. def on_locate(self, obj, fit_center=True):
  4488. """
  4489. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4490. :param obj: The object on which to locate certain points
  4491. :param fit_center: If to fit view. Boolean.
  4492. :return: A point location. (x, y) tuple.
  4493. """
  4494. self.defaults.report_usage("on_locate()")
  4495. if obj is None:
  4496. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4497. return 'fail'
  4498. class DialogBoxChoice(QtWidgets.QDialog):
  4499. def __init__(self, title=None, icon=None, choice='bl'):
  4500. """
  4501. :param title: string with the window title
  4502. """
  4503. super(DialogBoxChoice, self).__init__()
  4504. self.ok = False
  4505. self.setWindowIcon(icon)
  4506. self.setWindowTitle(str(title))
  4507. self.form = QtWidgets.QFormLayout(self)
  4508. self.ref_radio = RadioSet([
  4509. {"label": _("Bottom-Left"), "value": "bl"},
  4510. {"label": _("Top-Left"), "value": "tl"},
  4511. {"label": _("Bottom-Right"), "value": "br"},
  4512. {"label": _("Top-Right"), "value": "tr"},
  4513. {"label": _("Center"), "value": "c"}
  4514. ], orientation='vertical', stretch=False)
  4515. self.ref_radio.set_value(choice)
  4516. self.form.addRow(self.ref_radio)
  4517. self.button_box = QtWidgets.QDialogButtonBox(
  4518. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4519. Qt.Horizontal, parent=self)
  4520. self.form.addRow(self.button_box)
  4521. self.button_box.accepted.connect(self.accept)
  4522. self.button_box.rejected.connect(self.reject)
  4523. if self.exec_() == QtWidgets.QDialog.Accepted:
  4524. self.ok = True
  4525. self.location_point = self.ref_radio.get_value()
  4526. else:
  4527. self.ok = False
  4528. self.location_point = None
  4529. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4530. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4531. choice=self.defaults['global_locate_pt'])
  4532. if dia_box.ok is True:
  4533. try:
  4534. location_point = dia_box.location_point
  4535. self.defaults['global_locate_pt'] = dia_box.location_point
  4536. except Exception:
  4537. return
  4538. else:
  4539. return
  4540. loc_b = obj.bounds()
  4541. if location_point == 'bl':
  4542. location = (loc_b[0], loc_b[1])
  4543. elif location_point == 'tl':
  4544. location = (loc_b[0], loc_b[3])
  4545. elif location_point == 'br':
  4546. location = (loc_b[2], loc_b[1])
  4547. elif location_point == 'tr':
  4548. location = (loc_b[2], loc_b[3])
  4549. else:
  4550. # center
  4551. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4552. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4553. location = (cx, cy)
  4554. self.locate_signal.emit(location, location_point)
  4555. if fit_center:
  4556. self.plotcanvas.fit_center(loc=location)
  4557. cursor = QtGui.QCursor()
  4558. if self.is_legacy is False:
  4559. # I don't know where those differences come from but they are constant for the current
  4560. # execution of the application and they are multiples of a value around 0.0263mm.
  4561. # In a random way sometimes they are more sometimes they are less
  4562. # if units == 'MM':
  4563. # cal_factor = 0.0263
  4564. # else:
  4565. # cal_factor = 0.0263 / 25.4
  4566. cal_location = (location[0], location[1])
  4567. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4568. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4569. j_pos = (
  4570. int(canvas_origin.x() + round(jump_loc[0])),
  4571. int(canvas_origin.y() + round(jump_loc[1]))
  4572. )
  4573. cursor.setPos(j_pos[0], j_pos[1])
  4574. else:
  4575. # find the canvas origin which is in the top left corner
  4576. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4577. # determine the coordinates for the lowest left point of the canvas
  4578. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4579. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4580. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4581. # canvas) and the point (width, height) is in the top-right location
  4582. loc = self.plotcanvas.axes.transData.transform_point(location)
  4583. j_pos = (
  4584. int(x0 + loc[0]),
  4585. int(y0 - loc[1])
  4586. )
  4587. cursor.setPos(j_pos[0], j_pos[1])
  4588. self.plotcanvas.mouse = [location[0], location[1]]
  4589. if self.defaults["global_cursor_color_enabled"] is True:
  4590. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4591. else:
  4592. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4593. if self.grid_status():
  4594. # Update cursor
  4595. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4596. symbol='++', edge_color=self.cursor_color_3D,
  4597. edge_width=self.defaults["global_cursor_width"],
  4598. size=self.defaults["global_cursor_size"])
  4599. # Set the position label
  4600. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4601. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4602. # Set the relative position label
  4603. self.dx = location[0] - float(self.rel_point1[0])
  4604. self.dy = location[1] - float(self.rel_point1[1])
  4605. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4606. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4607. self.inform.emit('[success] %s' % _("Done."))
  4608. return location
  4609. def on_copy_command(self):
  4610. """
  4611. Will copy a selection of objects, creating new objects.
  4612. :return:
  4613. """
  4614. self.defaults.report_usage("on_copy_command()")
  4615. def initialize(obj_init, app):
  4616. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4617. try:
  4618. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4619. except AttributeError:
  4620. pass
  4621. try:
  4622. obj_init.apertures = deepcopy(obj.apertures)
  4623. except AttributeError:
  4624. pass
  4625. try:
  4626. if obj.tools:
  4627. obj_init.tools = deepcopy(obj.tools)
  4628. except Exception as err:
  4629. log.debug("App.on_copy_command() --> %s" % str(err))
  4630. try:
  4631. obj_init.source_file = deepcopy(obj.source_file)
  4632. except (AttributeError, TypeError):
  4633. pass
  4634. def initialize_excellon(obj_init, app):
  4635. obj_init.source_file = deepcopy(obj.source_file)
  4636. obj_init.tools = deepcopy(obj.tools)
  4637. # drills are offset, so they need to be deep copied
  4638. obj_init.drills = deepcopy(obj.drills)
  4639. # slots are offset, so they need to be deep copied
  4640. obj_init.slots = deepcopy(obj.slots)
  4641. obj_init.create_geometry()
  4642. def initialize_script(obj_init, app_obj):
  4643. obj_init.source_file = deepcopy(obj.source_file)
  4644. def initialize_document(obj_init, app_obj):
  4645. obj_init.source_file = deepcopy(obj.source_file)
  4646. for obj in self.collection.get_selected():
  4647. obj_name = obj.options["name"]
  4648. try:
  4649. if isinstance(obj, ExcellonObject):
  4650. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4651. elif isinstance(obj, GerberObject):
  4652. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4653. elif isinstance(obj, GeometryObject):
  4654. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4655. elif isinstance(obj, ScriptObject):
  4656. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4657. elif isinstance(obj, DocumentObject):
  4658. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4659. except Exception as e:
  4660. return "Operation failed: %s" % str(e)
  4661. def on_copy_object2(self, custom_name):
  4662. def initialize_geometry(obj_init, app):
  4663. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4664. try:
  4665. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4666. except AttributeError:
  4667. pass
  4668. try:
  4669. obj_init.apertures = deepcopy(obj.apertures)
  4670. except AttributeError:
  4671. pass
  4672. try:
  4673. if obj.tools:
  4674. obj_init.tools = deepcopy(obj.tools)
  4675. except Exception as ee:
  4676. log.debug("on_copy_object2() --> %s" % str(ee))
  4677. def initialize_gerber(obj_init, app):
  4678. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4679. obj_init.apertures = deepcopy(obj.apertures)
  4680. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4681. def initialize_excellon(obj_init, app):
  4682. obj_init.tools = deepcopy(obj.tools)
  4683. # drills are offset, so they need to be deep copied
  4684. obj_init.drills = deepcopy(obj.drills)
  4685. # slots are offset, so they need to be deep copied
  4686. obj_init.slots = deepcopy(obj.slots)
  4687. obj_init.create_geometry()
  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("excellon", str(obj_name) + custom_name, initialize_excellon)
  4693. elif isinstance(obj, GerberObject):
  4694. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4695. elif isinstance(obj, GeometryObject):
  4696. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4697. except Exception as er:
  4698. return "Operation failed: %s" % str(er)
  4699. def on_rename_object(self, text):
  4700. """
  4701. Will rename an object.
  4702. :param text: New name for the object.
  4703. :return:
  4704. """
  4705. self.defaults.report_usage("on_rename_object()")
  4706. named_obj = self.collection.get_active()
  4707. for obj in named_obj:
  4708. if obj is list:
  4709. self.on_rename_object(text)
  4710. else:
  4711. try:
  4712. obj.options['name'] = text
  4713. except Exception as e:
  4714. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4715. def convert_any2geo(self):
  4716. """
  4717. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4718. :return:
  4719. """
  4720. self.defaults.report_usage("convert_any2geo()")
  4721. def initialize(obj_init, app):
  4722. obj_init.solid_geometry = obj.solid_geometry
  4723. try:
  4724. obj_init.follow_geometry = obj.follow_geometry
  4725. except AttributeError:
  4726. pass
  4727. try:
  4728. obj_init.apertures = obj.apertures
  4729. except AttributeError:
  4730. pass
  4731. try:
  4732. if obj.tools:
  4733. obj_init.tools = obj.tools
  4734. except AttributeError:
  4735. pass
  4736. def initialize_excellon(obj_init, app):
  4737. # objs = self.collection.get_selected()
  4738. # GeometryObject.merge(objs, obj)
  4739. solid_geo = []
  4740. for tool in obj.tools:
  4741. for geo in obj.tools[tool]['solid_geometry']:
  4742. solid_geo.append(geo)
  4743. obj_init.solid_geometry = deepcopy(solid_geo)
  4744. if not self.collection.get_selected():
  4745. log.warning("App.convert_any2geo --> No object selected")
  4746. self.inform.emit('[WARNING_NOTCL] %s' %
  4747. _("No object is selected. Select an object and try again."))
  4748. return
  4749. for obj in self.collection.get_selected():
  4750. obj_name = obj.options["name"]
  4751. try:
  4752. if isinstance(obj, ExcellonObject):
  4753. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4754. else:
  4755. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4756. except Exception as e:
  4757. return "Operation failed: %s" % str(e)
  4758. def convert_any2gerber(self):
  4759. """
  4760. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4761. :return:
  4762. """
  4763. self.defaults.report_usage("convert_any2gerber()")
  4764. def initialize_geometry(obj_init, app):
  4765. apertures = {}
  4766. apid = 0
  4767. apertures[str(apid)] = {}
  4768. apertures[str(apid)]['geometry'] = []
  4769. for obj_orig in obj.solid_geometry:
  4770. new_elem = {}
  4771. new_elem['solid'] = obj_orig
  4772. try:
  4773. new_elem['follow'] = obj_orig.exterior
  4774. except AttributeError:
  4775. pass
  4776. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4777. apertures[str(apid)]['size'] = 0.0
  4778. apertures[str(apid)]['type'] = 'C'
  4779. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4780. obj_init.apertures = deepcopy(apertures)
  4781. def initialize_excellon(obj_init, app):
  4782. apertures = {}
  4783. apid = 10
  4784. for tool in obj.tools:
  4785. apertures[str(apid)] = {}
  4786. apertures[str(apid)]['geometry'] = []
  4787. for geo in obj.tools[tool]['solid_geometry']:
  4788. new_el = {}
  4789. new_el['solid'] = geo
  4790. new_el['follow'] = geo.exterior
  4791. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4792. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4793. apertures[str(apid)]['type'] = 'C'
  4794. apid += 1
  4795. # create solid_geometry
  4796. solid_geometry = []
  4797. for apid in apertures:
  4798. for geo_el in apertures[apid]['geometry']:
  4799. solid_geometry.append(geo_el['solid'])
  4800. solid_geometry = MultiPolygon(solid_geometry)
  4801. solid_geometry = solid_geometry.buffer(0.0000001)
  4802. obj_init.solid_geometry = deepcopy(solid_geometry)
  4803. obj_init.apertures = deepcopy(apertures)
  4804. # clear the working objects (perhaps not necessary due of Python GC)
  4805. apertures.clear()
  4806. if not self.collection.get_selected():
  4807. log.warning("App.convert_any2gerber --> No object selected")
  4808. self.inform.emit('[WARNING_NOTCL] %s' %
  4809. _("No object is selected. Select an object and try again."))
  4810. return
  4811. for obj in self.collection.get_selected():
  4812. obj_name = obj.options["name"]
  4813. try:
  4814. if isinstance(obj, ExcellonObject):
  4815. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4816. elif isinstance(obj, GeometryObject):
  4817. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4818. else:
  4819. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4820. except Exception as e:
  4821. return "Operation failed: %s" % str(e)
  4822. def abort_all_tasks(self):
  4823. """
  4824. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4825. on the first possible occasion.
  4826. :return:
  4827. """
  4828. if self.abort_flag is False:
  4829. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4830. self.abort_flag = True
  4831. self.cleanup.emit()
  4832. def app_is_idle(self):
  4833. if self.abort_flag:
  4834. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4835. self.abort_flag = False
  4836. def on_selectall(self):
  4837. """
  4838. Will draw a selection box shape around the selected objects.
  4839. :return:
  4840. """
  4841. self.defaults.report_usage("on_selectall()")
  4842. # delete the possible selection box around a possible selected object
  4843. self.delete_selection_shape()
  4844. for name in self.collection.get_names():
  4845. self.collection.set_active(name)
  4846. curr_sel_obj = self.collection.get_by_name(name)
  4847. # create the selection box around the selected object
  4848. if self.defaults['global_selection_shape'] is True:
  4849. self.draw_selection_shape(curr_sel_obj)
  4850. def on_preferences(self):
  4851. """
  4852. Adds the Preferences in a Tab in Plot Area
  4853. :return:
  4854. """
  4855. # add the tab if it was closed
  4856. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4857. # delete the absolute and relative position and messages in the infobar
  4858. self.ui.position_label.setText("")
  4859. self.ui.rel_position_label.setText("")
  4860. # Switch plot_area to preferences page
  4861. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4862. # self.ui.show()
  4863. # detect changes in the preferences
  4864. for idx in range(self.ui.pref_tab_area.count()):
  4865. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4866. try:
  4867. try:
  4868. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4869. except (TypeError, AttributeError):
  4870. pass
  4871. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4872. except AttributeError:
  4873. pass
  4874. try:
  4875. try:
  4876. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4877. except (TypeError, AttributeError):
  4878. pass
  4879. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4880. except AttributeError:
  4881. pass
  4882. try:
  4883. try:
  4884. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4885. except (TypeError, AttributeError):
  4886. pass
  4887. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4888. except AttributeError:
  4889. pass
  4890. try:
  4891. try:
  4892. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4893. except (TypeError, AttributeError):
  4894. pass
  4895. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4896. except AttributeError:
  4897. pass
  4898. try:
  4899. try:
  4900. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4901. except (TypeError, AttributeError):
  4902. pass
  4903. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4904. except AttributeError:
  4905. pass
  4906. def on_tools_database(self, source='app'):
  4907. """
  4908. Adds the Tools Database in a Tab in Plot Area.
  4909. :return:
  4910. """
  4911. for idx in range(self.ui.plot_tab_area.count()):
  4912. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4913. # there can be only one instance of Tools Database at one time
  4914. return
  4915. if source == 'app':
  4916. self.tools_db_tab = ToolsDB2(
  4917. app=self,
  4918. parent=self.ui,
  4919. callback_on_edited=self.on_tools_db_edited,
  4920. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4921. )
  4922. elif source == 'ncc':
  4923. self.tools_db_tab = ToolsDB2(
  4924. app=self,
  4925. parent=self.ui,
  4926. callback_on_edited=self.on_tools_db_edited,
  4927. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4928. )
  4929. elif source == 'paint':
  4930. self.tools_db_tab = ToolsDB2(
  4931. app=self,
  4932. parent=self.ui,
  4933. callback_on_edited=self.on_tools_db_edited,
  4934. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4935. )
  4936. # add the tab if it was closed
  4937. try:
  4938. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4939. self.tools_db_tab.setObjectName("database_tab")
  4940. except Exception as e:
  4941. log.debug("App.on_tools_database() --> %s" % str(e))
  4942. return
  4943. # delete the absolute and relative position and messages in the infobar
  4944. self.ui.position_label.setText("")
  4945. self.ui.rel_position_label.setText("")
  4946. # Switch plot_area to preferences page
  4947. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4948. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4949. self.tools_db_tab.ui_connect()
  4950. def on_tools_db_edited(self):
  4951. """
  4952. Executed whenever a tool is edited in Tools Database.
  4953. Will color the text of the Tools Database tab to Red color.
  4954. :return:
  4955. """
  4956. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4957. for idx in range(self.ui.plot_tab_area.count()):
  4958. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4959. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4960. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4961. self.tools_db_changed_flag = True
  4962. def on_geometry_tool_add_from_db_executed(self, tool):
  4963. """
  4964. Here add the tool from DB in the selected geometry object.
  4965. :return:
  4966. """
  4967. tool_from_db = deepcopy(tool)
  4968. obj = self.collection.get_active()
  4969. if isinstance(obj, GeometryObject):
  4970. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4971. # close the tab and delete it
  4972. for idx in range(self.ui.plot_tab_area.count()):
  4973. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4974. wdg = self.ui.plot_tab_area.widget(idx)
  4975. wdg.deleteLater()
  4976. self.ui.plot_tab_area.removeTab(idx)
  4977. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4978. else:
  4979. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4980. def on_plot_area_tab_closed(self, tab_obj_name):
  4981. """
  4982. Executed whenever a QTab is closed in the Plot Area.
  4983. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4984. :return:
  4985. """
  4986. if tab_obj_name == "preferences_tab":
  4987. self.preferencesUiManager.on_close_preferences_tab()
  4988. elif tab_obj_name == "database_tab":
  4989. # disconnect the signals from the table widget in tab
  4990. self.tools_db_tab.ui_disconnect()
  4991. if self.tools_db_changed_flag is True:
  4992. msgbox = QtWidgets.QMessageBox()
  4993. msgbox.setText(_("One or more Tools are edited.\n"
  4994. "Do you want to update the Tools Database?"))
  4995. msgbox.setWindowTitle(_("Save Tools Database"))
  4996. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4997. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4998. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4999. msgbox.setDefaultButton(bt_yes)
  5000. msgbox.exec_()
  5001. response = msgbox.clickedButton()
  5002. if response == bt_yes:
  5003. self.tools_db_tab.on_save_tools_db()
  5004. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  5005. else:
  5006. self.tools_db_changed_flag = False
  5007. self.inform.emit('')
  5008. return
  5009. self.tools_db_tab.deleteLater()
  5010. elif tab_obj_name == "text_editor_tab":
  5011. self.toggle_codeeditor = False
  5012. elif tab_obj_name == "bookmarks_tab":
  5013. self.book_dialog_tab.rebuild_actions()
  5014. self.book_dialog_tab.deleteLater()
  5015. else:
  5016. return
  5017. # def on_plotarea_tab_closed(self, tab_idx):
  5018. # """
  5019. #
  5020. # :param tab_idx: Index of the Tab from the plotarea that was closed
  5021. # :return:
  5022. # """
  5023. # widget = self.ui.plot_tab_area.widget(tab_idx)
  5024. #
  5025. # if widget is not None:
  5026. # widget.deleteLater()
  5027. # self.ui.plot_tab_area.removeTab(tab_idx)
  5028. def on_flipy(self):
  5029. """
  5030. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  5031. :return:
  5032. """
  5033. self.defaults.report_usage("on_flipy()")
  5034. obj_list = self.collection.get_selected()
  5035. xminlist = []
  5036. yminlist = []
  5037. xmaxlist = []
  5038. ymaxlist = []
  5039. if not obj_list:
  5040. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  5041. else:
  5042. try:
  5043. # first get a bounding box to fit all
  5044. for obj in obj_list:
  5045. xmin, ymin, xmax, ymax = obj.bounds()
  5046. xminlist.append(xmin)
  5047. yminlist.append(ymin)
  5048. xmaxlist.append(xmax)
  5049. ymaxlist.append(ymax)
  5050. # get the minimum x,y and maximum x,y for all objects selected
  5051. xminimal = min(xminlist)
  5052. yminimal = min(yminlist)
  5053. xmaximal = max(xmaxlist)
  5054. ymaximal = max(ymaxlist)
  5055. px = 0.5 * (xminimal + xmaximal)
  5056. py = 0.5 * (yminimal + ymaximal)
  5057. # execute mirroring
  5058. for obj in obj_list:
  5059. obj.mirror('X', [px, py])
  5060. obj.plot()
  5061. self.object_changed.emit(obj)
  5062. self.inform.emit('[success] %s' %
  5063. _("Flip on Y axis done."))
  5064. except Exception as e:
  5065. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5066. return
  5067. def on_flipx(self):
  5068. """
  5069. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5070. :return:
  5071. """
  5072. self.defaults.report_usage("on_flipx()")
  5073. obj_list = self.collection.get_selected()
  5074. xminlist = []
  5075. yminlist = []
  5076. xmaxlist = []
  5077. ymaxlist = []
  5078. if not obj_list:
  5079. self.inform.emit('[WARNING_NOTCL] %s' %
  5080. _("No object selected to Flip on X axis."))
  5081. else:
  5082. try:
  5083. # first get a bounding box to fit all
  5084. for obj in obj_list:
  5085. xmin, ymin, xmax, ymax = obj.bounds()
  5086. xminlist.append(xmin)
  5087. yminlist.append(ymin)
  5088. xmaxlist.append(xmax)
  5089. ymaxlist.append(ymax)
  5090. # get the minimum x,y and maximum x,y for all objects selected
  5091. xminimal = min(xminlist)
  5092. yminimal = min(yminlist)
  5093. xmaximal = max(xmaxlist)
  5094. ymaximal = max(ymaxlist)
  5095. px = 0.5 * (xminimal + xmaximal)
  5096. py = 0.5 * (yminimal + ymaximal)
  5097. # execute mirroring
  5098. for obj in obj_list:
  5099. obj.mirror('Y', [px, py])
  5100. obj.plot()
  5101. self.object_changed.emit(obj)
  5102. self.inform.emit('[success] %s' %
  5103. _("Flip on X axis done."))
  5104. except Exception as e:
  5105. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5106. return
  5107. def on_rotate(self, silent=False, preset=None):
  5108. """
  5109. Executed when Options -> Rotate Selection menu entry is clicked.
  5110. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5111. :param preset: A value to be used as predefined angle for rotation.
  5112. :return:
  5113. """
  5114. self.defaults.report_usage("on_rotate()")
  5115. obj_list = self.collection.get_selected()
  5116. xminlist = []
  5117. yminlist = []
  5118. xmaxlist = []
  5119. ymaxlist = []
  5120. if not obj_list:
  5121. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5122. else:
  5123. if silent is False:
  5124. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5125. min=-360, max=360, decimals=4,
  5126. init_val=float(self.defaults['tools_transform_rotate']))
  5127. num, ok = rotatebox.get_value()
  5128. else:
  5129. num = preset
  5130. ok = True
  5131. if ok:
  5132. try:
  5133. # first get a bounding box to fit all
  5134. for obj in obj_list:
  5135. xmin, ymin, xmax, ymax = obj.bounds()
  5136. xminlist.append(xmin)
  5137. yminlist.append(ymin)
  5138. xmaxlist.append(xmax)
  5139. ymaxlist.append(ymax)
  5140. # get the minimum x,y and maximum x,y for all objects selected
  5141. xminimal = min(xminlist)
  5142. yminimal = min(yminlist)
  5143. xmaximal = max(xmaxlist)
  5144. ymaximal = max(ymaxlist)
  5145. px = 0.5 * (xminimal + xmaximal)
  5146. py = 0.5 * (yminimal + ymaximal)
  5147. for sel_obj in obj_list:
  5148. sel_obj.rotate(-float(num), point=(px, py))
  5149. sel_obj.plot()
  5150. self.object_changed.emit(sel_obj)
  5151. self.inform.emit('[success] %s' %
  5152. _("Rotation done."))
  5153. except Exception as e:
  5154. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5155. return
  5156. def on_skewx(self):
  5157. """
  5158. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5159. :return:
  5160. """
  5161. self.defaults.report_usage("on_skewx()")
  5162. obj_list = self.collection.get_selected()
  5163. xminlist = []
  5164. yminlist = []
  5165. if not obj_list:
  5166. self.inform.emit('[WARNING_NOTCL] %s' %
  5167. _("No object selected to Skew/Shear on X axis."))
  5168. else:
  5169. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5170. min=-360, max=360, decimals=4,
  5171. init_val=float(self.defaults['tools_transform_skew_x']))
  5172. num, ok = skewxbox.get_value()
  5173. if ok:
  5174. # first get a bounding box to fit all
  5175. for obj in obj_list:
  5176. xmin, ymin, xmax, ymax = obj.bounds()
  5177. xminlist.append(xmin)
  5178. yminlist.append(ymin)
  5179. # get the minimum x,y and maximum x,y for all objects selected
  5180. xminimal = min(xminlist)
  5181. yminimal = min(yminlist)
  5182. for obj in obj_list:
  5183. obj.skew(num, 0, point=(xminimal, yminimal))
  5184. obj.plot()
  5185. self.object_changed.emit(obj)
  5186. self.inform.emit('[success] %s' %
  5187. _("Skew on X axis done."))
  5188. def on_skewy(self):
  5189. """
  5190. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5191. :return:
  5192. """
  5193. self.defaults.report_usage("on_skewy()")
  5194. obj_list = self.collection.get_selected()
  5195. xminlist = []
  5196. yminlist = []
  5197. if not obj_list:
  5198. self.inform.emit('[WARNING_NOTCL] %s' %
  5199. _("No object selected to Skew/Shear on Y axis."))
  5200. else:
  5201. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5202. min=-360, max=360, decimals=4,
  5203. init_val=float(self.defaults['tools_transform_skew_y']))
  5204. num, ok = skewybox.get_value()
  5205. if ok:
  5206. # first get a bounding box to fit all
  5207. for obj in obj_list:
  5208. xmin, ymin, xmax, ymax = obj.bounds()
  5209. xminlist.append(xmin)
  5210. yminlist.append(ymin)
  5211. # get the minimum x,y and maximum x,y for all objects selected
  5212. xminimal = min(xminlist)
  5213. yminimal = min(yminlist)
  5214. for obj in obj_list:
  5215. obj.skew(0, num, point=(xminimal, yminimal))
  5216. obj.plot()
  5217. self.object_changed.emit(obj)
  5218. self.inform.emit('[success] %s' %
  5219. _("Skew on Y axis done."))
  5220. def on_plots_updated(self):
  5221. """
  5222. Callback used to report when the plots have changed.
  5223. Adjust axes and zooms to fit.
  5224. :return: None
  5225. """
  5226. if self.is_legacy is False:
  5227. self.plotcanvas.update()
  5228. else:
  5229. self.plotcanvas.auto_adjust_axes()
  5230. self.on_zoom_fit(None)
  5231. self.collection.update_view()
  5232. # self.inform.emit(_("Plots updated ..."))
  5233. def on_toolbar_replot(self):
  5234. """
  5235. Callback for toolbar button. Re-plots all objects.
  5236. :return: None
  5237. """
  5238. self.defaults.report_usage("on_toolbar_replot")
  5239. self.log.debug("on_toolbar_replot()")
  5240. try:
  5241. self.collection.get_active().read_form()
  5242. except AttributeError:
  5243. self.log.debug("on_toolbar_replot(): AttributeError")
  5244. pass
  5245. self.plot_all()
  5246. def on_row_activated(self, index):
  5247. if index.isValid():
  5248. if index.internalPointer().parent_item != self.collection.root_item:
  5249. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5250. self.collection.on_item_activated(index)
  5251. def on_row_selected(self, obj_name):
  5252. """
  5253. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5254. It mean we clicked outside of the items and deselected all
  5255. :param obj_name:
  5256. :return:
  5257. """
  5258. if obj_name == 'none':
  5259. for act in self.ui.menuobjects.actions():
  5260. act.setChecked(False)
  5261. return
  5262. # get the name of the selected objects and add them to a list
  5263. name_list = []
  5264. for obj in self.collection.get_selected():
  5265. name_list.append(obj.options['name'])
  5266. # set all actions as unchecked but the ones selected make them checked
  5267. for act in self.ui.menuobjects.actions():
  5268. act.setChecked(False)
  5269. if act.text() in name_list:
  5270. act.setChecked(True)
  5271. def on_collection_updated(self, obj, state, old_name):
  5272. """
  5273. Create a menu from the object loaded in the collection.
  5274. :param obj: object that was changed (added, deleted, renamed)
  5275. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5276. :param old_name: the old name of the object before the action that triggered this slot happened
  5277. :return: None
  5278. """
  5279. icon_files = {
  5280. "gerber": self.resource_location + "/flatcam_icon16.png",
  5281. "excellon": self.resource_location + "/drill16.png",
  5282. "cncjob": self.resource_location + "/cnc16.png",
  5283. "geometry": self.resource_location + "/geometry16.png",
  5284. "script": self.resource_location + "/script_new16.png",
  5285. "document": self.resource_location + "/notes16_1.png"
  5286. }
  5287. if state == 'append':
  5288. for act in self.ui.menuobjects.actions():
  5289. try:
  5290. act.triggered.disconnect()
  5291. except TypeError:
  5292. pass
  5293. self.ui.menuobjects.clear()
  5294. gerber_list = []
  5295. exc_list = []
  5296. cncjob_list = []
  5297. geo_list = []
  5298. script_list = []
  5299. doc_list = []
  5300. for name in self.collection.get_names():
  5301. obj_named = self.collection.get_by_name(name)
  5302. if obj_named.kind == 'gerber':
  5303. gerber_list.append(name)
  5304. elif obj_named.kind == 'excellon':
  5305. exc_list.append(name)
  5306. elif obj_named.kind == 'cncjob':
  5307. cncjob_list.append(name)
  5308. elif obj_named.kind == 'geometry':
  5309. geo_list.append(name)
  5310. elif obj_named.kind == 'script':
  5311. script_list.append(name)
  5312. elif obj_named.kind == 'document':
  5313. doc_list.append(name)
  5314. def add_act(o_name):
  5315. obj_for_icon = self.collection.get_by_name(o_name)
  5316. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5317. add_action.setCheckable(True)
  5318. add_action.setText(o_name)
  5319. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5320. add_action.triggered.connect(
  5321. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5322. self.collection.set_inactive(o_name))
  5323. self.ui.menuobjects.addAction(add_action)
  5324. for name in gerber_list:
  5325. add_act(name)
  5326. self.ui.menuobjects.addSeparator()
  5327. for name in exc_list:
  5328. add_act(name)
  5329. self.ui.menuobjects.addSeparator()
  5330. for name in cncjob_list:
  5331. add_act(name)
  5332. self.ui.menuobjects.addSeparator()
  5333. for name in geo_list:
  5334. add_act(name)
  5335. self.ui.menuobjects.addSeparator()
  5336. for name in script_list:
  5337. add_act(name)
  5338. self.ui.menuobjects.addSeparator()
  5339. for name in doc_list:
  5340. add_act(name)
  5341. self.ui.menuobjects.addSeparator()
  5342. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5343. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5344. _('Select All')
  5345. )
  5346. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5347. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5348. _('Deselect All')
  5349. )
  5350. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5351. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5352. elif state == 'delete':
  5353. for act in self.ui.menuobjects.actions():
  5354. if act.text() == obj.options['name']:
  5355. try:
  5356. act.triggered.disconnect()
  5357. except TypeError:
  5358. pass
  5359. self.ui.menuobjects.removeAction(act)
  5360. break
  5361. elif state == 'rename':
  5362. for act in self.ui.menuobjects.actions():
  5363. if act.text() == old_name:
  5364. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5365. add_action.setText(obj.options['name'])
  5366. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5367. add_action.triggered.connect(
  5368. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5369. self.collection.set_inactive(obj.options['name']))
  5370. self.ui.menuobjects.insertAction(act, add_action)
  5371. try:
  5372. act.triggered.disconnect()
  5373. except TypeError:
  5374. pass
  5375. self.ui.menuobjects.removeAction(act)
  5376. break
  5377. elif state == 'delete_all':
  5378. for act in self.ui.menuobjects.actions():
  5379. try:
  5380. act.triggered.disconnect()
  5381. except TypeError:
  5382. pass
  5383. self.ui.menuobjects.clear()
  5384. self.ui.menuobjects.addSeparator()
  5385. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5386. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5387. _('Select All')
  5388. )
  5389. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5390. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5391. _('Deselect All')
  5392. )
  5393. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5394. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5395. def on_objects_selection(self, on_off):
  5396. obj_list = self.collection.get_names()
  5397. if on_off is True:
  5398. self.collection.set_all_active()
  5399. for act in self.ui.menuobjects.actions():
  5400. try:
  5401. act.setChecked(True)
  5402. except Exception:
  5403. pass
  5404. if obj_list:
  5405. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5406. else:
  5407. self.collection.set_all_inactive()
  5408. for act in self.ui.menuobjects.actions():
  5409. try:
  5410. act.setChecked(False)
  5411. except Exception:
  5412. pass
  5413. if obj_list:
  5414. self.inform.emit('%s' % _("Objects selection is cleared."))
  5415. else:
  5416. self.inform.emit('')
  5417. def grid_status(self):
  5418. if self.ui.grid_snap_btn.isChecked():
  5419. return True
  5420. else:
  5421. return False
  5422. def populate_cmenu_grids(self):
  5423. units = self.defaults['units'].lower()
  5424. # for act in self.ui.cmenu_gridmenu.actions():
  5425. # act.triggered.disconnect()
  5426. self.ui.cmenu_gridmenu.clear()
  5427. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5428. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5429. _("Grid On/Off"))
  5430. grid_toggle.setCheckable(True)
  5431. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5432. self.ui.cmenu_gridmenu.addSeparator()
  5433. for grid in sorted_list:
  5434. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5435. "%s" % str(grid))
  5436. action.triggered.connect(self.set_grid)
  5437. self.ui.cmenu_gridmenu.addSeparator()
  5438. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5439. _("Add"))
  5440. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5441. _("Delete"))
  5442. grid_add.triggered.connect(self.on_grid_add)
  5443. grid_delete.triggered.connect(self.on_grid_delete)
  5444. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5445. def set_grid(self):
  5446. menu_action = self.sender()
  5447. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5448. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5449. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5450. def on_grid_add(self):
  5451. # ## Current application units in lower Case
  5452. units = self.defaults['units'].lower()
  5453. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5454. text=_('Enter a Grid Value:'),
  5455. min=0.0000, max=99.9999, decimals=4)
  5456. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5457. val, ok = grid_add_popup.get_value()
  5458. if ok:
  5459. if float(val) == 0:
  5460. self.inform.emit('[WARNING_NOTCL] %s' %
  5461. _("Please enter a grid value with non-zero value, in Float format."))
  5462. return
  5463. else:
  5464. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5465. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5466. self.inform.emit('[success] %s...' %
  5467. _("New Grid added"))
  5468. else:
  5469. self.inform.emit('[WARNING_NOTCL] %s...' %
  5470. _("Grid already exists"))
  5471. else:
  5472. self.inform.emit('[WARNING_NOTCL] %s...' %
  5473. _("Adding New Grid cancelled"))
  5474. def on_grid_delete(self):
  5475. # ## Current application units in lower Case
  5476. units = self.defaults['units'].lower()
  5477. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5478. text='Enter a Grid Value:',
  5479. min=0.0000, max=99.9999, decimals=4)
  5480. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5481. val, ok = grid_del_popup.get_value()
  5482. if ok:
  5483. if float(val) == 0:
  5484. self.inform.emit('[WARNING_NOTCL] %s' %
  5485. _("Please enter a grid value with non-zero value, in Float format."))
  5486. return
  5487. else:
  5488. try:
  5489. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5490. except ValueError:
  5491. self.inform.emit('[ERROR_NOTCL]%s...' %
  5492. _(" Grid Value does not exist"))
  5493. return
  5494. self.inform.emit('[success] %s...' %
  5495. _("Grid Value deleted"))
  5496. else:
  5497. self.inform.emit('[WARNING_NOTCL] %s...' %
  5498. _("Delete Grid value cancelled"))
  5499. def on_shortcut_list(self):
  5500. self.defaults.report_usage("on_shortcut_list()")
  5501. # add the tab if it was closed
  5502. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5503. # delete the absolute and relative position and messages in the infobar
  5504. self.ui.position_label.setText("")
  5505. self.ui.rel_position_label.setText("")
  5506. # Switch plot_area to preferences page
  5507. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5508. # self.ui.show()
  5509. def on_select_tab(self, name):
  5510. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5511. if self.ui.splitter.sizes()[0] == 0:
  5512. self.ui.splitter.setSizes([1, 1])
  5513. else:
  5514. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5515. self.ui.splitter.setSizes([0, 1])
  5516. if name == 'project':
  5517. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5518. elif name == 'selected':
  5519. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5520. elif name == 'tool':
  5521. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5522. def on_copy_name(self):
  5523. self.defaults.report_usage("on_copy_name()")
  5524. obj = self.collection.get_active()
  5525. try:
  5526. name = obj.options["name"]
  5527. except AttributeError:
  5528. log.debug("on_copy_name() --> No object selected to copy it's name")
  5529. self.inform.emit('[WARNING_NOTCL]%s' %
  5530. _(" No object selected to copy it's name"))
  5531. return
  5532. self.clipboard.setText(name)
  5533. self.inform.emit(_("Name copied on clipboard ..."))
  5534. def on_mouse_click_over_plot(self, event):
  5535. """
  5536. Default actions are:
  5537. :param event: Contains information about the event, like which button
  5538. was clicked, the pixel coordinates and the axes coordinates.
  5539. :return: None
  5540. """
  5541. self.pos = []
  5542. if self.is_legacy is False:
  5543. event_pos = event.pos
  5544. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5545. # # Set the mouse button for panning
  5546. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5547. else:
  5548. event_pos = (event.xdata, event.ydata)
  5549. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5550. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5551. # So it can receive key presses
  5552. self.plotcanvas.native.setFocus()
  5553. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5554. if self.grid_status():
  5555. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5556. else:
  5557. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5558. try:
  5559. if event.button == 1:
  5560. # Reset here the relative coordinates so there is a new reference on the click position
  5561. if self.rel_point1 is None:
  5562. self.rel_point1 = self.pos
  5563. else:
  5564. self.rel_point2 = copy(self.rel_point1)
  5565. self.rel_point1 = self.pos
  5566. self.on_mouse_move_over_plot(event, origin_click=True)
  5567. except Exception as e:
  5568. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5569. def on_mouse_double_click_over_plot(self, event):
  5570. if event.button == 1:
  5571. self.doubleclick = True
  5572. def on_mouse_move_over_plot(self, event, origin_click=None):
  5573. """
  5574. Callback for the mouse motion event over the plot.
  5575. :param event: Contains information about the event.
  5576. :param origin_click
  5577. :return: None
  5578. """
  5579. if self.is_legacy is False:
  5580. event_pos = event.pos
  5581. if self.defaults["global_pan_button"] == '2':
  5582. pan_button = 2
  5583. else:
  5584. pan_button = 3
  5585. self.event_is_dragging = event.is_dragging
  5586. else:
  5587. event_pos = (event.xdata, event.ydata)
  5588. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5589. if self.defaults["global_pan_button"] == '2':
  5590. pan_button = 3
  5591. else:
  5592. pan_button = 2
  5593. self.event_is_dragging = self.plotcanvas.is_dragging
  5594. # So it can receive key presses but not when the Tcl Shell is active
  5595. if not self.ui.shell_dock.isVisible():
  5596. if not self.plotcanvas.native.hasFocus():
  5597. self.plotcanvas.native.setFocus()
  5598. self.pos_jump = event_pos
  5599. self.ui.popMenu.mouse_is_panning = False
  5600. if origin_click is None:
  5601. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5602. if event.button == pan_button and self.event_is_dragging == 1:
  5603. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5604. if self.ui.popMenu.popup_active:
  5605. self.ui.popMenu.popup_active = False
  5606. return
  5607. self.ui.popMenu.mouse_is_panning = True
  5608. return
  5609. if self.rel_point1 is not None:
  5610. try: # May fail in case mouse not within axes
  5611. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5612. if self.grid_status():
  5613. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5614. # Update cursor
  5615. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5616. symbol='++', edge_color=self.cursor_color_3D,
  5617. edge_width=self.defaults["global_cursor_width"],
  5618. size=self.defaults["global_cursor_size"])
  5619. else:
  5620. pos = (pos_canvas[0], pos_canvas[1])
  5621. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5622. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5623. self.dx = pos[0] - float(self.rel_point1[0])
  5624. self.dy = pos[1] - float(self.rel_point1[1])
  5625. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5626. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5627. self.mouse = [pos[0], pos[1]]
  5628. # if the mouse is moved and the LMB is clicked then the action is a selection
  5629. if self.event_is_dragging == 1 and event.button == 1:
  5630. self.delete_selection_shape()
  5631. if self.dx < 0:
  5632. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5633. face_color=self.defaults['global_alt_sel_fill'])
  5634. self.selection_type = False
  5635. elif self.dx >= 0:
  5636. self.draw_moving_selection_shape(self.pos, pos)
  5637. self.selection_type = True
  5638. else:
  5639. self.selection_type = None
  5640. else:
  5641. self.selection_type = None
  5642. # hover effect - enabled in Preferences -> General -> GUI Settings
  5643. if self.defaults['global_hover']:
  5644. for obj in self.collection.get_list():
  5645. try:
  5646. # select the object(s) only if it is enabled (plotted)
  5647. if obj.options['plot']:
  5648. if obj not in self.collection.get_selected():
  5649. poly_obj = Polygon(
  5650. [(obj.options['xmin'], obj.options['ymin']),
  5651. (obj.options['xmax'], obj.options['ymin']),
  5652. (obj.options['xmax'], obj.options['ymax']),
  5653. (obj.options['xmin'], obj.options['ymax'])]
  5654. )
  5655. if Point(pos).within(poly_obj):
  5656. if obj.isHovering is False:
  5657. obj.isHovering = True
  5658. obj.notHovering = True
  5659. # create the selection box around the selected object
  5660. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5661. else:
  5662. if obj.notHovering is True:
  5663. obj.notHovering = False
  5664. obj.isHovering = False
  5665. self.delete_hover_shape()
  5666. except Exception:
  5667. # the Exception here will happen if we try to select on screen and we have an
  5668. # newly (and empty) just created Geometry or Excellon object that do not have the
  5669. # xmin, xmax, ymin, ymax options.
  5670. # In this case poly_obj creation (see above) will fail
  5671. pass
  5672. except Exception:
  5673. self.ui.position_label.setText("")
  5674. self.ui.rel_position_label.setText("")
  5675. self.mouse = None
  5676. def on_mouse_click_release_over_plot(self, event):
  5677. """
  5678. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5679. and has been registered in ''self.__init__()''.
  5680. :param event: contains information about the event.
  5681. :return:
  5682. """
  5683. if self.is_legacy is False:
  5684. event_pos = event.pos
  5685. right_button = 2
  5686. else:
  5687. event_pos = (event.xdata, event.ydata)
  5688. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5689. right_button = 3
  5690. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5691. if self.grid_status():
  5692. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5693. else:
  5694. pos = (pos_canvas[0], pos_canvas[1])
  5695. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5696. # canvas menu
  5697. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5698. self.ui.popMenu.mouse_is_panning = False
  5699. self.cursor = QtGui.QCursor()
  5700. self.populate_cmenu_grids()
  5701. self.ui.popMenu.popup(self.cursor.pos())
  5702. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5703. # selection and then select a type of selection ("enclosing" or "touching")
  5704. if event.button == 1: # left click
  5705. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5706. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5707. if modifiers == QtCore.Qt.ShiftModifier:
  5708. # do not auto open the Project Tab
  5709. self.click_noproject = True
  5710. self.clipboard.setText(
  5711. self.defaults["global_point_clipboard_format"] %
  5712. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5713. )
  5714. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5715. return
  5716. if self.doubleclick is True:
  5717. self.doubleclick = False
  5718. if self.collection.get_selected():
  5719. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5720. if self.ui.splitter.sizes()[0] == 0:
  5721. self.ui.splitter.setSizes([1, 1])
  5722. try:
  5723. # delete the selection shape(S) as it may be in the way
  5724. self.delete_selection_shape()
  5725. self.delete_hover_shape()
  5726. except Exception as e:
  5727. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5728. return
  5729. else:
  5730. # WORKAROUND for LEGACY MODE
  5731. if self.is_legacy is True:
  5732. # if there is no move on canvas then we have no dragging selection
  5733. if self.dx == 0 or self.dy == 0:
  5734. self.selection_type = None
  5735. if self.selection_type is not None:
  5736. try:
  5737. self.selection_area_handler(self.pos, pos, self.selection_type)
  5738. self.selection_type = None
  5739. except Exception as e:
  5740. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5741. return
  5742. else:
  5743. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5744. if key_modifier == QtCore.Qt.ShiftModifier:
  5745. mod_key = 'Shift'
  5746. elif key_modifier == QtCore.Qt.ControlModifier:
  5747. mod_key = 'Control'
  5748. else:
  5749. mod_key = None
  5750. try:
  5751. if mod_key == self.defaults["global_mselect_key"]:
  5752. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5753. # deselect, and if it's not selected then it will be selected
  5754. # If there is no active command (self.command_active is None) then we check if we clicked
  5755. # on a object by checking the bounding limits against mouse click position
  5756. if self.command_active is None:
  5757. self.select_objects(key='multisel')
  5758. self.delete_hover_shape()
  5759. else:
  5760. # If there is no active command (self.command_active is None) then we check if we clicked
  5761. # on a object by checking the bounding limits against mouse click position
  5762. if self.command_active is None:
  5763. self.select_objects()
  5764. self.delete_hover_shape()
  5765. except Exception as e:
  5766. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5767. return
  5768. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5769. """
  5770. :param start_pos: mouse position when the selection LMB click was done
  5771. :param end_pos: mouse position when the left mouse button is released
  5772. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5773. :return:
  5774. """
  5775. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5776. # delete previous selection shape
  5777. self.delete_selection_shape()
  5778. # make all objects inactive
  5779. self.collection.set_all_inactive()
  5780. for obj in self.collection.get_list():
  5781. try:
  5782. # select the object(s) only if it is enabled (plotted)
  5783. if obj.options['plot']:
  5784. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5785. (obj.options['xmax'], obj.options['ymin']),
  5786. (obj.options['xmax'], obj.options['ymax']),
  5787. (obj.options['xmin'], obj.options['ymax'])])
  5788. if sel_type is True:
  5789. if poly_obj.within(poly_selection):
  5790. # create the selection box around the selected object
  5791. if self.defaults['global_selection_shape'] is True:
  5792. self.draw_selection_shape(obj)
  5793. self.collection.set_active(obj.options['name'])
  5794. else:
  5795. if poly_selection.intersects(poly_obj):
  5796. # create the selection box around the selected object
  5797. if self.defaults['global_selection_shape'] is True:
  5798. self.draw_selection_shape(obj)
  5799. self.collection.set_active(obj.options['name'])
  5800. obj.selection_shape_drawn = True
  5801. except Exception as e:
  5802. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5803. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5804. # In this case poly_obj creation (see above) will fail
  5805. log.debug("App.selection_area_handler() --> %s" % str(e))
  5806. def select_objects(self, key=None):
  5807. """
  5808. Will select objects clicked on canvas
  5809. :param key: for future use in cumulative selection
  5810. :return:
  5811. """
  5812. # list where we store the overlapped objects under our mouse left click position
  5813. if key is None:
  5814. self.objects_under_the_click_list = []
  5815. # Populate the list with the overlapped objects on the click position
  5816. curr_x, curr_y = self.pos
  5817. for obj in self.all_objects_list:
  5818. # ScriptObject and DocumentObject objects can't be selected
  5819. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5820. continue
  5821. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5822. continue
  5823. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5824. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5825. if obj.options['name'] not in self.objects_under_the_click_list:
  5826. if obj.options['plot']:
  5827. # add objects to the objects_under_the_click list only if the object is plotted
  5828. # (active and not disabled)
  5829. self.objects_under_the_click_list.append(obj.options['name'])
  5830. try:
  5831. if self.objects_under_the_click_list:
  5832. curr_sel_obj = self.collection.get_active()
  5833. # case when there is only an object under the click and we toggle it
  5834. if len(self.objects_under_the_click_list) == 1:
  5835. if curr_sel_obj is None:
  5836. self.collection.set_active(self.objects_under_the_click_list[0])
  5837. curr_sel_obj = self.collection.get_active()
  5838. # create the selection box around the selected object
  5839. if self.defaults['global_selection_shape'] is True:
  5840. self.draw_selection_shape(curr_sel_obj)
  5841. curr_sel_obj.selection_shape_drawn = True
  5842. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5843. self.on_objects_selection(False)
  5844. self.delete_selection_shape()
  5845. curr_sel_obj.selection_shape_drawn = False
  5846. self.collection.set_active(self.objects_under_the_click_list[0])
  5847. curr_sel_obj = self.collection.get_active()
  5848. # create the selection box around the selected object
  5849. if self.defaults['global_selection_shape'] is True:
  5850. self.draw_selection_shape(curr_sel_obj)
  5851. curr_sel_obj.selection_shape_drawn = True
  5852. self.selected_message(curr_sel_obj=curr_sel_obj)
  5853. elif curr_sel_obj.selection_shape_drawn is False:
  5854. if self.defaults['global_selection_shape'] is True:
  5855. self.draw_selection_shape(curr_sel_obj)
  5856. curr_sel_obj.selection_shape_drawn = True
  5857. else:
  5858. self.on_objects_selection(False)
  5859. self.delete_selection_shape()
  5860. if self.call_source != 'app':
  5861. self.call_source = 'app'
  5862. self.selected_message(curr_sel_obj=curr_sel_obj)
  5863. else:
  5864. # If there is no selected object
  5865. # make active the first element of the overlapped objects list
  5866. if self.collection.get_active() is None:
  5867. self.collection.set_active(self.objects_under_the_click_list[0])
  5868. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5869. name_sel_obj = self.collection.get_active().options['name']
  5870. # In case that there is a selected object but it is not in the overlapped object list
  5871. # make that object inactive and activate the first element in the overlapped object list
  5872. if name_sel_obj not in self.objects_under_the_click_list:
  5873. self.collection.set_inactive(name_sel_obj)
  5874. name_sel_obj = self.objects_under_the_click_list[0]
  5875. self.collection.set_active(name_sel_obj)
  5876. else:
  5877. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5878. self.collection.set_all_inactive()
  5879. self.collection.set_active(
  5880. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5881. curr_sel_obj = self.collection.get_active()
  5882. # delete the possible selection box around a possible selected object
  5883. self.delete_selection_shape()
  5884. curr_sel_obj.selection_shape_drawn = False
  5885. # create the selection box around the selected object
  5886. if self.defaults['global_selection_shape'] is True:
  5887. self.draw_selection_shape(curr_sel_obj)
  5888. curr_sel_obj.selection_shape_drawn = True
  5889. self.selected_message(curr_sel_obj=curr_sel_obj)
  5890. else:
  5891. # deselect everything
  5892. self.on_objects_selection(False)
  5893. # delete the possible selection box around a possible selected object
  5894. self.delete_selection_shape()
  5895. for o in self.collection.get_list():
  5896. o.selection_shape_drawn = False
  5897. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5898. # only when working on App
  5899. if self.call_source == 'app':
  5900. if self.click_noproject is False:
  5901. # if the Tool Tab is in focus don't change focus to Project Tab
  5902. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5903. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5904. else:
  5905. # restore auto open the Project Tab
  5906. self.click_noproject = False
  5907. # delete any text in the status bar, implicitly the last object name that was selected
  5908. # self.inform.emit("")
  5909. else:
  5910. self.call_source = 'app'
  5911. except Exception as e:
  5912. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5913. def selected_message(self, curr_sel_obj):
  5914. if curr_sel_obj:
  5915. if curr_sel_obj.kind == 'gerber':
  5916. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5917. color='green',
  5918. name=str(curr_sel_obj.options['name']),
  5919. tx=_("selected"))
  5920. )
  5921. elif curr_sel_obj.kind == 'excellon':
  5922. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5923. color='brown',
  5924. name=str(curr_sel_obj.options['name']),
  5925. tx=_("selected"))
  5926. )
  5927. elif curr_sel_obj.kind == 'cncjob':
  5928. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5929. color='blue',
  5930. name=str(curr_sel_obj.options['name']),
  5931. tx=_("selected"))
  5932. )
  5933. elif curr_sel_obj.kind == 'geometry':
  5934. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5935. color='red',
  5936. name=str(curr_sel_obj.options['name']),
  5937. tx=_("selected"))
  5938. )
  5939. def delete_hover_shape(self):
  5940. self.hover_shapes.clear()
  5941. self.hover_shapes.redraw()
  5942. def draw_hover_shape(self, sel_obj, color=None):
  5943. """
  5944. :param sel_obj: The object for which the hover shape must be drawn
  5945. :param color: The color of the hover shape
  5946. :return: None
  5947. """
  5948. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5949. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5950. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5951. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5952. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5953. if self.defaults['units'].upper() == 'MM':
  5954. hover_rect = hover_rect.buffer(-0.1)
  5955. hover_rect = hover_rect.buffer(0.2)
  5956. else:
  5957. hover_rect = hover_rect.buffer(-0.00393)
  5958. hover_rect = hover_rect.buffer(0.00787)
  5959. # if color:
  5960. # face = Color(color)
  5961. # face.alpha = 0.2
  5962. # outline = Color(color, alpha=0.8)
  5963. # else:
  5964. # face = Color(self.defaults['global_sel_fill'])
  5965. # face.alpha = 0.2
  5966. # outline = self.defaults['global_sel_line']
  5967. if color:
  5968. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5969. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5970. else:
  5971. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5972. outline = self.defaults['global_sel_line']
  5973. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5974. if self.is_legacy is True:
  5975. self.hover_shapes.redraw()
  5976. def delete_selection_shape(self):
  5977. self.move_tool.sel_shapes.clear()
  5978. self.move_tool.sel_shapes.redraw()
  5979. def draw_selection_shape(self, sel_obj, color=None):
  5980. """
  5981. Will draw a selection shape around the selected object.
  5982. :param sel_obj: The object for which the selection shape must be drawn
  5983. :param color: The color for the selection shape.
  5984. :return: None
  5985. """
  5986. if sel_obj is None:
  5987. return
  5988. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5989. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5990. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5991. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5992. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5993. if self.defaults['units'].upper() == 'MM':
  5994. sel_rect = sel_rect.buffer(-0.1)
  5995. sel_rect = sel_rect.buffer(0.2)
  5996. else:
  5997. sel_rect = sel_rect.buffer(-0.00393)
  5998. sel_rect = sel_rect.buffer(0.00787)
  5999. if color:
  6000. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6001. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6002. else:
  6003. if self.is_legacy is False:
  6004. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6005. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  6006. else:
  6007. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  6008. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  6009. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6010. color=outline,
  6011. face_color=face,
  6012. update=True,
  6013. layer=0,
  6014. tolerance=None))
  6015. if self.is_legacy is True:
  6016. self.move_tool.sel_shapes.redraw()
  6017. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6018. """
  6019. Will draw a selection shape when dragging mouse on canvas.
  6020. :param old_coords: Old coordinates
  6021. :param coords: New coordinates
  6022. :param kwargs: Keyword arguments
  6023. :return:
  6024. """
  6025. if 'color' in kwargs:
  6026. color = kwargs['color']
  6027. else:
  6028. color = self.defaults['global_sel_line']
  6029. if 'face_color' in kwargs:
  6030. face_color = kwargs['face_color']
  6031. else:
  6032. face_color = self.defaults['global_sel_fill']
  6033. if 'face_alpha' in kwargs:
  6034. face_alpha = kwargs['face_alpha']
  6035. else:
  6036. face_alpha = 0.3
  6037. x0, y0 = old_coords
  6038. x1, y1 = coords
  6039. pt1 = (x0, y0)
  6040. pt2 = (x1, y0)
  6041. pt3 = (x1, y1)
  6042. pt4 = (x0, y1)
  6043. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6044. # color_t = Color(face_color)
  6045. # color_t.alpha = face_alpha
  6046. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  6047. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6048. layer=0, tolerance=None)
  6049. if self.is_legacy is True:
  6050. self.move_tool.sel_shapes.redraw()
  6051. def on_file_new_click(self):
  6052. """
  6053. Callback for menu item File -> New.
  6054. Executed on clicking the Menu -> File -> New Project
  6055. :return:
  6056. """
  6057. if self.collection.get_list() and self.should_we_save:
  6058. msgbox = QtWidgets.QMessageBox()
  6059. # msgbox.setText("<B>Save changes ...</B>")
  6060. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6061. "Creating a New project will delete them.\n"
  6062. "Do you want to Save the project?"))
  6063. msgbox.setWindowTitle(_("Save changes"))
  6064. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6065. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6066. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6067. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6068. msgbox.setDefaultButton(bt_yes)
  6069. msgbox.exec_()
  6070. response = msgbox.clickedButton()
  6071. if response == bt_yes:
  6072. self.on_file_saveprojectas()
  6073. elif response == bt_cancel:
  6074. return
  6075. elif response == bt_no:
  6076. self.on_file_new()
  6077. else:
  6078. self.on_file_new()
  6079. self.inform.emit('[success] %s...' % _("New Project created"))
  6080. def on_file_new(self, cli=None):
  6081. """
  6082. Returns the application to its startup state. This method is thread-safe.
  6083. :param cli: Boolean. If True this method was run from command line
  6084. :return: None
  6085. """
  6086. self.defaults.report_usage("on_file_new")
  6087. # Remove everything from memory
  6088. App.log.debug("on_file_new()")
  6089. # close any editor that might be open
  6090. if self.call_source != 'app':
  6091. self.editor2object(cleanup=True)
  6092. # ## EDITOR section
  6093. self.geo_editor = FlatCAMGeoEditor(self)
  6094. self.exc_editor = FlatCAMExcEditor(self)
  6095. self.grb_editor = FlatCAMGrbEditor(self)
  6096. # Clear pool
  6097. self.clear_pool()
  6098. for obj in self.collection.get_list():
  6099. # delete shapes left drawn from mark shape_collections, if any
  6100. if isinstance(obj, GerberObject):
  6101. try:
  6102. for el in obj.mark_shapes:
  6103. obj.mark_shapes[el].clear(update=True)
  6104. obj.mark_shapes[el].enabled = False
  6105. del el
  6106. except AttributeError:
  6107. pass
  6108. # also delete annotation shapes, if any
  6109. elif isinstance(obj, CNCJobObject):
  6110. try:
  6111. obj.text_col.enabled = False
  6112. del obj.text_col
  6113. obj.annotation.clear(update=True)
  6114. del obj.annotation
  6115. except AttributeError:
  6116. pass
  6117. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6118. self.shell.init_tcl()
  6119. # delete any selection shape on canvas
  6120. self.delete_selection_shape()
  6121. # delete all FlatCAM objects
  6122. self.collection.delete_all()
  6123. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  6124. self.setup_component_editor()
  6125. # Clear project filename
  6126. self.project_filename = None
  6127. # Load the application defaults
  6128. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6129. # Re-fresh project options
  6130. self.on_options_app2project()
  6131. # Init FlatCAMTools
  6132. self.init_tools()
  6133. # Try to close all tabs in the PlotArea but only if the GUI is active (CLI is None)
  6134. if cli is None:
  6135. # we need to go in reverse because once we remove a tab then the index changes
  6136. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  6137. # and so on. Therefore the deletion should be done in reverse
  6138. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  6139. for index in range(wdg_count, -1, -1):
  6140. try:
  6141. self.ui.plot_tab_area.closeTab(index)
  6142. except Exception as e:
  6143. log.debug("App.on_file_new() --> %s" % str(e))
  6144. # # And then add again the Plot Area
  6145. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  6146. self.ui.plot_tab_area.protectTab(0)
  6147. # take the focus of the Notebook on Project Tab.
  6148. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6149. self.set_ui_title(name=_("New Project - Not saved"))
  6150. def obj_properties(self):
  6151. """
  6152. Will launch the object Properties Tool
  6153. :return:
  6154. """
  6155. self.defaults.report_usage("obj_properties()")
  6156. self.properties_tool.run(toggle=False)
  6157. def on_project_context_save(self):
  6158. """
  6159. Wrapper, will save the object function of it's type
  6160. :return:
  6161. """
  6162. obj = self.collection.get_active()
  6163. if type(obj) == GeometryObject:
  6164. self.on_file_exportdxf()
  6165. elif type(obj) == ExcellonObject:
  6166. self.on_file_saveexcellon()
  6167. elif type(obj) == CNCJobObject:
  6168. obj.on_exportgcode_button_click()
  6169. elif type(obj) == GerberObject:
  6170. self.on_file_savegerber()
  6171. elif type(obj) == ScriptObject:
  6172. self.on_file_savescript()
  6173. elif type(obj) == DocumentObject:
  6174. self.on_file_savedocument()
  6175. def obj_move(self):
  6176. """
  6177. Callback for the Move menu entry in various Context Menu's.
  6178. :return:
  6179. """
  6180. self.defaults.report_usage("obj_move()")
  6181. self.move_tool.run(toggle=False)
  6182. def on_fileopengerber(self, signal, name=None):
  6183. """
  6184. File menu callback for opening a Gerber.
  6185. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6186. :param name:
  6187. :return: None
  6188. """
  6189. self.defaults.report_usage("on_fileopengerber")
  6190. App.log.debug("on_fileopengerber()")
  6191. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6192. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6193. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6194. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6195. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6196. "*.mil);;" \
  6197. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6198. "Allegro Files (*.art);;" \
  6199. "Mentor Files (*.pho *.gdo);;" \
  6200. "All Files (*.*)"
  6201. if name is None:
  6202. try:
  6203. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6204. directory=self.get_last_folder(),
  6205. filter=_filter_)
  6206. except TypeError:
  6207. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6208. filenames = [str(filename) for filename in filenames]
  6209. else:
  6210. filenames = [name]
  6211. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6212. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6213. _("Opening Gerber file.")),
  6214. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6215. color=QtGui.QColor("gray"))
  6216. if len(filenames) == 0:
  6217. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6218. else:
  6219. for filename in filenames:
  6220. if filename != '':
  6221. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6222. def on_fileopenexcellon(self, signal, name=None):
  6223. """
  6224. File menu callback for opening an Excellon file.
  6225. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6226. :param name:
  6227. :return: None
  6228. """
  6229. self.defaults.report_usage("on_fileopenexcellon")
  6230. App.log.debug("on_fileopenexcellon()")
  6231. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6232. "All Files (*.*)"
  6233. if name is None:
  6234. try:
  6235. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6236. directory=self.get_last_folder(),
  6237. filter=_filter_)
  6238. except TypeError:
  6239. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6240. filenames = [str(filename) for filename in filenames]
  6241. else:
  6242. filenames = [str(name)]
  6243. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6244. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6245. _("Opening Excellon file.")),
  6246. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6247. color=QtGui.QColor("gray"))
  6248. if len(filenames) == 0:
  6249. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6250. else:
  6251. for filename in filenames:
  6252. if filename != '':
  6253. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6254. def on_fileopengcode(self, signal, name=None):
  6255. """
  6256. File menu call back for opening gcode.
  6257. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6258. :param name:
  6259. :return:
  6260. """
  6261. self.defaults.report_usage("on_fileopengcode")
  6262. App.log.debug("on_fileopengcode()")
  6263. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6264. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6265. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6266. "All Files (*.*)"
  6267. if name is None:
  6268. try:
  6269. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6270. directory=self.get_last_folder(),
  6271. filter=_filter_)
  6272. except TypeError:
  6273. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6274. filenames = [str(filename) for filename in filenames]
  6275. else:
  6276. filenames = [name]
  6277. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6278. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6279. _("Opening G-Code file.")),
  6280. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6281. color=QtGui.QColor("gray"))
  6282. if len(filenames) == 0:
  6283. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6284. else:
  6285. for filename in filenames:
  6286. if filename != '':
  6287. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6288. def on_file_openproject(self, signal):
  6289. """
  6290. File menu callback for opening a project.
  6291. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6292. :return: None
  6293. """
  6294. self.defaults.report_usage("on_file_openproject")
  6295. App.log.debug("on_file_openproject()")
  6296. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6297. try:
  6298. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6299. directory=self.get_last_folder(), filter=_filter_)
  6300. except TypeError:
  6301. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6302. # The Qt methods above will return a QString which can cause problems later.
  6303. # So far json.dump() will fail to serialize it.
  6304. # TODO: Improve the serialization methods and remove this fix.
  6305. filename = str(filename)
  6306. if filename == "":
  6307. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6308. else:
  6309. # self.worker_task.emit({'fcn': self.open_project,
  6310. # 'params': [filename]})
  6311. # The above was failing because open_project() is not
  6312. # thread safe. The new_project()
  6313. self.open_project(filename)
  6314. def on_fileopenhpgl2(self, signal, name=None):
  6315. """
  6316. File menu callback for opening a HPGL2.
  6317. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6318. :param name:
  6319. :return: None
  6320. """
  6321. self.defaults.report_usage("on_fileopenhpgl2")
  6322. App.log.debug("on_fileopenhpgl2()")
  6323. _filter_ = "HPGL2 Files (*.plt);;" \
  6324. "All Files (*.*)"
  6325. if name is None:
  6326. try:
  6327. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6328. directory=self.get_last_folder(),
  6329. filter=_filter_)
  6330. except TypeError:
  6331. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6332. filenames = [str(filename) for filename in filenames]
  6333. else:
  6334. filenames = [name]
  6335. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6336. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6337. _("Opening HPGL2 file.")),
  6338. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6339. color=QtGui.QColor("gray"))
  6340. if len(filenames) == 0:
  6341. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6342. else:
  6343. for filename in filenames:
  6344. if filename != '':
  6345. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6346. def on_file_openconfig(self, signal):
  6347. """
  6348. File menu callback for opening a config file.
  6349. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6350. :return: None
  6351. """
  6352. self.defaults.report_usage("on_file_openconfig")
  6353. App.log.debug("on_file_openconfig()")
  6354. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6355. try:
  6356. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6357. directory=self.data_path, filter=_filter_)
  6358. except TypeError:
  6359. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6360. filter=_filter_)
  6361. if filename == "":
  6362. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6363. else:
  6364. self.open_config_file(filename)
  6365. def on_file_exportsvg(self):
  6366. """
  6367. Callback for menu item File->Export SVG.
  6368. :return: None
  6369. """
  6370. self.defaults.report_usage("on_file_exportsvg")
  6371. App.log.debug("on_file_exportsvg()")
  6372. obj = self.collection.get_active()
  6373. if obj is None:
  6374. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6375. msg = _("Please Select a Geometry object to export")
  6376. msgbox = QtWidgets.QMessageBox()
  6377. msgbox.setInformativeText(msg)
  6378. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6379. msgbox.setDefaultButton(bt_ok)
  6380. msgbox.exec_()
  6381. return
  6382. # Check for more compatible types and add as required
  6383. if (not isinstance(obj, GeometryObject)
  6384. and not isinstance(obj, GerberObject)
  6385. and not isinstance(obj, CNCJobObject)
  6386. and not isinstance(obj, ExcellonObject)):
  6387. msg = '[ERROR_NOTCL] %s' % \
  6388. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6389. msgbox = QtWidgets.QMessageBox()
  6390. msgbox.setInformativeText(msg)
  6391. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6392. msgbox.setDefaultButton(bt_ok)
  6393. msgbox.exec_()
  6394. return
  6395. name = obj.options["name"]
  6396. _filter = "SVG File (*.svg);;All Files (*.*)"
  6397. try:
  6398. filename, _f = FCFileSaveDialog.get_saved_filename(
  6399. caption=_("Export SVG"),
  6400. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6401. filter=_filter)
  6402. except TypeError:
  6403. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6404. filename = str(filename)
  6405. if filename == "":
  6406. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6407. return
  6408. else:
  6409. self.export_svg(name, filename)
  6410. if self.defaults["global_open_style"] is False:
  6411. self.file_opened.emit("SVG", filename)
  6412. self.file_saved.emit("SVG", filename)
  6413. def on_file_exportpng(self):
  6414. self.defaults.report_usage("on_file_exportpng")
  6415. App.log.debug("on_file_exportpng()")
  6416. self.date = str(datetime.today()).rpartition('.')[0]
  6417. self.date = ''.join(c for c in self.date if c not in ':-')
  6418. self.date = self.date.replace(' ', '_')
  6419. if self.is_legacy is False:
  6420. image = _screenshot()
  6421. data = np.asarray(image)
  6422. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6423. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6424. return
  6425. filter_ = "PNG File (*.png);;All Files (*.*)"
  6426. try:
  6427. filename, _f = FCFileSaveDialog.get_saved_filename(
  6428. caption=_("Export PNG Image"),
  6429. directory=self.get_last_save_folder() + '/png_' + self.date,
  6430. filter=filter_)
  6431. except TypeError:
  6432. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6433. filename = str(filename)
  6434. if filename == "":
  6435. self.inform.emit(_("Cancelled."))
  6436. return
  6437. else:
  6438. if self.is_legacy is False:
  6439. write_png(filename, data)
  6440. else:
  6441. self.plotcanvas.figure.savefig(filename)
  6442. if self.defaults["global_open_style"] is False:
  6443. self.file_opened.emit("png", filename)
  6444. self.file_saved.emit("png", filename)
  6445. def on_file_savegerber(self):
  6446. """
  6447. Callback for menu item in Project context menu.
  6448. :return: None
  6449. """
  6450. self.defaults.report_usage("on_file_savegerber")
  6451. App.log.debug("on_file_savegerber()")
  6452. obj = self.collection.get_active()
  6453. if obj is None:
  6454. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6455. return
  6456. # Check for more compatible types and add as required
  6457. if not isinstance(obj, GerberObject):
  6458. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6459. return
  6460. name = self.collection.get_active().options["name"]
  6461. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6462. try:
  6463. filename, _f = FCFileSaveDialog.get_saved_filename(
  6464. caption="Save Gerber source file",
  6465. directory=self.get_last_save_folder() + '/' + name,
  6466. filter=_filter)
  6467. except TypeError:
  6468. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6469. filename = str(filename)
  6470. if filename == "":
  6471. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6472. return
  6473. else:
  6474. self.save_source_file(name, filename)
  6475. if self.defaults["global_open_style"] is False:
  6476. self.file_opened.emit("Gerber", filename)
  6477. self.file_saved.emit("Gerber", filename)
  6478. def on_file_savescript(self):
  6479. """
  6480. Callback for menu item in Project context menu.
  6481. :return: None
  6482. """
  6483. self.defaults.report_usage("on_file_savescript")
  6484. App.log.debug("on_file_savescript()")
  6485. obj = self.collection.get_active()
  6486. if obj is None:
  6487. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6488. return
  6489. # Check for more compatible types and add as required
  6490. if not isinstance(obj, ScriptObject):
  6491. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6492. return
  6493. name = self.collection.get_active().options["name"]
  6494. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6495. try:
  6496. filename, _f = FCFileSaveDialog.get_saved_filename(
  6497. caption="Save Script source file",
  6498. directory=self.get_last_save_folder() + '/' + name,
  6499. filter=_filter)
  6500. except TypeError:
  6501. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6502. filename = str(filename)
  6503. if filename == "":
  6504. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6505. return
  6506. else:
  6507. self.save_source_file(name, filename)
  6508. if self.defaults["global_open_style"] is False:
  6509. self.file_opened.emit("Script", filename)
  6510. self.file_saved.emit("Script", filename)
  6511. def on_file_savedocument(self):
  6512. """
  6513. Callback for menu item in Project context menu.
  6514. :return: None
  6515. """
  6516. self.defaults.report_usage("on_file_savedocument")
  6517. App.log.debug("on_file_savedocument()")
  6518. obj = self.collection.get_active()
  6519. if obj is None:
  6520. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6521. return
  6522. # Check for more compatible types and add as required
  6523. if not isinstance(obj, ScriptObject):
  6524. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6525. return
  6526. name = self.collection.get_active().options["name"]
  6527. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6528. try:
  6529. filename, _f = FCFileSaveDialog.get_saved_filename(
  6530. caption="Save Document source file",
  6531. directory=self.get_last_save_folder() + '/' + name,
  6532. filter=_filter)
  6533. except TypeError:
  6534. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6535. filename = str(filename)
  6536. if filename == "":
  6537. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6538. return
  6539. else:
  6540. self.save_source_file(name, filename)
  6541. if self.defaults["global_open_style"] is False:
  6542. self.file_opened.emit("Document", filename)
  6543. self.file_saved.emit("Document", filename)
  6544. def on_file_saveexcellon(self):
  6545. """
  6546. Callback for menu item in project context menu.
  6547. :return: None
  6548. """
  6549. self.defaults.report_usage("on_file_saveexcellon")
  6550. App.log.debug("on_file_saveexcellon()")
  6551. obj = self.collection.get_active()
  6552. if obj is None:
  6553. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6554. return
  6555. # Check for more compatible types and add as required
  6556. if not isinstance(obj, ExcellonObject):
  6557. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6558. return
  6559. name = self.collection.get_active().options["name"]
  6560. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6561. try:
  6562. filename, _f = FCFileSaveDialog.get_saved_filename(
  6563. caption=_("Save Excellon source file"),
  6564. directory=self.get_last_save_folder() + '/' + name,
  6565. filter=_filter)
  6566. except TypeError:
  6567. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6568. filename = str(filename)
  6569. if filename == "":
  6570. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6571. return
  6572. else:
  6573. self.save_source_file(name, filename)
  6574. if self.defaults["global_open_style"] is False:
  6575. self.file_opened.emit("Excellon", filename)
  6576. self.file_saved.emit("Excellon", filename)
  6577. def on_file_exportexcellon(self):
  6578. """
  6579. Callback for menu item File->Export->Excellon.
  6580. :return: None
  6581. """
  6582. self.defaults.report_usage("on_file_exportexcellon")
  6583. App.log.debug("on_file_exportexcellon()")
  6584. obj = self.collection.get_active()
  6585. if obj is None:
  6586. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6587. return
  6588. # Check for more compatible types and add as required
  6589. if not isinstance(obj, ExcellonObject):
  6590. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6591. return
  6592. name = self.collection.get_active().options["name"]
  6593. _filter = self.defaults["excellon_save_filters"]
  6594. try:
  6595. filename, _f = FCFileSaveDialog.get_saved_filename(
  6596. caption=_("Export Excellon"),
  6597. directory=self.get_last_save_folder() + '/' + name,
  6598. filter=_filter)
  6599. except TypeError:
  6600. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6601. filename = str(filename)
  6602. if filename == "":
  6603. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6604. return
  6605. else:
  6606. used_extension = filename.rpartition('.')[2]
  6607. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6608. self.export_excellon(name, filename)
  6609. if self.defaults["global_open_style"] is False:
  6610. self.file_opened.emit("Excellon", filename)
  6611. self.file_saved.emit("Excellon", filename)
  6612. def on_file_exportgerber(self):
  6613. """
  6614. Callback for menu item File->Export->Gerber.
  6615. :return: None
  6616. """
  6617. self.defaults.report_usage("on_file_exportgerber")
  6618. App.log.debug("on_file_exportgerber()")
  6619. obj = self.collection.get_active()
  6620. if obj is None:
  6621. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6622. return
  6623. # Check for more compatible types and add as required
  6624. if not isinstance(obj, GerberObject):
  6625. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6626. return
  6627. name = self.collection.get_active().options["name"]
  6628. _filter_ = self.defaults['gerber_save_filters']
  6629. try:
  6630. filename, _f = FCFileSaveDialog.get_saved_filename(
  6631. caption=_("Export Gerber"),
  6632. directory=self.get_last_save_folder() + '/' + name,
  6633. filter=_filter_)
  6634. except TypeError:
  6635. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6636. filename = str(filename)
  6637. if filename == "":
  6638. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6639. return
  6640. else:
  6641. used_extension = filename.rpartition('.')[2]
  6642. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6643. self.export_gerber(name, filename)
  6644. if self.defaults["global_open_style"] is False:
  6645. self.file_opened.emit("Gerber", filename)
  6646. self.file_saved.emit("Gerber", filename)
  6647. def on_file_exportdxf(self):
  6648. """
  6649. Callback for menu item File->Export DXF.
  6650. :return: None
  6651. """
  6652. self.defaults.report_usage("on_file_exportdxf")
  6653. App.log.debug("on_file_exportdxf()")
  6654. obj = self.collection.get_active()
  6655. if obj is None:
  6656. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6657. msg = _("Please Select a Geometry object to export")
  6658. msgbox = QtWidgets.QMessageBox()
  6659. msgbox.setInformativeText(msg)
  6660. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6661. msgbox.setDefaultButton(bt_ok)
  6662. msgbox.exec_()
  6663. return
  6664. # Check for more compatible types and add as required
  6665. if not isinstance(obj, GeometryObject):
  6666. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6667. msgbox = QtWidgets.QMessageBox()
  6668. msgbox.setInformativeText(msg)
  6669. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6670. msgbox.setDefaultButton(bt_ok)
  6671. msgbox.exec_()
  6672. return
  6673. name = self.collection.get_active().options["name"]
  6674. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6675. try:
  6676. filename, _f = FCFileSaveDialog.get_saved_filename(
  6677. caption=_("Export DXF"),
  6678. directory=self.get_last_save_folder() + '/' + name,
  6679. filter=_filter_)
  6680. except TypeError:
  6681. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6682. filename = str(filename)
  6683. if filename == "":
  6684. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6685. return
  6686. else:
  6687. self.export_dxf(name, filename)
  6688. if self.defaults["global_open_style"] is False:
  6689. self.file_opened.emit("DXF", filename)
  6690. self.file_saved.emit("DXF", filename)
  6691. def on_file_importsvg(self, type_of_obj):
  6692. """
  6693. Callback for menu item File->Import SVG.
  6694. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6695. :type type_of_obj: str
  6696. :return: None
  6697. """
  6698. self.defaults.report_usage("on_file_importsvg")
  6699. App.log.debug("on_file_importsvg()")
  6700. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6701. try:
  6702. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6703. directory=self.get_last_folder(), filter=_filter_)
  6704. except TypeError:
  6705. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6706. filter=_filter_)
  6707. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6708. type_of_obj = "geometry"
  6709. filenames = [str(filename) for filename in filenames]
  6710. if len(filenames) == 0:
  6711. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6712. else:
  6713. for filename in filenames:
  6714. if filename != '':
  6715. self.worker_task.emit({'fcn': self.import_svg,
  6716. 'params': [filename, type_of_obj]})
  6717. def on_file_importdxf(self, type_of_obj):
  6718. """
  6719. Callback for menu item File->Import DXF.
  6720. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6721. :type type_of_obj: str
  6722. :return: None
  6723. """
  6724. self.defaults.report_usage("on_file_importdxf")
  6725. App.log.debug("on_file_importdxf()")
  6726. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6727. try:
  6728. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6729. directory=self.get_last_folder(),
  6730. filter=_filter_)
  6731. except TypeError:
  6732. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6733. filter=_filter_)
  6734. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6735. type_of_obj = "geometry"
  6736. filenames = [str(filename) for filename in filenames]
  6737. if len(filenames) == 0:
  6738. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6739. else:
  6740. for filename in filenames:
  6741. if filename != '':
  6742. self.worker_task.emit({'fcn': self.import_dxf,
  6743. 'params': [filename, type_of_obj]})
  6744. # ###############################################################################################################
  6745. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6746. # ###############################################################################################################
  6747. def init_code_editor(self, name):
  6748. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6749. # add the tab if it was closed
  6750. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6751. self.text_editor_tab.setObjectName('text_editor_tab')
  6752. # delete the absolute and relative position and messages in the infobar
  6753. self.ui.position_label.setText("")
  6754. self.ui.rel_position_label.setText("")
  6755. # first clear previous text in text editor (if any)
  6756. self.text_editor_tab.code_editor.clear()
  6757. self.text_editor_tab.code_editor.setReadOnly(False)
  6758. self.toggle_codeeditor = True
  6759. self.text_editor_tab.code_editor.completer_enable = False
  6760. self.text_editor_tab.buttonRun.hide()
  6761. # make sure to keep a reference to the code editor
  6762. self.reference_code_editor = self.text_editor_tab.code_editor
  6763. # Switch plot_area to CNCJob tab
  6764. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6765. def on_view_source(self):
  6766. """
  6767. Called when the user wants to see the source file of the selected object
  6768. :return:
  6769. """
  6770. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6771. self.proc_container.view.set_busy(_("Loading..."))
  6772. try:
  6773. obj = self.collection.get_active()
  6774. except Exception as e:
  6775. log.debug("App.on_view_source() --> %s" % str(e))
  6776. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6777. return 'fail'
  6778. if obj is None:
  6779. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6780. return 'fail'
  6781. flt = "All Files (*.*)"
  6782. if obj.kind == 'gerber':
  6783. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6784. elif obj.kind == 'excellon':
  6785. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6786. elif obj.kind == 'cncjob':
  6787. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6788. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6789. # add the tab if it was closed
  6790. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6791. self.source_editor_tab.setObjectName('source_editor_tab')
  6792. # delete the absolute and relative position and messages in the infobar
  6793. self.ui.position_label.setText("")
  6794. self.ui.rel_position_label.setText("")
  6795. # first clear previous text in text editor (if any)
  6796. self.source_editor_tab.code_editor.clear()
  6797. self.source_editor_tab.code_editor.setReadOnly(False)
  6798. self.source_editor_tab.code_editor.completer_enable = False
  6799. self.source_editor_tab.buttonRun.hide()
  6800. # Switch plot_area to CNCJob tab
  6801. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6802. try:
  6803. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6804. except TypeError:
  6805. pass
  6806. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6807. try:
  6808. self.source_editor_tab.buttonSave.clicked.disconnect()
  6809. except TypeError:
  6810. pass
  6811. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6812. # then append the text from GCode to the text editor
  6813. if obj.kind == 'cncjob':
  6814. try:
  6815. file = obj.export_gcode(
  6816. preamble=self.defaults["cncjob_prepend"],
  6817. postamble=self.defaults["cncjob_append"],
  6818. to_file=True)
  6819. if file == 'fail':
  6820. return 'fail'
  6821. except AttributeError:
  6822. self.inform.emit('[WARNING_NOTCL] %s' %
  6823. _("There is no selected object for which to see it's source file code."))
  6824. return 'fail'
  6825. else:
  6826. try:
  6827. file = StringIO(obj.source_file)
  6828. except (AttributeError, TypeError):
  6829. self.inform.emit('[WARNING_NOTCL] %s' %
  6830. _("There is no selected object for which to see it's source file code."))
  6831. return 'fail'
  6832. self.source_editor_tab.t_frame.hide()
  6833. try:
  6834. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6835. # for line in file:
  6836. # QtWidgets.QApplication.processEvents()
  6837. # proc_line = str(line).strip('\n')
  6838. # self.source_editor_tab.code_editor.append(proc_line)
  6839. except Exception as e:
  6840. log.debug('App.on_view_source() -->%s' % str(e))
  6841. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6842. return
  6843. self.source_editor_tab.handleTextChanged()
  6844. self.source_editor_tab.t_frame.show()
  6845. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6846. self.proc_container.view.set_idle()
  6847. # self.ui.show()
  6848. def on_toggle_code_editor(self):
  6849. self.defaults.report_usage("on_toggle_code_editor()")
  6850. if self.toggle_codeeditor is False:
  6851. self.init_code_editor(name=_("Code Editor"))
  6852. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6853. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6854. self.text_editor_tab.buttonSave.clicked.disconnect()
  6855. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6856. else:
  6857. for idx in range(self.ui.plot_tab_area.count()):
  6858. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6859. self.ui.plot_tab_area.closeTab(idx)
  6860. break
  6861. self.toggle_codeeditor = False
  6862. def on_code_editor_close(self):
  6863. self.toggle_codeeditor = False
  6864. def goto_text_line(self):
  6865. """
  6866. Will scroll a text to the specified text line.
  6867. :return: None
  6868. """
  6869. dia_box = Dialog_box(title=_("Go to Line ..."),
  6870. label=_("Line:"),
  6871. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6872. initial_text='')
  6873. try:
  6874. line = int(dia_box.location) - 1
  6875. except (ValueError, TypeError):
  6876. line = 0
  6877. if dia_box.ok:
  6878. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6879. # at the top of the window
  6880. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6881. # get the document() of the TextEditor
  6882. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6883. # create a Text Cursor based on the searched line
  6884. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6885. # set cursor of the code editor with the cursor at the searcehd line
  6886. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6887. def on_filenewscript(self, silent=False, name=None, text=None):
  6888. """
  6889. Will create a new script file and open it in the Code Editor
  6890. :param silent: if True will not display status messages
  6891. :param name: if specified will be the name of the new script
  6892. :param text: pass a source file to the newly created script to be loaded in it
  6893. :return: None
  6894. """
  6895. if silent is False:
  6896. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6897. # delete the absolute and relative position and messages in the infobar
  6898. self.ui.position_label.setText("")
  6899. self.ui.rel_position_label.setText("")
  6900. if name is not None:
  6901. self.new_script_object(name=name, text=text)
  6902. else:
  6903. self.new_script_object(text=text)
  6904. # script_text = script_obj.source_file
  6905. #
  6906. # self.proc_container.view.set_busy(_("Loading..."))
  6907. # script_obj.script_editor_tab.t_frame.hide()
  6908. #
  6909. # script_obj.script_editor_tab.t_frame.show()
  6910. # self.proc_container.view.set_idle()
  6911. def on_fileopenscript(self, name=None, silent=False):
  6912. """
  6913. Will open a Tcl script file into the Code Editor
  6914. :param silent: if True will not display status messages
  6915. :param name: name of a Tcl script file to open
  6916. :return:
  6917. """
  6918. self.defaults.report_usage("on_fileopenscript")
  6919. App.log.debug("on_fileopenscript()")
  6920. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6921. "All Files (*.*)"
  6922. if name:
  6923. filenames = [name]
  6924. else:
  6925. try:
  6926. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6927. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6928. except TypeError:
  6929. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6930. if len(filenames) == 0:
  6931. if silent is False:
  6932. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6933. else:
  6934. for filename in filenames:
  6935. if filename != '':
  6936. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6937. def on_fileopenscript_example(self, name=None, silent=False):
  6938. """
  6939. Will open a Tcl script file into the Code Editor
  6940. :param silent: if True will not display status messages
  6941. :param name: name of a Tcl script file to open
  6942. :return:
  6943. """
  6944. self.defaults.report_usage("on_fileopenscript_example")
  6945. log.debug("on_fileopenscript_example()")
  6946. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6947. "All Files (*.*)"
  6948. # test if the app was frozen and choose the path for the configuration file
  6949. if getattr(sys, "frozen", False) is True:
  6950. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6951. else:
  6952. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6953. if name:
  6954. filenames = [name]
  6955. else:
  6956. try:
  6957. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6958. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6959. except TypeError:
  6960. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6961. if len(filenames) == 0:
  6962. if silent is False:
  6963. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6964. else:
  6965. for filename in filenames:
  6966. if filename != '':
  6967. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6968. def on_filerunscript(self, name=None, silent=False):
  6969. """
  6970. File menu callback for loading and running a TCL script.
  6971. :param silent: if True will not display status messages
  6972. :param name: name of a Tcl script file to be run by FlatCAM
  6973. :return: None
  6974. """
  6975. self.defaults.report_usage("on_filerunscript")
  6976. App.log.debug("on_file_runscript()")
  6977. if name:
  6978. filename = name
  6979. if self.cmd_line_headless != 1:
  6980. self.splash.showMessage('%s: %ssec\n%s' %
  6981. (_("Canvas initialization started.\n"
  6982. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6983. _("Executing ScriptObject file.")
  6984. ),
  6985. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6986. color=QtGui.QColor("gray"))
  6987. else:
  6988. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6989. "All Files (*.*)"
  6990. try:
  6991. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6992. directory=self.get_last_folder(), filter=_filter_)
  6993. except TypeError:
  6994. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6995. # The Qt methods above will return a QString which can cause problems later.
  6996. # So far json.dump() will fail to serialize it.
  6997. filename = str(filename)
  6998. if filename == "":
  6999. if silent is False:
  7000. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7001. else:
  7002. if self.cmd_line_headless != 1:
  7003. if self.ui.shell_dock.isHidden():
  7004. self.ui.shell_dock.show()
  7005. try:
  7006. with open(filename, "r") as tcl_script:
  7007. cmd_line_shellfile_content = tcl_script.read()
  7008. if self.cmd_line_headless != 1:
  7009. self.shell.exec_command(cmd_line_shellfile_content)
  7010. else:
  7011. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7012. if silent is False:
  7013. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7014. except Exception as e:
  7015. log.debug("App.on_filerunscript() -> %s" % str(e))
  7016. sys.exit(2)
  7017. def on_file_saveproject(self, silent=False):
  7018. """
  7019. Callback for menu item File->Save Project. Saves the project to
  7020. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7021. if set to None. The project is saved by calling ``self.save_project()``.
  7022. :param silent: if True will not display status messages
  7023. :return: None
  7024. """
  7025. self.defaults.report_usage("on_file_saveproject")
  7026. if self.project_filename is None:
  7027. self.on_file_saveprojectas()
  7028. else:
  7029. self.worker_task.emit({'fcn': self.save_project,
  7030. 'params': [self.project_filename, silent]})
  7031. if self.defaults["global_open_style"] is False:
  7032. self.file_opened.emit("project", self.project_filename)
  7033. self.file_saved.emit("project", self.project_filename)
  7034. self.set_ui_title(name=self.project_filename)
  7035. self.should_we_save = False
  7036. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7037. """
  7038. Callback for menu item File->Save Project As... Opens a file
  7039. chooser and saves the project to the given file via
  7040. ``self.save_project()``.
  7041. :param make_copy if to be create a copy of the project; boolean
  7042. :param use_thread: if to be run in a separate thread; boolean
  7043. :param quit_action: if to be followed by quiting the application; boolean
  7044. :return: None
  7045. """
  7046. self.defaults.report_usage("on_file_saveprojectas")
  7047. self.date = str(datetime.today()).rpartition('.')[0]
  7048. self.date = ''.join(c for c in self.date if c not in ':-')
  7049. self.date = self.date.replace(' ', '_')
  7050. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7051. try:
  7052. filename, _f = FCFileSaveDialog.get_saved_filename(
  7053. caption=_("Save Project As ..."),
  7054. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  7055. proj=_("Project")),
  7056. filter=filter_
  7057. )
  7058. except TypeError:
  7059. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  7060. filename = str(filename)
  7061. if filename == '':
  7062. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7063. return
  7064. if use_thread is True:
  7065. self.worker_task.emit({'fcn': self.save_project,
  7066. 'params': [filename, quit_action]})
  7067. else:
  7068. self.save_project(filename, quit_action)
  7069. # self.save_project(filename)
  7070. if self.defaults["global_open_style"] is False:
  7071. self.file_opened.emit("project", filename)
  7072. self.file_saved.emit("project", filename)
  7073. if not make_copy:
  7074. self.project_filename = filename
  7075. self.set_ui_title(name=self.project_filename)
  7076. self.should_we_save = False
  7077. def on_file_save_objects_pdf(self, use_thread=True):
  7078. self.date = str(datetime.today()).rpartition('.')[0]
  7079. self.date = ''.join(c for c in self.date if c not in ':-')
  7080. self.date = self.date.replace(' ', '_')
  7081. try:
  7082. obj_selection = self.collection.get_selected()
  7083. if len(obj_selection) == 1:
  7084. obj_name = str(obj_selection[0].options['name'])
  7085. else:
  7086. obj_name = _("FlatCAM objects print")
  7087. except AttributeError as err:
  7088. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7089. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7090. return
  7091. if not obj_selection:
  7092. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7093. return
  7094. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7095. try:
  7096. filename, _f = FCFileSaveDialog.get_saved_filename(
  7097. caption=_("Save Object as PDF ..."),
  7098. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7099. obj_name=obj_name,
  7100. date=self.date),
  7101. filter=filter_
  7102. )
  7103. except TypeError:
  7104. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7105. filename = str(filename)
  7106. if filename == '':
  7107. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7108. return
  7109. if use_thread is True:
  7110. self.proc_container.new(_("Printing PDF ... Please wait."))
  7111. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7112. else:
  7113. self.save_pdf(filename, obj_selection)
  7114. # self.save_project(filename)
  7115. if self.defaults["global_open_style"] is False:
  7116. self.file_opened.emit("pdf", filename)
  7117. self.file_saved.emit("pdf", filename)
  7118. def save_pdf(self, file_name, obj_selection):
  7119. p_size = self.defaults['global_workspaceT']
  7120. orientation = self.defaults['global_workspace_orientation']
  7121. color = 'black'
  7122. transparency_level = 1.0
  7123. self.pagesize = {}
  7124. self.pagesize.update(
  7125. {
  7126. 'Bounds': None,
  7127. 'A0': (841 * mm, 1189 * mm),
  7128. 'A1': (594 * mm, 841 * mm),
  7129. 'A2': (420 * mm, 594 * mm),
  7130. 'A3': (297 * mm, 420 * mm),
  7131. 'A4': (210 * mm, 297 * mm),
  7132. 'A5': (148 * mm, 210 * mm),
  7133. 'A6': (105 * mm, 148 * mm),
  7134. 'A7': (74 * mm, 105 * mm),
  7135. 'A8': (52 * mm, 74 * mm),
  7136. 'A9': (37 * mm, 52 * mm),
  7137. 'A10': (26 * mm, 37 * mm),
  7138. 'B0': (1000 * mm, 1414 * mm),
  7139. 'B1': (707 * mm, 1000 * mm),
  7140. 'B2': (500 * mm, 707 * mm),
  7141. 'B3': (353 * mm, 500 * mm),
  7142. 'B4': (250 * mm, 353 * mm),
  7143. 'B5': (176 * mm, 250 * mm),
  7144. 'B6': (125 * mm, 176 * mm),
  7145. 'B7': (88 * mm, 125 * mm),
  7146. 'B8': (62 * mm, 88 * mm),
  7147. 'B9': (44 * mm, 62 * mm),
  7148. 'B10': (31 * mm, 44 * mm),
  7149. 'C0': (917 * mm, 1297 * mm),
  7150. 'C1': (648 * mm, 917 * mm),
  7151. 'C2': (458 * mm, 648 * mm),
  7152. 'C3': (324 * mm, 458 * mm),
  7153. 'C4': (229 * mm, 324 * mm),
  7154. 'C5': (162 * mm, 229 * mm),
  7155. 'C6': (114 * mm, 162 * mm),
  7156. 'C7': (81 * mm, 114 * mm),
  7157. 'C8': (57 * mm, 81 * mm),
  7158. 'C9': (40 * mm, 57 * mm),
  7159. 'C10': (28 * mm, 40 * mm),
  7160. # American paper sizes
  7161. 'LETTER': (8.5 * inch, 11 * inch),
  7162. 'LEGAL': (8.5 * inch, 14 * inch),
  7163. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7164. # From https://en.wikipedia.org/wiki/Paper_size
  7165. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7166. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7167. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7168. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7169. 'LEDGER': (17 * inch, 11 * inch),
  7170. }
  7171. )
  7172. exported_svg = []
  7173. for obj in obj_selection:
  7174. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7175. scale_factor_x=None, scale_factor_y=None,
  7176. skew_factor_x=None, skew_factor_y=None,
  7177. mirror=None)
  7178. if obj.kind.lower() == 'gerber':
  7179. # color = self.defaults["gerber_plot_fill"][:-2]
  7180. color = obj.fill_color[:-2]
  7181. elif obj.kind.lower() == 'excellon':
  7182. color = '#C40000'
  7183. elif obj.kind.lower() == 'geometry':
  7184. color = self.defaults["global_draw_color"]
  7185. # Change the attributes of the exported SVG
  7186. # We don't need stroke-width
  7187. # We set opacity to maximum
  7188. # We set the colour to WHITE
  7189. root = ET.fromstring(svg_obj)
  7190. for child in root:
  7191. child.set('fill', str(color))
  7192. child.set('opacity', str(transparency_level))
  7193. child.set('stroke', str(color))
  7194. exported_svg.append(ET.tostring(root))
  7195. xmin = Inf
  7196. ymin = Inf
  7197. xmax = -Inf
  7198. ymax = -Inf
  7199. for obj in obj_selection:
  7200. try:
  7201. gxmin, gymin, gxmax, gymax = obj.bounds()
  7202. xmin = min([xmin, gxmin])
  7203. ymin = min([ymin, gymin])
  7204. xmax = max([xmax, gxmax])
  7205. ymax = max([ymax, gymax])
  7206. except Exception as e:
  7207. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7208. # Determine bounding area for svg export
  7209. bounds = [xmin, ymin, xmax, ymax]
  7210. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7211. # This contain the measure units
  7212. uom = obj_selection[0].units.lower()
  7213. # Define a boundary around SVG of about 1.0mm (~39mils)
  7214. if uom in "mm":
  7215. boundary = 1.0
  7216. else:
  7217. boundary = 0.0393701
  7218. # Convert everything to strings for use in the xml doc
  7219. svgwidth = str(size[0] + (2 * boundary))
  7220. svgheight = str(size[1] + (2 * boundary))
  7221. minx = str(bounds[0] - boundary)
  7222. miny = str(bounds[1] + boundary + size[1])
  7223. # Add a SVG Header and footer to the svg output from shapely
  7224. # The transform flips the Y Axis so that everything renders
  7225. # properly within svg apps such as inkscape
  7226. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7227. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7228. svg_header += 'width="' + svgwidth + uom + '" '
  7229. svg_header += 'height="' + svgheight + uom + '" '
  7230. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7231. svg_header += '>'
  7232. svg_header += '<g transform="scale(1,-1)">'
  7233. svg_footer = '</g> </svg>'
  7234. svg_elem = str(svg_header)
  7235. for svg_item in exported_svg:
  7236. svg_elem += str(svg_item)
  7237. svg_elem += str(svg_footer)
  7238. # Parse the xml through a xml parser just to add line feeds
  7239. # and to make it look more pretty for the output
  7240. doc = parse_xml_string(svg_elem)
  7241. doc_final = doc.toprettyxml()
  7242. try:
  7243. if self.defaults['units'].upper() == 'IN':
  7244. unit = inch
  7245. else:
  7246. unit = mm
  7247. doc_final = StringIO(doc_final)
  7248. drawing = svg2rlg(doc_final)
  7249. if p_size == 'Bounds':
  7250. renderPDF.drawToFile(drawing, file_name)
  7251. else:
  7252. if orientation == 'p':
  7253. page_size = portrait(self.pagesize[p_size])
  7254. else:
  7255. page_size = landscape(self.pagesize[p_size])
  7256. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7257. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7258. renderPDF.draw(drawing, my_canvas, 0, 0)
  7259. my_canvas.save()
  7260. except Exception as e:
  7261. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7262. return 'fail'
  7263. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7264. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7265. """
  7266. Exports a Geometry Object to an SVG file.
  7267. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7268. :param filename: Path to the SVG file to save to.
  7269. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7270. :return:
  7271. """
  7272. self.defaults.report_usage("export_svg()")
  7273. if filename is None:
  7274. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7275. is not None else self.defaults["global_last_folder"]
  7276. self.log.debug("export_svg()")
  7277. try:
  7278. obj = self.collection.get_by_name(str(obj_name))
  7279. except Exception:
  7280. # TODO: The return behavior has not been established... should raise exception?
  7281. return "Could not retrieve object: %s" % obj_name
  7282. with self.proc_container.new(_("Exporting SVG")) as proc:
  7283. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7284. # Determine bounding area for svg export
  7285. bounds = obj.bounds()
  7286. size = obj.size()
  7287. # Convert everything to strings for use in the xml doc
  7288. svgwidth = str(size[0])
  7289. svgheight = str(size[1])
  7290. minx = str(bounds[0])
  7291. miny = str(bounds[1] - size[1])
  7292. uom = obj.units.lower()
  7293. # Add a SVG Header and footer to the svg output from shapely
  7294. # The transform flips the Y Axis so that everything renders
  7295. # properly within svg apps such as inkscape
  7296. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7297. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7298. svg_header += 'width="' + svgwidth + uom + '" '
  7299. svg_header += 'height="' + svgheight + uom + '" '
  7300. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7301. svg_header += '<g transform="scale(1,-1)">'
  7302. svg_footer = '</g> </svg>'
  7303. svg_elem = svg_header + exported_svg + svg_footer
  7304. # Parse the xml through a xml parser just to add line feeds
  7305. # and to make it look more pretty for the output
  7306. svgcode = parse_xml_string(svg_elem)
  7307. svgcode = svgcode.toprettyxml()
  7308. try:
  7309. with open(filename, 'w') as fp:
  7310. fp.write(svgcode)
  7311. except PermissionError:
  7312. self.inform.emit('[WARNING] %s' %
  7313. _("Permission denied, saving not possible.\n"
  7314. "Most likely another app is holding the file open and not accessible."))
  7315. return 'fail'
  7316. if self.defaults["global_open_style"] is False:
  7317. self.file_opened.emit("SVG", filename)
  7318. self.file_saved.emit("SVG", filename)
  7319. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7320. def save_source_file(self, obj_name, filename, use_thread=True):
  7321. """
  7322. Exports a FlatCAM Object to an Gerber/Excellon file.
  7323. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7324. :param filename: Path to the Gerber file to save to.
  7325. :param use_thread: if to be run in a separate thread
  7326. :return:
  7327. """
  7328. self.defaults.report_usage("save source file()")
  7329. if filename is None:
  7330. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7331. is not None else self.defaults["global_last_folder"]
  7332. self.log.debug("save source file()")
  7333. obj = self.collection.get_by_name(obj_name)
  7334. file_string = StringIO(obj.source_file)
  7335. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7336. if file_string.getvalue() == '':
  7337. self.inform.emit('[ERROR_NOTCL] %s' %
  7338. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7339. return 'fail'
  7340. try:
  7341. with open(filename, 'w') as file:
  7342. file.writelines('G04*\n')
  7343. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7344. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7345. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7346. file.writelines('G04 Created on : %s*\n' % time_string)
  7347. for line in file_string:
  7348. file.writelines(line)
  7349. except PermissionError:
  7350. self.inform.emit('[WARNING] %s' %
  7351. _("Permission denied, saving not possible.\n"
  7352. "Most likely another app is holding the file open and not accessible."))
  7353. return 'fail'
  7354. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7355. """
  7356. Exports a Excellon Object to an Excellon file.
  7357. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7358. :param filename: Path to the Excellon file to save to.
  7359. :param local_use:
  7360. :param use_thread: if to be run in a separate thread
  7361. :return:
  7362. """
  7363. self.defaults.report_usage("export_excellon()")
  7364. if filename is None:
  7365. if self.defaults["global_last_save_folder"]:
  7366. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7367. else:
  7368. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7369. self.log.debug("export_excellon()")
  7370. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7371. self.defaults["excellon_exp_decimals"]
  7372. )
  7373. if local_use is None:
  7374. try:
  7375. obj = self.collection.get_by_name(str(obj_name))
  7376. except Exception:
  7377. return "Could not retrieve object: %s" % obj_name
  7378. else:
  7379. obj = local_use
  7380. if not isinstance(obj, ExcellonObject):
  7381. self.inform.emit('[ERROR_NOTCL] %s' %
  7382. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7383. return
  7384. # updated units
  7385. eunits = self.defaults["excellon_exp_units"]
  7386. ewhole = self.defaults["excellon_exp_integer"]
  7387. efract = self.defaults["excellon_exp_decimals"]
  7388. ezeros = self.defaults["excellon_exp_zeros"]
  7389. eformat = self.defaults["excellon_exp_format"]
  7390. slot_type = self.defaults["excellon_exp_slot_type"]
  7391. fc_units = self.defaults['units'].upper()
  7392. if fc_units == 'MM':
  7393. factor = 1 if eunits == 'METRIC' else 0.03937
  7394. else:
  7395. factor = 25.4 if eunits == 'METRIC' else 1
  7396. def make_excellon():
  7397. try:
  7398. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7399. header = 'M48\n'
  7400. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7401. (str(self.version), str(self.version_date))
  7402. header += ';Filename: %s' % str(obj_name) + '\n'
  7403. header += ';Created on : %s' % time_str + '\n'
  7404. if eformat == 'dec':
  7405. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7406. header += eunits + '\n'
  7407. for tool in obj.tools:
  7408. if eunits == 'METRIC':
  7409. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7410. tool=str(tool),
  7411. dec=2)
  7412. else:
  7413. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7414. tool=str(tool),
  7415. dec=4)
  7416. else:
  7417. if ezeros == 'LZ':
  7418. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7419. form='ndec', e_zeros='LZ', factor=factor,
  7420. slot_type=slot_type)
  7421. header += '%s,%s\n' % (eunits, 'LZ')
  7422. header += format_exc
  7423. for tool in obj.tools:
  7424. if eunits == 'METRIC':
  7425. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7426. tool=str(tool),
  7427. dec=2)
  7428. else:
  7429. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7430. tool=str(tool),
  7431. dec=4)
  7432. else:
  7433. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7434. form='ndec', e_zeros='TZ', factor=factor,
  7435. slot_type=slot_type)
  7436. header += '%s,%s\n' % (eunits, 'TZ')
  7437. header += format_exc
  7438. for tool in obj.tools:
  7439. if eunits == 'METRIC':
  7440. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7441. tool=str(tool),
  7442. dec=2)
  7443. else:
  7444. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7445. tool=str(tool),
  7446. dec=4)
  7447. header += '%\n'
  7448. footer = 'M30\n'
  7449. exported_excellon = header
  7450. exported_excellon += excellon_code
  7451. exported_excellon += footer
  7452. if local_use is None:
  7453. try:
  7454. with open(filename, 'w') as fp:
  7455. fp.write(exported_excellon)
  7456. except PermissionError:
  7457. self.inform.emit('[WARNING] %s' %
  7458. _("Permission denied, saving not possible.\n"
  7459. "Most likely another app is holding the file open and not accessible."))
  7460. return 'fail'
  7461. if self.defaults["global_open_style"] is False:
  7462. self.file_opened.emit("Excellon", filename)
  7463. self.file_saved.emit("Excellon", filename)
  7464. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7465. else:
  7466. return exported_excellon
  7467. except Exception as e:
  7468. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7469. return 'fail'
  7470. if use_thread is True:
  7471. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7472. def job_thread_exc(app_obj):
  7473. ret = make_excellon()
  7474. if ret == 'fail':
  7475. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7476. return
  7477. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7478. else:
  7479. eret = make_excellon()
  7480. if eret == 'fail':
  7481. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7482. return 'fail'
  7483. if local_use is not None:
  7484. return eret
  7485. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7486. """
  7487. Exports a Gerber Object to an Gerber file.
  7488. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7489. :param filename: Path to the Gerber file to save to.
  7490. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7491. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7492. :param use_thread: if to be run in a separate thread
  7493. :return:
  7494. """
  7495. self.defaults.report_usage("export_gerber()")
  7496. if filename is None:
  7497. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7498. is not None else self.defaults["global_last_folder"]
  7499. self.log.debug("export_gerber()")
  7500. if local_use is None:
  7501. try:
  7502. obj = self.collection.get_by_name(str(obj_name))
  7503. except Exception:
  7504. return "Could not retrieve object: %s" % obj_name
  7505. else:
  7506. obj = local_use
  7507. # updated units
  7508. gunits = self.defaults["gerber_exp_units"]
  7509. gwhole = self.defaults["gerber_exp_integer"]
  7510. gfract = self.defaults["gerber_exp_decimals"]
  7511. gzeros = self.defaults["gerber_exp_zeros"]
  7512. fc_units = self.defaults['units'].upper()
  7513. if fc_units == 'MM':
  7514. factor = 1 if gunits == 'MM' else 0.03937
  7515. else:
  7516. factor = 25.4 if gunits == 'MM' else 1
  7517. def make_gerber():
  7518. try:
  7519. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7520. header = 'G04*\n'
  7521. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7522. (str(self.version), str(self.version_date))
  7523. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7524. header += 'G04 Created on : %s*' % time_str + '\n'
  7525. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7526. header += "%MO{units}*%\n".format(units=gunits)
  7527. for apid in obj.apertures:
  7528. if obj.apertures[apid]['type'] == 'C':
  7529. header += "%ADD{apid}{type},{size}*%\n".format(
  7530. apid=str(apid),
  7531. type='C',
  7532. size=(factor * obj.apertures[apid]['size'])
  7533. )
  7534. elif obj.apertures[apid]['type'] == 'R':
  7535. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7536. apid=str(apid),
  7537. type='R',
  7538. width=(factor * obj.apertures[apid]['width']),
  7539. height=(factor * obj.apertures[apid]['height'])
  7540. )
  7541. elif obj.apertures[apid]['type'] == 'O':
  7542. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7543. apid=str(apid),
  7544. type='O',
  7545. width=(factor * obj.apertures[apid]['width']),
  7546. height=(factor * obj.apertures[apid]['height'])
  7547. )
  7548. header += '\n'
  7549. # obsolete units but some software may need it
  7550. if gunits == 'IN':
  7551. header += 'G70*\n'
  7552. else:
  7553. header += 'G71*\n'
  7554. # Absolute Mode
  7555. header += 'G90*\n'
  7556. header += 'G01*\n'
  7557. # positive polarity
  7558. header += '%LPD*%\n'
  7559. footer = 'M02*\n'
  7560. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7561. exported_gerber = header
  7562. exported_gerber += gerber_code
  7563. exported_gerber += footer
  7564. if local_use is None:
  7565. try:
  7566. with open(filename, 'w') as fp:
  7567. fp.write(exported_gerber)
  7568. except PermissionError:
  7569. self.inform.emit('[WARNING] %s' %
  7570. _("Permission denied, saving not possible.\n"
  7571. "Most likely another app is holding the file open and not accessible."))
  7572. return 'fail'
  7573. if self.defaults["global_open_style"] is False:
  7574. self.file_opened.emit("Gerber", filename)
  7575. self.file_saved.emit("Gerber", filename)
  7576. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7577. else:
  7578. return exported_gerber
  7579. except Exception as e:
  7580. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7581. return 'fail'
  7582. if use_thread is True:
  7583. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7584. def job_thread_grb(app_obj):
  7585. ret = make_gerber()
  7586. if ret == 'fail':
  7587. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7588. return
  7589. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7590. else:
  7591. gret = make_gerber()
  7592. if gret == 'fail':
  7593. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7594. return 'fail'
  7595. if local_use is not None:
  7596. return gret
  7597. def export_dxf(self, obj_name, filename, use_thread=True):
  7598. """
  7599. Exports a Geometry Object to an DXF file.
  7600. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7601. :param filename: Path to the DXF file to save to.
  7602. :param use_thread: if to be run in a separate thread
  7603. :return:
  7604. """
  7605. self.defaults.report_usage("export_dxf()")
  7606. if filename is None:
  7607. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7608. is not None else self.defaults["global_last_folder"]
  7609. self.log.debug("export_dxf()")
  7610. try:
  7611. obj = self.collection.get_by_name(str(obj_name))
  7612. except Exception:
  7613. # TODO: The return behavior has not been established... should raise exception?
  7614. return "Could not retrieve object: %s" % obj_name
  7615. def make_dxf():
  7616. try:
  7617. dxf_code = obj.export_dxf()
  7618. dxf_code.saveas(filename)
  7619. if self.defaults["global_open_style"] is False:
  7620. self.file_opened.emit("DXF", filename)
  7621. self.file_saved.emit("DXF", filename)
  7622. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7623. except Exception:
  7624. return 'fail'
  7625. if use_thread is True:
  7626. with self.proc_container.new(_("Exporting DXF")) as proc:
  7627. def job_thread_exc(app_obj):
  7628. ret_dxf_val = make_dxf()
  7629. if ret_dxf_val == 'fail':
  7630. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7631. return
  7632. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7633. else:
  7634. ret = make_dxf()
  7635. if ret == 'fail':
  7636. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7637. return
  7638. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7639. """
  7640. Adds a new Geometry Object to the projects and populates
  7641. it with shapes extracted from the SVG file.
  7642. :param plot: If True then the resulting object will be plotted on canvas
  7643. :param filename: Path to the SVG file.
  7644. :param geo_type: Type of FlatCAM object that will be created from SVG
  7645. :param outname: The name given to the resulting FlatCAM object
  7646. :return:
  7647. """
  7648. self.defaults.report_usage("import_svg()")
  7649. log.debug("App.import_svg()")
  7650. obj_type = ""
  7651. if geo_type is None or geo_type == "geometry":
  7652. obj_type = "geometry"
  7653. elif geo_type == "gerber":
  7654. obj_type = "gerber"
  7655. else:
  7656. self.inform.emit('[ERROR_NOTCL] %s' %
  7657. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7658. return
  7659. units = self.defaults['units'].upper()
  7660. def obj_init(geo_obj, app_obj):
  7661. geo_obj.import_svg(filename, obj_type, units=units)
  7662. geo_obj.multigeo = False
  7663. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7664. with self.proc_container.new(_("Importing SVG")) as proc:
  7665. # Object name
  7666. name = outname or filename.split('/')[-1].split('\\')[-1]
  7667. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7668. if ret == 'fail':
  7669. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7670. return 'fail'
  7671. # Register recent file
  7672. self.file_opened.emit("svg", filename)
  7673. # GUI feedback
  7674. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7675. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7676. """
  7677. Adds a new Geometry Object to the projects and populates
  7678. it with shapes extracted from the DXF file.
  7679. :param filename: Path to the DXF file.
  7680. :param geo_type: Type of FlatCAM object that will be created from DXF
  7681. :param outname: Name for the imported Geometry
  7682. :param plot: If True then the resulting object will be plotted on canvas
  7683. :return:
  7684. """
  7685. self.defaults.report_usage("import_dxf()")
  7686. obj_type = ""
  7687. if geo_type is None or geo_type == "geometry":
  7688. obj_type = "geometry"
  7689. elif geo_type == "gerber":
  7690. obj_type = geo_type
  7691. else:
  7692. self.inform.emit('[ERROR_NOTCL] %s' %
  7693. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7694. return
  7695. units = self.defaults['units'].upper()
  7696. def obj_init(geo_obj, app_obj):
  7697. geo_obj.import_dxf(filename, obj_type, units=units)
  7698. geo_obj.multigeo = False
  7699. with self.proc_container.new(_("Importing DXF")):
  7700. # Object name
  7701. name = outname or filename.split('/')[-1].split('\\')[-1]
  7702. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7703. if ret == 'fail':
  7704. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7705. return 'fail'
  7706. # Register recent file
  7707. self.file_opened.emit("dxf", filename)
  7708. # GUI feedback
  7709. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7710. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7711. """
  7712. Opens a Gerber file, parses it and creates a new object for
  7713. it in the program. Thread-safe.
  7714. :param outname: Name of the resulting object. None causes the
  7715. name to be that of the file. Str.
  7716. :param filename: Gerber file filename
  7717. :type filename: str
  7718. :param plot: boolean, to plot or not the resulting object
  7719. :param from_tcl: True if run from Tcl Shell
  7720. :return: None
  7721. """
  7722. # How the object should be initialized
  7723. def obj_init(gerber_obj, app_obj):
  7724. assert isinstance(gerber_obj, GerberObject), \
  7725. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7726. # Opening the file happens here
  7727. try:
  7728. gerber_obj.parse_file(filename)
  7729. except IOError:
  7730. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7731. return "fail"
  7732. except ParseError as err:
  7733. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7734. app_obj.log.error(str(err))
  7735. return "fail"
  7736. except Exception as e:
  7737. log.debug("App.open_gerber() --> %s" % str(e))
  7738. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7739. msg += traceback.format_exc()
  7740. app_obj.inform.emit(msg)
  7741. return "fail"
  7742. if gerber_obj.is_empty():
  7743. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7744. _("Object is not Gerber file or empty. Aborting object creation."))
  7745. return "fail"
  7746. App.log.debug("open_gerber()")
  7747. with self.proc_container.new(_("Opening Gerber")):
  7748. # Object name
  7749. name = outname or filename.split('/')[-1].split('\\')[-1]
  7750. # # ## Object creation # ##
  7751. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7752. if ret_val == 'fail':
  7753. if from_tcl:
  7754. filename = self.defaults['global_tcl_path'] + '/' + name
  7755. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7756. if ret_val == 'fail':
  7757. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7758. return 'fail'
  7759. # Register recent file
  7760. self.file_opened.emit("gerber", filename)
  7761. # GUI feedback
  7762. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7763. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7764. """
  7765. Opens an Excellon file, parses it and creates a new object for
  7766. it in the program. Thread-safe.
  7767. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7768. :param filename: Excellon file filename
  7769. :type filename: str
  7770. :param plot: boolean, to plot or not the resulting object
  7771. :param from_tcl: True if run from Tcl Shell
  7772. :return: None
  7773. """
  7774. App.log.debug("open_excellon()")
  7775. # How the object should be initialized
  7776. def obj_init(excellon_obj, app_obj):
  7777. try:
  7778. ret = excellon_obj.parse_file(filename=filename)
  7779. if ret == "fail":
  7780. log.debug("Excellon parsing failed.")
  7781. self.inform.emit('[ERROR_NOTCL] %s' %
  7782. _("This is not Excellon file."))
  7783. return "fail"
  7784. except IOError:
  7785. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7786. (_("Cannot open file"), filename))
  7787. log.debug("Could not open Excellon object.")
  7788. return "fail"
  7789. except Exception:
  7790. msg = '[ERROR_NOTCL] %s' % \
  7791. _("An internal error has occurred. See shell.\n")
  7792. msg += traceback.format_exc()
  7793. app_obj.inform.emit(msg)
  7794. return "fail"
  7795. ret = excellon_obj.create_geometry()
  7796. if ret == 'fail':
  7797. log.debug("Could not create geometry for Excellon object.")
  7798. return "fail"
  7799. for tool in excellon_obj.tools:
  7800. if excellon_obj.tools[tool]['solid_geometry']:
  7801. return
  7802. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7803. return "fail"
  7804. with self.proc_container.new(_("Opening Excellon.")):
  7805. # Object name
  7806. name = outname or filename.split('/')[-1].split('\\')[-1]
  7807. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7808. if ret_val == 'fail':
  7809. if from_tcl:
  7810. filename = self.defaults['global_tcl_path'] + '/' + name
  7811. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7812. if ret_val == 'fail':
  7813. self.inform.emit('[ERROR_NOTCL] %s' %
  7814. _('Open Excellon file failed. Probable not an Excellon file.'))
  7815. return
  7816. # Register recent file
  7817. self.file_opened.emit("excellon", filename)
  7818. # GUI feedback
  7819. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7820. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7821. """
  7822. Opens a G-gcode file, parses it and creates a new object for
  7823. it in the program. Thread-safe.
  7824. :param filename: G-code file filename
  7825. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7826. :param force_parsing:
  7827. :param plot: If True plot the object on canvas
  7828. :param from_tcl: True if run from Tcl Shell
  7829. :return: None
  7830. """
  7831. App.log.debug("open_gcode()")
  7832. # How the object should be initialized
  7833. def obj_init(job_obj, app_obj_):
  7834. """
  7835. :param job_obj: the resulting object
  7836. :type app_obj_: App
  7837. """
  7838. assert isinstance(app_obj_, App), \
  7839. "Initializer expected App, got %s" % type(app_obj_)
  7840. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7841. try:
  7842. f = open(filename)
  7843. gcode = f.read()
  7844. f.close()
  7845. except IOError:
  7846. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7847. return "fail"
  7848. job_obj.gcode = gcode
  7849. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7850. if gcode_ret == "fail":
  7851. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7852. return "fail"
  7853. job_obj.create_geometry()
  7854. with self.proc_container.new(_("Opening G-Code.")):
  7855. # Object name
  7856. name = outname or filename.split('/')[-1].split('\\')[-1]
  7857. # New object creation and file processing
  7858. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7859. if ret_val == 'fail':
  7860. if from_tcl:
  7861. filename = self.defaults['global_tcl_path'] + '/' + name
  7862. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7863. if ret_val == 'fail':
  7864. self.inform.emit('[ERROR_NOTCL] %s' %
  7865. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7866. "Try to load it from File menu.\n "
  7867. "Attempting to create a FlatCAM CNCJob Object from "
  7868. "G-Code file failed during processing"))
  7869. return "fail"
  7870. # Register recent file
  7871. self.file_opened.emit("cncjob", filename)
  7872. # GUI feedback
  7873. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7874. def open_hpgl2(self, filename, outname=None):
  7875. """
  7876. Opens a HPGL2 file, parses it and creates a new object for
  7877. it in the program. Thread-safe.
  7878. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7879. :param filename: HPGL2 file filename
  7880. :return: None
  7881. """
  7882. filename = filename
  7883. # How the object should be initialized
  7884. def obj_init(geo_obj, app_obj):
  7885. assert isinstance(geo_obj, GeometryObject), \
  7886. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7887. # Opening the file happens here
  7888. obj = HPGL2(self)
  7889. try:
  7890. HPGL2.parse_file(obj, filename)
  7891. except IOError:
  7892. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7893. return "fail"
  7894. except ParseError as err:
  7895. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7896. app_obj.log.error(str(err))
  7897. return "fail"
  7898. except Exception as e:
  7899. log.debug("App.open_hpgl2() --> %s" % str(e))
  7900. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7901. msg += traceback.format_exc()
  7902. app_obj.inform.emit(msg)
  7903. return "fail"
  7904. geo_obj.multigeo = True
  7905. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7906. geo_obj.tools = deepcopy(obj.tools)
  7907. geo_obj.source_file = deepcopy(obj.source_file)
  7908. del obj
  7909. if not geo_obj.solid_geometry:
  7910. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7911. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7912. return "fail"
  7913. App.log.debug("open_hpgl2()")
  7914. with self.proc_container.new(_("Opening HPGL2")):
  7915. # Object name
  7916. name = outname or filename.split('/')[-1].split('\\')[-1]
  7917. # # ## Object creation # ##
  7918. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7919. if ret == 'fail':
  7920. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7921. return 'fail'
  7922. # Register recent file
  7923. self.file_opened.emit("geometry", filename)
  7924. # GUI feedback
  7925. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7926. def open_script(self, filename, outname=None, silent=False):
  7927. """
  7928. Opens a Script file, parses it and creates a new object for
  7929. it in the program. Thread-safe.
  7930. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7931. :param filename: Script file filename
  7932. :param silent: If True there will be no messages printed to StatusBar
  7933. :return: None
  7934. """
  7935. App.log.debug("open_script()")
  7936. with self.proc_container.new(_("Opening TCL Script...")):
  7937. try:
  7938. with open(filename, "r") as opened_script:
  7939. script_content = opened_script.readlines()
  7940. script_content = ''.join(script_content)
  7941. if silent is False:
  7942. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7943. except Exception as e:
  7944. log.debug("App.open_script() -> %s" % str(e))
  7945. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  7946. return
  7947. # Object name
  7948. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7949. # New object creation and file processing
  7950. self.on_filenewscript(name=script_name, text=script_content)
  7951. # Register recent file
  7952. self.file_opened.emit("script", filename)
  7953. # GUI feedback
  7954. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7955. def open_config_file(self, filename, run_from_arg=None):
  7956. """
  7957. Loads a config file from the specified file.
  7958. :param filename: Name of the file from which to load.
  7959. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7960. :return: None
  7961. """
  7962. App.log.debug("Opening config file: " + filename)
  7963. if run_from_arg:
  7964. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7965. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7966. _("Opening FlatCAM Config file.")),
  7967. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7968. color=QtGui.QColor("gray"))
  7969. # # add the tab if it was closed
  7970. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7971. # # first clear previous text in text editor (if any)
  7972. # self.ui.text_editor_tab.code_editor.clear()
  7973. #
  7974. # # Switch plot_area to CNCJob tab
  7975. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7976. # close the Code editor if already open
  7977. if self.toggle_codeeditor:
  7978. self.on_toggle_code_editor()
  7979. self.on_toggle_code_editor()
  7980. try:
  7981. if filename:
  7982. f = QtCore.QFile(filename)
  7983. if f.open(QtCore.QIODevice.ReadOnly):
  7984. stream = QtCore.QTextStream(f)
  7985. code_edited = stream.readAll()
  7986. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7987. f.close()
  7988. except IOError:
  7989. App.log.error("Failed to open config file: %s" % filename)
  7990. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7991. (_("Failed to open config file"), filename))
  7992. return
  7993. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7994. """
  7995. Loads a project from the specified file.
  7996. 1) Loads and parses file
  7997. 2) Registers the file as recently opened.
  7998. 3) Calls on_file_new()
  7999. 4) Updates options
  8000. 5) Calls new_object() with the object's from_dict() as init method.
  8001. 6) Calls plot_all() if plot=True
  8002. :param filename: Name of the file from which to load.
  8003. :param run_from_arg: True if run for arguments
  8004. :param plot: If True plot all objects in the project
  8005. :param cli: Run from command line
  8006. :param from_tcl: True if run from Tcl Sehll
  8007. :return: None
  8008. """
  8009. App.log.debug("Opening project: " + filename)
  8010. # block autosaving while a project is loaded
  8011. self.block_autosave = True
  8012. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8013. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8014. if cli is None:
  8015. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8016. if run_from_arg:
  8017. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8018. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8019. _("Opening FlatCAM Project file.")),
  8020. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8021. color=QtGui.QColor("gray"))
  8022. # Open and parse an uncompressed Project file
  8023. try:
  8024. f = open(filename, 'r')
  8025. except IOError:
  8026. if from_tcl:
  8027. name = filename.split('/')[-1].split('\\')[-1]
  8028. filename = self.defaults['global_tcl_path'] + '/' + name
  8029. try:
  8030. f = open(filename, 'r')
  8031. except IOError:
  8032. log.error("Failed to open project file: %s" % filename)
  8033. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8034. return
  8035. else:
  8036. log.error("Failed to open project file: %s" % filename)
  8037. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8038. return
  8039. try:
  8040. d = json.load(f, object_hook=dict2obj)
  8041. except Exception as e:
  8042. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8043. (filename, str(e)))
  8044. f.close()
  8045. # Open and parse a compressed Project file
  8046. try:
  8047. with lzma.open(filename) as f:
  8048. file_content = f.read().decode('utf-8')
  8049. d = json.loads(file_content, object_hook=dict2obj)
  8050. except Exception as e:
  8051. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8052. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8053. return
  8054. # Clear the current project
  8055. # # NOT THREAD SAFE # ##
  8056. if run_from_arg is True:
  8057. pass
  8058. elif cli is True:
  8059. self.delete_selection_shape()
  8060. else:
  8061. self.on_file_new()
  8062. # Project options
  8063. self.options.update(d['options'])
  8064. self.project_filename = filename
  8065. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8066. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8067. if cli is None:
  8068. self.set_screen_units(self.options["units"])
  8069. # Re create objects
  8070. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8071. for obj in d['objs']:
  8072. try:
  8073. def obj_init(obj_inst, app_inst):
  8074. obj_inst.from_dict(obj)
  8075. App.log.debug("Recreating from opened project an %s object: %s" %
  8076. (obj['kind'].capitalize(), obj['options']['name']))
  8077. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8078. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8079. if cli is None:
  8080. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8081. obj['kind'].upper(),
  8082. obj['options']['name']
  8083. )
  8084. )
  8085. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8086. except Exception as e:
  8087. print('App.open_project() --> ' + str(e))
  8088. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8089. self.should_we_save = False
  8090. self.file_opened.emit("project", filename)
  8091. # restore autosaving after a project was loaded
  8092. self.block_autosave = False
  8093. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8094. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8095. if cli is None:
  8096. self.set_ui_title(name=self.project_filename)
  8097. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8098. def plot_all(self, fit_view=True, use_thread=True):
  8099. """
  8100. Re-generates all plots from all objects.
  8101. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8102. :param use_thread: if True will use threading for plotting the objects
  8103. :return: None
  8104. """
  8105. self.log.debug("Plot_all()")
  8106. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8107. for plot_obj in self.collection.get_list():
  8108. def worker_task(obj):
  8109. with self.proc_container.new("Plotting"):
  8110. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8111. if fit_view is True:
  8112. self.object_plotted.emit(obj)
  8113. if use_thread is True:
  8114. # Send to worker
  8115. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8116. else:
  8117. worker_task(plot_obj)
  8118. def register_folder(self, filename):
  8119. """
  8120. Register the last folder used by the app to open something
  8121. :param filename: the last folder is extracted from the filename
  8122. :return: None
  8123. """
  8124. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8125. def register_save_folder(self, filename):
  8126. """
  8127. Register the last folder used by the app to save something
  8128. :param filename: the last folder is extracted from the filename
  8129. :return: None
  8130. """
  8131. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8132. # def set_progress_bar(self, percentage, text=""):
  8133. # """
  8134. # Set a progress bar to a value (percentage)
  8135. #
  8136. # :param percentage: Value set to the progressbar
  8137. # :param text: Not used
  8138. # :return: None
  8139. # """
  8140. # self.ui.progress_bar.setValue(int(percentage))
  8141. def setup_recent_items(self):
  8142. """
  8143. Setup a dictionary with the recent files accessed, organized by type
  8144. :return:
  8145. """
  8146. icons = {
  8147. "gerber": self.resource_location + "/flatcam_icon16.png",
  8148. "excellon": self.resource_location + "/drill16.png",
  8149. 'geometry': self.resource_location + "/geometry16.png",
  8150. "cncjob": self.resource_location + "/cnc16.png",
  8151. "script": self.resource_location + "/script_new24.png",
  8152. "document": self.resource_location + "/notes16_1.png",
  8153. "project": self.resource_location + "/project16.png",
  8154. "svg": self.resource_location + "/geometry16.png",
  8155. "dxf": self.resource_location + "/dxf16.png",
  8156. "pdf": self.resource_location + "/pdf32.png",
  8157. "image": self.resource_location + "/image16.png"
  8158. }
  8159. try:
  8160. image_opener = self.image_tool.import_image
  8161. except AttributeError:
  8162. image_opener = None
  8163. openers = {
  8164. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8165. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8166. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8167. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8168. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8169. "document": None,
  8170. 'project': self.open_project,
  8171. 'svg': self.import_svg,
  8172. 'dxf': self.import_dxf,
  8173. 'image': image_opener,
  8174. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8175. }
  8176. # Open recent file for files
  8177. try:
  8178. f = open(self.data_path + '/recent.json')
  8179. except IOError:
  8180. App.log.error("Failed to load recent item list.")
  8181. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8182. return
  8183. try:
  8184. self.recent = json.load(f)
  8185. except json.errors.JSONDecodeError:
  8186. App.log.error("Failed to parse recent item list.")
  8187. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8188. f.close()
  8189. return
  8190. f.close()
  8191. # Open recent file for projects
  8192. try:
  8193. fp = open(self.data_path + '/recent_projects.json')
  8194. except IOError:
  8195. App.log.error("Failed to load recent project item list.")
  8196. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8197. return
  8198. try:
  8199. self.recent_projects = json.load(fp)
  8200. except json.errors.JSONDecodeError:
  8201. App.log.error("Failed to parse recent project item list.")
  8202. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8203. fp.close()
  8204. return
  8205. fp.close()
  8206. # Closure needed to create callbacks in a loop.
  8207. # Otherwise late binding occurs.
  8208. def make_callback(func, fname):
  8209. def opener():
  8210. func(fname)
  8211. return opener
  8212. def reset_recent_files():
  8213. # Reset menu
  8214. self.ui.recent.clear()
  8215. self.recent = []
  8216. try:
  8217. ff = open(self.data_path + '/recent.json', 'w')
  8218. except IOError:
  8219. App.log.error("Failed to open recent items file for writing.")
  8220. return
  8221. json.dump(self.recent, ff)
  8222. def reset_recent_projects():
  8223. # Reset menu
  8224. self.ui.recent_projects.clear()
  8225. self.recent_projects = []
  8226. try:
  8227. frp = open(self.data_path + '/recent_projects.json', 'w')
  8228. except IOError:
  8229. App.log.error("Failed to open recent projects items file for writing.")
  8230. return
  8231. json.dump(self.recent, frp)
  8232. # Reset menu
  8233. self.ui.recent.clear()
  8234. self.ui.recent_projects.clear()
  8235. # Create menu items for projects
  8236. for recent in self.recent_projects:
  8237. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8238. if recent['kind'] == 'project':
  8239. try:
  8240. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8241. # Attach callback
  8242. o = make_callback(openers[recent["kind"]], recent['filename'])
  8243. action.triggered.connect(o)
  8244. self.ui.recent_projects.addAction(action)
  8245. except KeyError:
  8246. App.log.error("Unsupported file type: %s" % recent["kind"])
  8247. # Last action in Recent Files menu is one that Clear the content
  8248. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8249. (_("Clear Recent projects")), self)
  8250. clear_action_proj.triggered.connect(reset_recent_projects)
  8251. self.ui.recent_projects.addSeparator()
  8252. self.ui.recent_projects.addAction(clear_action_proj)
  8253. # Create menu items for files
  8254. for recent in self.recent:
  8255. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8256. if recent['kind'] != 'project':
  8257. try:
  8258. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8259. # Attach callback
  8260. o = make_callback(openers[recent["kind"]], recent['filename'])
  8261. action.triggered.connect(o)
  8262. self.ui.recent.addAction(action)
  8263. except KeyError:
  8264. App.log.error("Unsupported file type: %s" % recent["kind"])
  8265. # Last action in Recent Files menu is one that Clear the content
  8266. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8267. (_("Clear Recent files")), self)
  8268. clear_action.triggered.connect(reset_recent_files)
  8269. self.ui.recent.addSeparator()
  8270. self.ui.recent.addAction(clear_action)
  8271. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8272. # self.ui.menufilerecent.set_submenu(recent_menu)
  8273. # recent_menu.show_all()
  8274. # self.ui.recent.show()
  8275. self.log.debug("Recent items list has been populated.")
  8276. def setup_component_editor(self):
  8277. """
  8278. Default text for the Selected tab when is not taken by the Object UI.
  8279. :return:
  8280. """
  8281. # label = QtWidgets.QLabel("Choose an item from Project")
  8282. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8283. sel_title = QtWidgets.QTextEdit(
  8284. _('<b>Shortcut Key List</b>'))
  8285. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8286. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8287. f_settings = QSettings("Open Source", "FlatCAM")
  8288. if f_settings.contains("notebook_font_size"):
  8289. fsize = f_settings.value('notebook_font_size', type=int)
  8290. else:
  8291. fsize = 12
  8292. tsize = fsize + int(fsize / 2)
  8293. # selected_text = (_('''
  8294. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8295. # </p>
  8296. #
  8297. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8298. # The normal flow when working in FlatCAM is the following:</span></p>
  8299. #
  8300. # <ol>
  8301. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8302. # file into
  8303. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8304. # even dragging and dropping the files on the GUI.<br />
  8305. # <br />
  8306. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8307. # drop of the
  8308. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8309. # &nbsp;</li>
  8310. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8311. # and then
  8312. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8313. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8314. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8315. # <br />
  8316. # If the selection of the object is done on the canvas by single click instead, and the
  8317. # <strong>SELECTED TAB</strong>
  8318. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8319. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8320. # it even if it was out of focus.<br />
  8321. # <br />
  8322. # You can change the parameters in this screen and the flow direction is like this:<br />
  8323. # <br />
  8324. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8325. # <strong> Geometry Object
  8326. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8327. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8328. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8329. # </ol>
  8330. #
  8331. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8332. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8333. # <strong>F3</strong>.</span></p>
  8334. #
  8335. # ''').format(fsize=fsize, tsize=tsize))
  8336. selected_text = '''
  8337. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8338. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8339. {s1}</span></p>
  8340. <ol>
  8341. <li><span style="font-size:{fsize}px">{s2}<br />
  8342. <br />
  8343. {s3}</span><br />
  8344. &nbsp;</li>
  8345. <li><span style="font-size:{fsize}px">{s4}<br />
  8346. &nbsp;</li>
  8347. <br />
  8348. <li><span style="font-size:{fsize}px">{s5}<br />
  8349. &nbsp;</li>
  8350. <br />
  8351. <li><span style="font-size:{fsize}px">{s6}<br />
  8352. <br />
  8353. {s7}</span></li>
  8354. </ol>
  8355. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8356. '''.format(
  8357. title=_("Selected Tab - Choose an Item from Project Tab"),
  8358. subtitle=_("Details"),
  8359. s1=_("The normal flow when working in FlatCAM is the following:"),
  8360. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8361. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8362. "files on the GUI."),
  8363. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8364. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8365. "actions offered within the app."),
  8366. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8367. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8368. "SELECTED TAB will be updated with the object properties according to its kind: "
  8369. "Gerber, Excellon, Geometry or CNCJob object."),
  8370. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8371. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8372. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8373. "the SELECTED TAB and populate it even if it was out of focus."),
  8374. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8375. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8376. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8377. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8378. "(again, done in SELECTED TAB) --> Save GCode."),
  8379. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8380. "or through its own key shortcut: <b>F3</b>."),
  8381. tsize=tsize,
  8382. fsize=fsize
  8383. )
  8384. sel_title.setText(selected_text)
  8385. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8386. self.ui.selected_scroll_area.setWidget(sel_title)
  8387. def setup_obj_classes(self):
  8388. """
  8389. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8390. class.
  8391. :return: None
  8392. """
  8393. FlatCAMObj.app = self
  8394. ObjectCollection.app = self
  8395. Gerber.app = self
  8396. Excellon.app = self
  8397. Geometry.app = self
  8398. CNCjob.app = self
  8399. FCProcess.app = self
  8400. FCProcessContainer.app = self
  8401. OptionsGroupUI.app = self
  8402. def version_check(self):
  8403. """
  8404. Checks for the latest version of the program. Alerts the
  8405. user if theirs is outdated. This method is meant to be run
  8406. in a separate thread.
  8407. :return: None
  8408. """
  8409. self.log.debug("version_check()")
  8410. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8411. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8412. App.version_url,
  8413. str(self.defaults['global_serial']),
  8414. str(self.version),
  8415. str(self.os),
  8416. urllib.parse.urlencode(self.defaults["global_stats"])
  8417. )
  8418. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8419. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8420. # urllib.parse.urlencode(self.defaults["global_stats"])
  8421. else:
  8422. # no_stats dict; just so it won't break things on website
  8423. no_ststs_dict = {}
  8424. no_ststs_dict["global_ststs"] = {}
  8425. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8426. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8427. App.log.debug("Checking for updates @ %s" % full_url)
  8428. # ## Get the data
  8429. try:
  8430. f = urllib.request.urlopen(full_url)
  8431. except Exception:
  8432. # App.log.warning("Failed checking for latest version. Could not connect.")
  8433. self.log.warning("Failed checking for latest version. Could not connect.")
  8434. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8435. return
  8436. try:
  8437. data = json.load(f)
  8438. except Exception as e:
  8439. App.log.error("Could not parse information about latest version.")
  8440. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8441. App.log.debug("json.load(): %s" % str(e))
  8442. f.close()
  8443. return
  8444. f.close()
  8445. # ## Latest version?
  8446. if self.version >= data["version"]:
  8447. App.log.debug("FlatCAM is up to date!")
  8448. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8449. return
  8450. App.log.debug("Newer version available.")
  8451. self.message.emit(
  8452. _("Newer Version Available"),
  8453. '%s<br><br>><b>%s</b><br>%s' % (
  8454. _("There is a newer version of FlatCAM available for download:"),
  8455. str(data["name"]),
  8456. str(data["message"])
  8457. ),
  8458. _("info")
  8459. )
  8460. def on_plotcanvas_setup(self, container=None):
  8461. """
  8462. This is doing the setup for the plot area (canvas).
  8463. :param container: QT Widget where to install the canvas
  8464. :return: None
  8465. """
  8466. if container:
  8467. plot_container = container
  8468. else:
  8469. plot_container = self.ui.right_layout
  8470. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8471. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8472. self.is_legacy = True
  8473. self.defaults["global_graphic_engine"] = "2D"
  8474. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8475. else:
  8476. try:
  8477. self.plotcanvas = PlotCanvas(plot_container, self)
  8478. except Exception as er:
  8479. msg_txt = traceback.format_exc()
  8480. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8481. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8482. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8483. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8484. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8485. msg += msg_txt
  8486. self.inform.emit(msg)
  8487. return 'fail'
  8488. # So it can receive key presses
  8489. self.plotcanvas.native.setFocus()
  8490. if self.is_legacy is False:
  8491. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8492. # Set the mouse button for panning
  8493. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8494. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8495. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8496. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8497. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8498. # Keys over plot enabled
  8499. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8500. if self.defaults['global_cursor_type'] == 'small':
  8501. self.app_cursor = self.plotcanvas.new_cursor()
  8502. else:
  8503. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8504. if self.ui.grid_snap_btn.isChecked():
  8505. self.app_cursor.enabled = True
  8506. else:
  8507. self.app_cursor.enabled = False
  8508. if self.is_legacy is False:
  8509. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8510. else:
  8511. # will use the default Matplotlib axes
  8512. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8513. def on_zoom_fit(self, event):
  8514. """
  8515. Callback for zoom-fit request. This can be either from the corresponding
  8516. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8517. with axes limits from the geometry bounds of all objects.
  8518. :param event: Ignored.
  8519. :return: None
  8520. """
  8521. if self.is_legacy is False:
  8522. self.plotcanvas.fit_view()
  8523. else:
  8524. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8525. width = xmax - xmin
  8526. height = ymax - ymin
  8527. xmin -= 0.05 * width
  8528. xmax += 0.05 * width
  8529. ymin -= 0.05 * height
  8530. ymax += 0.05 * height
  8531. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8532. def on_zoom_in(self):
  8533. """
  8534. Callback for zoom-in request.
  8535. :return:
  8536. """
  8537. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8538. def on_zoom_out(self):
  8539. """
  8540. Callback for zoom-out request.
  8541. :return:
  8542. """
  8543. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8544. def disable_all_plots(self):
  8545. self.defaults.report_usage("disable_all_plots()")
  8546. self.disable_plots(self.collection.get_list())
  8547. self.inform.emit('[success] %s' %
  8548. _("All plots disabled."))
  8549. def disable_other_plots(self):
  8550. self.defaults.report_usage("disable_other_plots()")
  8551. self.disable_plots(self.collection.get_non_selected())
  8552. self.inform.emit('[success] %s' %
  8553. _("All non selected plots disabled."))
  8554. def enable_all_plots(self):
  8555. self.defaults.report_usage("enable_all_plots()")
  8556. self.enable_plots(self.collection.get_list())
  8557. self.inform.emit('[success] %s' %
  8558. _("All plots enabled."))
  8559. def on_enable_sel_plots(self):
  8560. log.debug("App.on_enable_sel_plot()")
  8561. object_list = self.collection.get_selected()
  8562. self.enable_plots(objects=object_list)
  8563. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8564. def on_disable_sel_plots(self):
  8565. log.debug("App.on_disable_sel_plot()")
  8566. # self.inform.emit(_("Disabling plots ..."))
  8567. object_list = self.collection.get_selected()
  8568. self.disable_plots(objects=object_list)
  8569. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8570. def enable_plots(self, objects):
  8571. """
  8572. Enable plots
  8573. :param objects: list of Objects to be enabled
  8574. :return:
  8575. """
  8576. log.debug("Enabling plots ...")
  8577. # self.inform.emit(_("Working ..."))
  8578. for obj in objects:
  8579. if obj.options['plot'] is False:
  8580. obj.options.set_change_callback(lambda x: None)
  8581. obj.options['plot'] = True
  8582. try:
  8583. # only the Gerber obj has on_plot_cb_click() method
  8584. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8585. # disable this cb while disconnected,
  8586. # in case the operation takes time the user is not allowed to change it
  8587. obj.ui.plot_cb.setDisabled(True)
  8588. except AttributeError:
  8589. pass
  8590. obj.set_form_item("plot")
  8591. try:
  8592. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8593. obj.ui.plot_cb.setDisabled(False)
  8594. except AttributeError:
  8595. pass
  8596. obj.options.set_change_callback(obj.on_options_change)
  8597. def worker_task(objs):
  8598. with self.proc_container.new(_("Enabling plots ...")):
  8599. for plot_obj in objs:
  8600. # obj.options['plot'] = True
  8601. if isinstance(plot_obj, CNCJobObject):
  8602. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8603. else:
  8604. plot_obj.plot(visible=True)
  8605. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8606. # self.plots_updated.emit()
  8607. def disable_plots(self, objects):
  8608. """
  8609. Disables plots
  8610. :param objects: list of Objects to be disabled
  8611. :return:
  8612. """
  8613. # if no objects selected then do nothing
  8614. if not self.collection.get_selected():
  8615. return
  8616. log.debug("Disabling plots ...")
  8617. # self.inform.emit(_("Working ..."))
  8618. for obj in objects:
  8619. if obj.options['plot'] is True:
  8620. obj.options.set_change_callback(lambda x: None)
  8621. obj.options['plot'] = False
  8622. try:
  8623. # only the Gerber obj has on_plot_cb_click() method
  8624. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8625. obj.ui.plot_cb.setDisabled(True)
  8626. except AttributeError:
  8627. pass
  8628. obj.set_form_item("plot")
  8629. try:
  8630. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8631. obj.ui.plot_cb.setDisabled(False)
  8632. except AttributeError:
  8633. pass
  8634. obj.options.set_change_callback(obj.on_options_change)
  8635. try:
  8636. self.delete_selection_shape()
  8637. except Exception as e:
  8638. log.debug("App.disable_plots() --> %s" % str(e))
  8639. # self.plots_updated.emit()
  8640. def worker_task(objs):
  8641. with self.proc_container.new(_("Disabling plots ...")):
  8642. for plot_obj in objs:
  8643. # obj.options['plot'] = True
  8644. if isinstance(plot_obj, CNCJobObject):
  8645. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8646. else:
  8647. plot_obj.plot(visible=False)
  8648. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8649. def toggle_plots(self, objects):
  8650. """
  8651. Toggle plots visibility
  8652. :param objects: list of Objects for which to be toggled the visibility
  8653. :return: None
  8654. """
  8655. # if no objects selected then do nothing
  8656. if not self.collection.get_selected():
  8657. return
  8658. log.debug("Toggling plots ...")
  8659. self.inform.emit(_("Working ..."))
  8660. for obj in objects:
  8661. if obj.options['plot'] is False:
  8662. obj.options['plot'] = True
  8663. else:
  8664. obj.options['plot'] = False
  8665. self.plots_updated.emit()
  8666. def clear_plots(self):
  8667. """
  8668. Clear the plots
  8669. :return: None
  8670. """
  8671. objects = self.collection.get_list()
  8672. for obj in objects:
  8673. obj.clear(obj == objects[-1])
  8674. # Clear pool to free memory
  8675. self.clear_pool()
  8676. def on_set_color_action_triggered(self):
  8677. """
  8678. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8679. :return:
  8680. """
  8681. new_color = self.defaults['gerber_plot_fill']
  8682. clicked_action = self.sender()
  8683. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8684. act_name = clicked_action.text()
  8685. sel_obj_list = self.collection.get_selected()
  8686. if not sel_obj_list:
  8687. return
  8688. # a default value, I just chose this one
  8689. alpha_level = 'BF'
  8690. for sel_obj in sel_obj_list:
  8691. if sel_obj.kind == 'excellon':
  8692. alpha_level = str(hex(
  8693. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8694. elif sel_obj.kind == 'gerber':
  8695. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8696. elif sel_obj.kind == 'geometry':
  8697. alpha_level = 'FF'
  8698. else:
  8699. log.debug(
  8700. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8701. continue
  8702. sel_obj.alpha_level = alpha_level
  8703. if act_name == _('Red'):
  8704. new_color = '#FF0000' + alpha_level
  8705. if act_name == _('Blue'):
  8706. new_color = '#0000FF' + alpha_level
  8707. if act_name == _('Yellow'):
  8708. new_color = '#FFDF00' + alpha_level
  8709. if act_name == _('Green'):
  8710. new_color = '#00FF00' + alpha_level
  8711. if act_name == _('Purple'):
  8712. new_color = '#FF00FF' + alpha_level
  8713. if act_name == _('Brown'):
  8714. new_color = '#A52A2A' + alpha_level
  8715. if act_name == _('White'):
  8716. new_color = '#FFFFFF' + alpha_level
  8717. if act_name == _('Black'):
  8718. new_color = '#000000' + alpha_level
  8719. if act_name == _('Custom'):
  8720. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8721. c_dialog = QtWidgets.QColorDialog()
  8722. plot_fill_color = c_dialog.getColor(initial=new_color)
  8723. if plot_fill_color.isValid() is False:
  8724. return
  8725. new_color = str(plot_fill_color.name()) + alpha_level
  8726. if act_name == _("Default"):
  8727. for sel_obj in sel_obj_list:
  8728. if sel_obj.kind == 'excellon':
  8729. new_color = self.defaults['excellon_plot_fill']
  8730. new_line_color = self.defaults['excellon_plot_line']
  8731. elif sel_obj.kind == 'gerber':
  8732. new_color = self.defaults['gerber_plot_fill']
  8733. new_line_color = self.defaults['gerber_plot_line']
  8734. elif sel_obj.kind == 'geometry':
  8735. new_color = self.defaults['geometry_plot_line']
  8736. new_line_color = self.defaults['geometry_plot_line']
  8737. else:
  8738. log.debug(
  8739. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8740. continue
  8741. sel_obj.fill_color = new_color
  8742. sel_obj.outline_color = new_line_color
  8743. sel_obj.shapes.redraw(
  8744. update_colors=(new_color, new_line_color)
  8745. )
  8746. return
  8747. if act_name == _("Opacity"):
  8748. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8749. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8750. if ok_button:
  8751. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8752. for sel_obj in sel_obj_list:
  8753. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8754. sel_obj.shapes.redraw(
  8755. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8756. )
  8757. return
  8758. new_line_color = color_variant(new_color[:7], 0.7)
  8759. if act_name == _("White"):
  8760. new_line_color = color_variant("#dedede", 0.7)
  8761. for sel_obj in sel_obj_list:
  8762. sel_obj.fill_color = new_color
  8763. sel_obj.outline_color = new_line_color
  8764. sel_obj.shapes.redraw(
  8765. update_colors=(new_color, new_line_color)
  8766. )
  8767. def on_grid_snap_triggered(self, state):
  8768. """
  8769. :param state: A parameter with the state of the grid, boolean
  8770. :return:
  8771. """
  8772. if state:
  8773. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_filled_16.png'))
  8774. else:
  8775. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_16.png'))
  8776. self.ui.snap_infobar_label.clicked_state = state
  8777. def on_grid_icon_snap_clicked(self):
  8778. """
  8779. Slot called by clicking a GUI element, in this case a FCLabel
  8780. :return:
  8781. """
  8782. if isinstance(self.sender(), FCLabel):
  8783. self.ui.grid_snap_btn.trigger()
  8784. def generate_cnc_job(self, objects):
  8785. """
  8786. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8787. :param objects: Selected objects in the Project Tab
  8788. :return:
  8789. """
  8790. self.defaults.report_usage("generate_cnc_job()")
  8791. # for obj in objects:
  8792. # obj.generatecncjob()
  8793. for obj in objects:
  8794. obj.on_generatecnc_button_click()
  8795. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8796. """
  8797. Saves the current project to the specified file.
  8798. :param filename: Name of the file in which to save.
  8799. :type filename: str
  8800. :param quit_action: if the project saving will be followed by an app quit; boolean
  8801. :param silent: if True will not display status messages
  8802. :param from_tcl True is run from Tcl Shell
  8803. :return: None
  8804. """
  8805. self.log.debug("save_project()")
  8806. self.save_in_progress = True
  8807. with self.proc_container.new(_("Saving FlatCAM Project")):
  8808. # Capture the latest changes
  8809. # Current object
  8810. try:
  8811. current_object = self.collection.get_active()
  8812. if current_object:
  8813. current_object.read_form()
  8814. except Exception as e:
  8815. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8816. pass
  8817. # Serialize the whole project
  8818. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8819. "options": self.options,
  8820. "version": self.version}
  8821. if self.defaults["global_save_compressed"] is True:
  8822. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8823. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8824. # # Write
  8825. f.write(g)
  8826. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8827. else:
  8828. # Open file
  8829. try:
  8830. f = open(filename, 'w')
  8831. except IOError:
  8832. App.log.error("Failed to open file for saving: %s", filename)
  8833. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8834. return
  8835. # Write
  8836. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8837. f.close()
  8838. # verification of the saved project
  8839. # Open and parse
  8840. try:
  8841. saved_f = open(filename, 'r')
  8842. except IOError:
  8843. if silent is False:
  8844. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8845. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8846. return
  8847. try:
  8848. saved_d = json.load(saved_f, object_hook=dict2obj)
  8849. except Exception:
  8850. if silent is False:
  8851. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8852. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8853. f.close()
  8854. return
  8855. saved_f.close()
  8856. if silent is False:
  8857. if 'version' in saved_d:
  8858. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8859. else:
  8860. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8861. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8862. tb_settings = QSettings("Open Source", "FlatCAM")
  8863. lock_state = self.ui.lock_action.isChecked()
  8864. tb_settings.setValue('toolbar_lock', lock_state)
  8865. # This will write the setting to the platform specific storage.
  8866. del tb_settings
  8867. # if quit:
  8868. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8869. # t.start()
  8870. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8871. def start_delayed_quit(self, delay, filename, should_quit=None):
  8872. """
  8873. :param delay: period of checking if project file size is more than zero; in seconds
  8874. :param filename: the name of the project file to be checked periodically for size more than zero
  8875. :param should_quit: if the task finished will be followed by an app quit; boolean
  8876. :return:
  8877. """
  8878. to_quit = should_quit
  8879. self.save_timer = QtCore.QTimer()
  8880. self.save_timer.setInterval(delay)
  8881. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8882. self.save_timer.start()
  8883. def check_project_file_size(self, filename, should_quit=None):
  8884. """
  8885. :param filename: the name of the project file to be checked periodically for size more than zero
  8886. :param should_quit: will quit the app if True; boolean
  8887. :return:
  8888. """
  8889. try:
  8890. if os.stat(filename).st_size > 0:
  8891. self.save_in_progress = False
  8892. self.save_timer.stop()
  8893. if should_quit:
  8894. self.app_quit.emit()
  8895. except Exception:
  8896. traceback.print_exc()
  8897. def save_project_auto(self):
  8898. """
  8899. Called periodically to save the project.
  8900. 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
  8901. # progress.
  8902. :return:
  8903. """
  8904. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8905. self.on_file_saveproject()
  8906. def save_project_auto_update(self):
  8907. """
  8908. Update the auto save time interval value.
  8909. :return:
  8910. """
  8911. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8912. try:
  8913. if self.autosave_timer.isActive():
  8914. self.autosave_timer.stop()
  8915. except Exception:
  8916. pass
  8917. if self.defaults['global_autosave'] is True:
  8918. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8919. self.autosave_timer.start()
  8920. def on_options_app2project(self):
  8921. """
  8922. Callback for Options->Transfer Options->App=>Project. Copies options
  8923. from application defaults to project defaults.
  8924. :return: None
  8925. """
  8926. self.defaults.report_usage("on_options_app2project")
  8927. self.preferencesUiManager.defaults_read_form()
  8928. self.options.update(self.defaults)
  8929. def toggle_shell(self):
  8930. """
  8931. Toggle shell: if is visible close it, if it is closed then open it
  8932. :return: None
  8933. """
  8934. self.defaults.report_usage("toggle_shell()")
  8935. if self.ui.shell_dock.isVisible():
  8936. self.ui.shell_dock.hide()
  8937. self.plotcanvas.native.setFocus()
  8938. else:
  8939. self.ui.shell_dock.show()
  8940. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8941. # self.shell._edit.setFocus()
  8942. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8943. # HACK - simulate a mouse click - alternative
  8944. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8945. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8946. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8947. # no_km)
  8948. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8949. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8950. # no_km)
  8951. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8952. def on_toggle_shell_from_settings(self, state):
  8953. """
  8954. Toggle shell: if is visible close it, if it is closed then open it
  8955. :return: None
  8956. """
  8957. self.defaults.report_usage("on_toggle_shell_from_settings()")
  8958. if state is True:
  8959. if not self.ui.shell_dock.isVisible():
  8960. self.ui.shell_dock.show()
  8961. else:
  8962. if self.ui.shell_dock.isVisible():
  8963. self.ui.shell_dock.hide()
  8964. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8965. """
  8966. Shows a message on the FlatCAM Shell
  8967. :param msg: Message to display.
  8968. :param show: Opens the shell.
  8969. :param error: Shows the message as an error.
  8970. :param warning: Shows the message as an warning.
  8971. :param success: Shows the message as an success.
  8972. :param selected: Indicate that something was selected on canvas
  8973. :return: None
  8974. """
  8975. if show:
  8976. self.ui.shell_dock.show()
  8977. try:
  8978. if error:
  8979. self.shell.append_error(msg + "\n")
  8980. elif warning:
  8981. self.shell.append_warning(msg + "\n")
  8982. elif success:
  8983. self.shell.append_success(msg + "\n")
  8984. elif selected:
  8985. self.shell.append_selected(msg + "\n")
  8986. else:
  8987. self.shell.append_output(msg + "\n")
  8988. except AttributeError:
  8989. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8990. class ArgsThread(QtCore.QObject):
  8991. open_signal = pyqtSignal(list)
  8992. start = pyqtSignal()
  8993. if sys.platform == 'win32':
  8994. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8995. else:
  8996. address = ('/tmp/testipc', 'AF_UNIX')
  8997. def __init__(self):
  8998. super(ArgsThread, self).__init__()
  8999. self.listener = None
  9000. self.thread_exit = False
  9001. self.start.connect(self.run)
  9002. def my_loop(self, address):
  9003. try:
  9004. self.listener = Listener(*address)
  9005. while self.thread_exit is False:
  9006. conn = self.listener.accept()
  9007. self.serve(conn)
  9008. except socket.error:
  9009. try:
  9010. conn = Client(*address)
  9011. conn.send(sys.argv)
  9012. conn.send('close')
  9013. # close the current instance only if there are args
  9014. if len(sys.argv) > 1:
  9015. try:
  9016. self.listener.close()
  9017. except Exception:
  9018. pass
  9019. sys.exit()
  9020. except ConnectionRefusedError:
  9021. if sys.platform == 'win32':
  9022. pass
  9023. else:
  9024. os.system('rm /tmp/testipc')
  9025. self.listener = Listener(*address)
  9026. while True:
  9027. conn = self.listener.accept()
  9028. self.serve(conn)
  9029. def serve(self, conn):
  9030. while self.thread_exit is False:
  9031. msg = conn.recv()
  9032. if msg == 'close':
  9033. break
  9034. self.open_signal.emit(msg)
  9035. conn.close()
  9036. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9037. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9038. @pyqtSlot()
  9039. def run(self):
  9040. self.my_loop(self.address)
  9041. # end of file