FlatCAMApp.py 484 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import shutil
  16. from datetime import datetime
  17. import time
  18. import ctypes
  19. import traceback
  20. from PyQt5.QtCore import pyqtSlot, Qt
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Diverse
  37. from FlatCAMCommon import LoudDict, color_variant, ExclusionAreas
  38. from FlatCAMBookmark import BookmarkManager
  39. from FlatCAMDB import ToolsDB2
  40. from vispy.gloo.util import _screenshot
  41. from vispy.io import write_png
  42. # FlatCAM Objects
  43. from defaults import FlatCAMDefaults
  44. from flatcamGUI.preferences.OptionsGroupUI import OptionsGroupUI
  45. from flatcamGUI.preferences.PreferencesUIManager import PreferencesUIManager
  46. from flatcamObjects.ObjectCollection import *
  47. from flatcamObjects.FlatCAMObj import FlatCAMObj
  48. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  49. from flatcamObjects.FlatCAMDocument import DocumentObject
  50. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  51. from flatcamObjects.FlatCAMGeometry import GeometryObject
  52. from flatcamObjects.FlatCAMGerber import GerberObject
  53. from flatcamObjects.FlatCAMScript import ScriptObject
  54. # FlatCAM Parsing files
  55. from flatcamParsers.ParseExcellon import Excellon
  56. from flatcamParsers.ParseGerber import Gerber
  57. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  58. # FlatCAM GUI
  59. from flatcamGUI.PlotCanvas import *
  60. from flatcamGUI.PlotCanvasLegacy import *
  61. from flatcamGUI.FlatCAMGUI import *
  62. from flatcamGUI.GUIElements import FCFileSaveDialog
  63. # FlatCAM Pre-processors
  64. from FlatCAMPostProc import load_preprocessors
  65. # FlatCAM Editors
  66. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  67. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  68. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  69. from flatcamEditors.FlatCAMTextEditor import TextEditor
  70. from flatcamParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from FlatCAMProcess import *
  73. from FlatCAMWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from flatcamTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import FlatCAMTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = 8.993
  138. version_date = "2020/08/01"
  139. beta = True
  140. engine = '3D'
  141. # current date now
  142. date = str(datetime.today()).rpartition('.')[0]
  143. date = ''.join(c for c in date if c not in ':-')
  144. date = date.replace(' ', '_')
  145. # ###############################################################################################################
  146. # ############################################ URLS's ###########################################################
  147. # ###############################################################################################################
  148. # URL for update checks and statistics
  149. version_url = "http://flatcam.org/version"
  150. # App URL
  151. app_url = "http://flatcam.org"
  152. # Manual URL
  153. manual_url = "http://flatcam.org/manual/index.html"
  154. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  155. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  156. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  157. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  158. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  159. # this variable will hold the project status
  160. # if True it will mean that the project was modified and not saved
  161. should_we_save = False
  162. # flag is True if saving action has been triggered
  163. save_in_progress = False
  164. # ###############################################################################################################
  165. # ####################################### APP Signals ######################################################
  166. # ###############################################################################################################
  167. # Inform the user
  168. # Handled by:
  169. # * App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal(str)
  171. app_quit = QtCore.pyqtSignal()
  172. # General purpose background task
  173. worker_task = QtCore.pyqtSignal(dict)
  174. # File opened
  175. # Handled by:
  176. # * register_folder()
  177. # * register_recent()
  178. # Note: Setting the parameters to unicode does not seem
  179. # to have an effect. Then are received as Qstring
  180. # anyway.
  181. # File type and filename
  182. file_opened = QtCore.pyqtSignal(str, str)
  183. # File type and filename
  184. file_saved = QtCore.pyqtSignal(str, str)
  185. # Percentage of progress
  186. progress = QtCore.pyqtSignal(int)
  187. plots_updated = QtCore.pyqtSignal()
  188. # Emitted by new_object() and passes the new object as argument, plot flag.
  189. # on_object_created() adds the object to the collection, plots on appropriate flag
  190. # and emits new_object_available.
  191. object_created = QtCore.pyqtSignal(object, bool, bool)
  192. # Emitted when a object has been changed (like scaled, mirrored)
  193. object_changed = QtCore.pyqtSignal(object)
  194. # Emitted after object has been plotted.
  195. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  196. object_plotted = QtCore.pyqtSignal(object)
  197. # Emitted when a new object has been added or deleted from/to the collection
  198. object_status_changed = QtCore.pyqtSignal(object, str, str)
  199. message = QtCore.pyqtSignal(str, str, str)
  200. # Emmited when shell command is finished(one command only)
  201. shell_command_finished = QtCore.pyqtSignal(object)
  202. # Emitted when multiprocess pool has been recreated
  203. pool_recreated = QtCore.pyqtSignal(object)
  204. # Emitted when an unhandled exception happens
  205. # in the worker task.
  206. thread_exception = QtCore.pyqtSignal(object)
  207. # used to signal that there are arguments for the app
  208. args_at_startup = QtCore.pyqtSignal(list)
  209. # a reusable signal to replot a list of objects
  210. # should be disconnected after use so it can be reused
  211. replot_signal = pyqtSignal(list)
  212. # signal emitted when jumping
  213. jump_signal = pyqtSignal(tuple)
  214. # signal emitted when jumping
  215. locate_signal = pyqtSignal(tuple, str)
  216. # close app signal
  217. close_app_signal = pyqtSignal()
  218. # will perform the cleanup operation after a Graceful Exit
  219. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  220. # graphic residues behind
  221. cleanup = pyqtSignal()
  222. def __init__(self, user_defaults=True):
  223. """
  224. Starts the application.
  225. :return: app
  226. :rtype: App
  227. """
  228. super().__init__()
  229. App.log.info("FlatCAM Starting...")
  230. self.main_thread = QtWidgets.QApplication.instance().thread()
  231. # ############################################################################################################
  232. # ################# Setup the listening thread for another instance launching with args ######################
  233. # ############################################################################################################
  234. if sys.platform == 'win32' or sys.platform == 'linux':
  235. # make sure the thread is stored by using a self. otherwise it's garbage collected
  236. self.th = QtCore.QThread()
  237. self.th.start(priority=QtCore.QThread.LowestPriority)
  238. self.new_launch = ArgsThread()
  239. self.new_launch.open_signal[list].connect(self.on_startup_args)
  240. self.new_launch.moveToThread(self.th)
  241. self.new_launch.start.emit()
  242. # ############################################################################################################
  243. # # ######################################## OS-specific #####################################################
  244. # ############################################################################################################
  245. portable = False
  246. # Folder for user settings.
  247. if sys.platform == 'win32':
  248. if platform.architecture()[0] == '32bit':
  249. App.log.debug("Win32!")
  250. else:
  251. App.log.debug("Win64!")
  252. # #######################################################################################################
  253. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  254. # #######################################################################################################
  255. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  256. try:
  257. with open(config_file, 'r'):
  258. pass
  259. except FileNotFoundError:
  260. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  261. try:
  262. with open(config_file, 'r') as f:
  263. try:
  264. for line in f:
  265. param = str(line).replace('\n', '').rpartition('=')
  266. if param[0] == 'portable':
  267. try:
  268. portable = eval(param[2])
  269. except NameError:
  270. portable = False
  271. if param[0] == 'headless':
  272. if param[2].lower() == 'true':
  273. self.cmd_line_headless = 1
  274. else:
  275. self.cmd_line_headless = None
  276. except Exception as e:
  277. log.debug('App.__init__() -->%s' % str(e))
  278. return
  279. except FileNotFoundError as e:
  280. log.debug(str(e))
  281. pass
  282. if portable is False:
  283. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  284. else:
  285. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  286. self.os = 'windows'
  287. else: # Linux/Unix/MacOS
  288. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  289. self.os = 'unix'
  290. # ############################################################################################################
  291. # ################################# Setup folders and files ##################################################
  292. # ############################################################################################################
  293. if not os.path.exists(self.data_path):
  294. os.makedirs(self.data_path)
  295. App.log.debug('Created data folder: ' + self.data_path)
  296. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  297. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  298. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  299. if not os.path.exists(self.preprocessorpaths):
  300. os.makedirs(self.preprocessorpaths)
  301. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  302. # create geo_tools_db.FlatDB file if there is none
  303. try:
  304. f = open(self.data_path + '/geo_tools_db.FlatDB')
  305. f.close()
  306. except IOError:
  307. App.log.debug('Creating empty geo_tool_db.FlatDB')
  308. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  309. json.dump({}, f)
  310. f.close()
  311. # create current_defaults.FlatConfig file if there is none
  312. try:
  313. f = open(self.data_path + '/current_defaults.FlatConfig')
  314. f.close()
  315. except IOError:
  316. App.log.debug('Creating empty current_defaults.FlatConfig')
  317. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  318. json.dump({}, f)
  319. f.close()
  320. # Write factory_defaults.FlatConfig file to disk
  321. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  322. # create a recent files json file if there is none
  323. try:
  324. f = open(self.data_path + '/recent.json')
  325. f.close()
  326. except IOError:
  327. App.log.debug('Creating empty recent.json')
  328. f = open(self.data_path + '/recent.json', 'w')
  329. json.dump([], f)
  330. f.close()
  331. # create a recent projects json file if there is none
  332. try:
  333. fp = open(self.data_path + '/recent_projects.json')
  334. fp.close()
  335. except IOError:
  336. App.log.debug('Creating empty recent_projects.json')
  337. fp = open(self.data_path + '/recent_projects.json', 'w')
  338. json.dump([], fp)
  339. fp.close()
  340. # Application directory. CHDIR to it. Otherwise, trying to load
  341. # GUI icons will fail as their path is relative.
  342. # This will fail under cx_freeze ...
  343. self.app_home = os.path.dirname(os.path.realpath(__file__))
  344. App.log.debug("Application path is " + self.app_home)
  345. App.log.debug("Started in " + os.getcwd())
  346. # cx_freeze workaround
  347. if os.path.isfile(self.app_home):
  348. self.app_home = os.path.dirname(self.app_home)
  349. os.chdir(self.app_home)
  350. # ############################################################################################################
  351. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  352. # ############################################################################################################
  353. self.defaults = FlatCAMDefaults()
  354. self.defaults["root_folder_path"] = self.app_home
  355. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  356. if user_defaults:
  357. self.defaults.load(filename=current_defaults_path)
  358. if self.defaults['units'] == 'MM':
  359. self.decimals = int(self.defaults['decimals_metric'])
  360. else:
  361. self.decimals = int(self.defaults['decimals_inch'])
  362. if self.defaults["global_gray_icons"] is False:
  363. self.resource_location = 'assets/resources'
  364. else:
  365. self.resource_location = 'assets/resources/dark_resources'
  366. self.current_units = self.defaults['units']
  367. # ###########################################################################################################
  368. # #################################### SETUP OBJECT CLASSES #################################################
  369. # ###########################################################################################################
  370. self.setup_obj_classes()
  371. # ###########################################################################################################
  372. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  373. # ###########################################################################################################
  374. self.pool = Pool()
  375. # ###########################################################################################################
  376. # ###################################### Setting the Splash Screen ##########################################
  377. # ###########################################################################################################
  378. splash_settings = QSettings("Open Source", "FlatCAM")
  379. if splash_settings.contains("splash_screen"):
  380. show_splash = splash_settings.value("splash_screen")
  381. else:
  382. splash_settings.setValue('splash_screen', 1)
  383. # This will write the setting to the platform specific storage.
  384. del splash_settings
  385. show_splash = 1
  386. if show_splash and self.cmd_line_headless != 1:
  387. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  388. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  389. # self.splash.setMask(splash_pix.mask())
  390. # move splashscreen to the current monitor
  391. desktop = QtWidgets.QApplication.desktop()
  392. screen = desktop.screenNumber(QtGui.QCursor.pos())
  393. current_screen_center = desktop.availableGeometry(screen).center()
  394. self.splash.move(current_screen_center - self.splash.rect().center())
  395. self.splash.show()
  396. self.splash.showMessage(_("FlatCAM is initializing ..."),
  397. alignment=Qt.AlignBottom | Qt.AlignLeft,
  398. color=QtGui.QColor("gray"))
  399. else:
  400. show_splash = 0
  401. # ###########################################################################################################
  402. # ######################################### Initialize GUI ##################################################
  403. # ###########################################################################################################
  404. # FlatCAM colors used in plotting
  405. self.FC_light_green = '#BBF268BF'
  406. self.FC_dark_green = '#006E20BF'
  407. self.FC_light_blue = '#a5a5ffbf'
  408. self.FC_dark_blue = '#0000ffbf'
  409. self.ui = FlatCAMGUI(self)
  410. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  411. if theme_settings.contains("theme"):
  412. theme = theme_settings.value('theme', type=str)
  413. else:
  414. theme = 'white'
  415. if self.defaults["global_cursor_color_enabled"]:
  416. self.cursor_color_3D = self.defaults["global_cursor_color"]
  417. else:
  418. if theme == 'white':
  419. self.cursor_color_3D = 'black'
  420. else:
  421. self.cursor_color_3D = 'gray'
  422. # update the defaults dict with the setting in QSetting
  423. self.defaults['global_theme'] = theme
  424. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  425. self.ui.final_save.connect(self.final_save)
  426. # restore the toolbar view
  427. self.restore_toolbar_view()
  428. # restore the GUI geometry
  429. self.restore_main_win_geom()
  430. # set FlatCAM units in the Status bar
  431. self.set_screen_units(self.defaults['units'])
  432. # ###########################################################################################################
  433. # ########################################### AUTOSAVE SETUP ################################################
  434. # ###########################################################################################################
  435. self.block_autosave = False
  436. self.autosave_timer = QtCore.QTimer(self)
  437. self.save_project_auto_update()
  438. self.autosave_timer.timeout.connect(self.save_project_auto)
  439. # ###########################################################################################################
  440. # #################################### LOAD PREPROCESSORS ###################################################
  441. # ###########################################################################################################
  442. # ----------------------------------------- WARNING --------------------------------------------------------
  443. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  444. # That's because the number of preprocessors can vary and here the comboboxes are populated
  445. # -----------------------------------------------------------------------------------------------------------
  446. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  447. # the preprocessor file
  448. self.preprocessors = load_preprocessors(self)
  449. # make sure that always the 'default' preprocessor is the first item in the dictionary
  450. if 'default' in self.preprocessors.keys():
  451. new_ppp_dict = {}
  452. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  453. default_pp = self.preprocessors.pop('default')
  454. new_ppp_dict['default'] = default_pp
  455. # then add the rest of the keys
  456. for name, val_class in self.preprocessors.items():
  457. new_ppp_dict[name] = val_class
  458. # and now put back the ordered dict with 'default' key first
  459. self.preprocessors = new_ppp_dict
  460. for name in list(self.preprocessors.keys()):
  461. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  462. if name.partition('_')[0] == 'Paste':
  463. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  464. continue
  465. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  466. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  467. if name == 'hpgl':
  468. continue
  469. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  470. # ###########################################################################################################
  471. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  472. # ###########################################################################################################
  473. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  474. inform=self.inform)
  475. self.preferencesUiManager.defaults_write_form()
  476. # When the self.defaults dictionary changes will update the Preferences GUI forms
  477. self.defaults.set_change_callback(self.on_defaults_dict_change)
  478. # ###########################################################################################################
  479. # ##################################### FIRST RUN SECTION ###################################################
  480. # ################################ It's done only once after install #####################################
  481. # ###########################################################################################################
  482. if self.defaults["first_run"] is True:
  483. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  484. initial_lay = 'minimal'
  485. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  486. # Set the combobox in Preferences to the current layout
  487. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  488. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  489. # after the first run, this object should be False
  490. self.defaults["first_run"] = False
  491. self.preferencesUiManager.save_defaults(silent=True)
  492. # ###########################################################################################################
  493. # ############################################ Data #########################################################
  494. # ###########################################################################################################
  495. self.recent = []
  496. self.recent_projects = []
  497. self.clipboard = QtWidgets.QApplication.clipboard()
  498. self.project_filename = None
  499. self.toggle_units_ignore = False
  500. # ###########################################################################################################
  501. # ########################################## LOAD LANGUAGES ################################################
  502. # ###########################################################################################################
  503. self.languages = fcTranslate.load_languages()
  504. for name in sorted(self.languages.values()):
  505. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  506. # ###########################################################################################################
  507. # ####################################### APPLY APP LANGUAGE ################################################
  508. # ###########################################################################################################
  509. ret_val = fcTranslate.apply_language('strings')
  510. if ret_val == "no language":
  511. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  512. log.debug("Could not find the Language files. The App strings are missing.")
  513. else:
  514. # make the current language the current selection on the language combobox
  515. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  516. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  517. # ###########################################################################################################
  518. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  519. # ###########################################################################################################
  520. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  521. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  522. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  523. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  524. self.defaults.propagate_defaults()
  525. # ###########################################################################################################
  526. # ######################################## UPDATE THE OPTIONS ###############################################
  527. # ###########################################################################################################
  528. self.options = LoudDict()
  529. # -----------------------------------------------------------------------------------------------------------
  530. # Update the self.options from the self.defaults
  531. # The self.defaults holds the application defaults while the self.options holds the object defaults
  532. # -----------------------------------------------------------------------------------------------------------
  533. # Copy app defaults to project options
  534. for def_key, def_val in self.defaults.items():
  535. self.options[def_key] = deepcopy(def_val)
  536. self.preferencesUiManager.show_preferences_gui()
  537. # ### End of Data ####
  538. # ###########################################################################################################
  539. # #################################### SETUP OBJECT COLLECTION ##############################################
  540. # ###########################################################################################################
  541. self.collection = ObjectCollection(self)
  542. self.ui.project_tab_layout.addWidget(self.collection.view)
  543. # ### Adjust tabs width ## ##
  544. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  545. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  546. self.collection.view.setMinimumWidth(290)
  547. self.log.debug("Finished creating Object Collection.")
  548. # ###########################################################################################################
  549. # ######################################## SETUP Plot Area ##################################################
  550. # ###########################################################################################################
  551. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  552. if self.defaults["global_graphic_engine"] == '3D':
  553. self.is_legacy = False
  554. else:
  555. self.is_legacy = True
  556. # Event signals disconnect id holders
  557. self.mp = None
  558. self.mm = None
  559. self.mr = None
  560. self.mdc = None
  561. self.mp_zc = None
  562. self.kp = None
  563. # Matplotlib axis
  564. self.axes = None
  565. if show_splash:
  566. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  567. "Canvas initialization started."),
  568. alignment=Qt.AlignBottom | Qt.AlignLeft,
  569. color=QtGui.QColor("gray"))
  570. start_plot_time = time.time() # debug
  571. self.plotcanvas = None
  572. self.app_cursor = None
  573. self.hover_shapes = None
  574. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  575. # setup the PlotCanvas
  576. self.on_plotcanvas_setup()
  577. end_plot_time = time.time()
  578. self.used_time = end_plot_time - start_plot_time
  579. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  580. if show_splash:
  581. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  582. "Canvas initialization started.\n"
  583. "Canvas initialization finished in"), '%.2f' % self.used_time),
  584. alignment=Qt.AlignBottom | Qt.AlignLeft,
  585. color=QtGui.QColor("gray"))
  586. self.ui.splitter.setStretchFactor(1, 2)
  587. # ###########################################################################################################
  588. # ############################################### SYS TRAY ##################################################
  589. # ###########################################################################################################
  590. if self.defaults["global_systray_icon"]:
  591. self.parent_w = QtWidgets.QWidget()
  592. if self.cmd_line_headless == 1:
  593. self.trayIcon = FlatCAMSystemTray(app=self,
  594. icon=QtGui.QIcon(self.resource_location +
  595. '/flatcam_icon32_green.png'),
  596. headless=True,
  597. parent=self.parent_w)
  598. else:
  599. self.trayIcon = FlatCAMSystemTray(app=self,
  600. icon=QtGui.QIcon(self.resource_location +
  601. '/flatcam_icon32_green.png'),
  602. parent=self.parent_w)
  603. # ###########################################################################################################
  604. # ############################################### Worker SETUP ##############################################
  605. # ###########################################################################################################
  606. if self.defaults["global_worker_number"]:
  607. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  608. else:
  609. self.workers = WorkerStack(workers_number=2)
  610. self.worker_task.connect(self.workers.add_task)
  611. self.log.debug("Finished creating Workers crew.")
  612. # ###########################################################################################################
  613. # ############################################# Activity Monitor ###########################################
  614. # ###########################################################################################################
  615. self.activity_view = FlatCAMActivityView(app=self)
  616. self.ui.infobar.addWidget(self.activity_view)
  617. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  618. # ###########################################################################################################
  619. # ############################################# Signal handling #############################################
  620. # ###########################################################################################################
  621. # ########################################## Custom signals ################################################
  622. # signal for displaying messages in status bar
  623. self.inform.connect(self.info)
  624. # signal to be called when the app is quiting
  625. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  626. self.message.connect(self.message_dialog)
  627. # self.progress.connect(self.set_progress_bar)
  628. # signals that are emitted when object state changes
  629. self.object_created.connect(self.on_object_created)
  630. self.object_changed.connect(self.on_object_changed)
  631. self.object_plotted.connect(self.on_object_plotted)
  632. self.plots_updated.connect(self.on_plots_updated)
  633. # signals emitted when file state change
  634. self.file_opened.connect(self.register_recent)
  635. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  636. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  637. # ########################################## Standard signals ###############################################
  638. # ### Menu
  639. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  640. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  641. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  642. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  643. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  644. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  645. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  646. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  647. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  648. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  649. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  650. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  651. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  652. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  653. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  654. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  655. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  656. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  657. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  658. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  659. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  660. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  661. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  662. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  663. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  664. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  665. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  666. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  667. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  668. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  669. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  670. self.ui.menufile_exit.triggered.connect(self.final_save)
  671. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  672. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  673. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  674. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  675. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  676. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  677. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  678. self.ui.menueditdelete.triggered.connect(self.on_delete)
  679. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  680. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  681. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  682. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  683. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  684. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  685. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  686. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  687. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  688. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  689. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  690. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  691. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  692. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  693. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  694. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  695. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  696. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  697. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  698. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  699. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  700. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  701. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  702. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  703. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  704. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  705. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  706. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  707. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  708. self.ui.menuview_replot.triggered.connect(self.plot_all)
  709. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  710. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  711. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  712. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  713. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  714. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  715. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  716. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  717. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  718. self.ui.menuview_toggle_hud.triggered.connect(self.on_toggle_hud)
  719. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  720. self.ui.menuhelp_about.triggered.connect(self.on_about)
  721. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  722. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  723. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  724. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  725. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  726. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  727. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  728. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  729. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  730. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  731. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  732. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  733. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  734. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  735. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  736. # ToolBar signals
  737. self.connect_toolbar_signals()
  738. # Notebook and Plot Tab Area signals
  739. # make the right click on the notebook tab and plot tab area tab raise a menu
  740. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  741. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  742. self.on_tab_setup_context_menu()
  743. # activate initial state
  744. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  745. # Context Menu
  746. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  747. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  748. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  749. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  750. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  751. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  752. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  753. self.ui.clearplot.triggered.connect(self.clear_plots)
  754. self.ui.replot.triggered.connect(self.plot_all)
  755. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  756. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  757. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  758. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  759. self.ui.popmenu_move.triggered.connect(self.obj_move)
  760. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  761. # Project Context Menu -> Color Setting
  762. for act in self.ui.menuprojectcolor.actions():
  763. act.triggered.connect(self.on_set_color_action_triggered)
  764. # ###########################################################################################################
  765. # #################################### GUI PREFERENCES SIGNALS ##############################################
  766. # ###########################################################################################################
  767. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  768. lambda: self.on_toggle_units(no_pref=False))
  769. # ##################################### Workspace Setting Signals ###########################################
  770. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  771. self.on_workspace_modified)
  772. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  773. self.on_workspace_modified
  774. )
  775. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  776. # ###########################################################################################################
  777. # ######################################## GUI SETTINGS SIGNALS #############################################
  778. # ###########################################################################################################
  779. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  780. # ######################################## Tools related signals ############################################
  781. # Film Tool
  782. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  783. self.on_film_color_entry)
  784. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  785. self.on_film_color_button)
  786. # QRCode Tool
  787. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  788. self.on_qrcode_fill_color_entry)
  789. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  790. self.on_qrcode_fill_color_button)
  791. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  792. self.on_qrcode_back_color_entry)
  793. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  794. self.on_qrcode_back_color_button)
  795. # portability changed signal
  796. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  797. # Object list
  798. self.collection.view.activated.connect(self.on_row_activated)
  799. self.collection.item_selected.connect(self.on_row_selected)
  800. self.object_status_changed.connect(self.on_collection_updated)
  801. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  802. # Export Excellon parameters.
  803. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  804. self.on_update_exc_export
  805. )
  806. # call it once to make sure it is updated at startup
  807. self.on_update_exc_export(state=self.defaults["excellon_update"])
  808. # when there are arguments at application startup this get launched
  809. self.args_at_startup[list].connect(self.on_startup_args)
  810. # ###########################################################################################################
  811. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  812. # ###########################################################################################################
  813. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  814. lambda: self.restore_extensions(ext_type='excellon'))
  815. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  816. lambda: self.restore_extensions(ext_type='gcode'))
  817. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  818. lambda: self.restore_extensions(ext_type='gerber'))
  819. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  820. lambda: self.delete_all_extensions(ext_type='excellon'))
  821. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  822. lambda: self.delete_all_extensions(ext_type='gcode'))
  823. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  824. lambda: self.delete_all_extensions(ext_type='gerber'))
  825. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  826. lambda: self.add_extension(ext_type='excellon'))
  827. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  828. lambda: self.add_extension(ext_type='gcode'))
  829. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  830. lambda: self.add_extension(ext_type='gerber'))
  831. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  832. lambda: self.del_extension(ext_type='excellon'))
  833. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  834. lambda: self.del_extension(ext_type='gcode'))
  835. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  836. lambda: self.del_extension(ext_type='gerber'))
  837. # connect the 'Apply' buttons from the Preferences/File Associations
  838. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  839. lambda: self.on_register_files(obj_type='excellon'))
  840. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  841. lambda: self.on_register_files(obj_type='gcode'))
  842. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  843. lambda: self.on_register_files(obj_type='gerber'))
  844. # ###########################################################################################################
  845. # ########################################### KEYWORDS SIGNALS ##############################################
  846. # ###########################################################################################################
  847. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  848. lambda: self.restore_extensions(ext_type='keyword'))
  849. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  850. lambda: self.delete_all_extensions(ext_type='keyword'))
  851. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  852. lambda: self.add_extension(ext_type='keyword'))
  853. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  854. lambda: self.del_extension(ext_type='keyword'))
  855. # connect the abort_all_tasks related slots to the related signals
  856. self.proc_container.idle_flag.connect(self.app_is_idle)
  857. # signal emitted when a tab is closed in the Plot Area
  858. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  859. # signal to close the application
  860. self.close_app_signal.connect(self.kill_app)
  861. # ################################# FINISHED CONNECTING SIGNALS #############################################
  862. # ###########################################################################################################
  863. # ###########################################################################################################
  864. # ###########################################################################################################
  865. self.log.debug("Finished connecting Signals.")
  866. # ###########################################################################################################
  867. # ########################################## Other setups ###################################################
  868. # ###########################################################################################################
  869. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  870. # depending on from where those tools are called different actions can be done
  871. self.call_source = 'app'
  872. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  873. self.tool_tab_locked = False
  874. # decide if to show or hide the Notebook side of the screen at startup
  875. if self.defaults["global_project_at_startup"] is True:
  876. self.ui.splitter.setSizes([1, 1])
  877. else:
  878. self.ui.splitter.setSizes([0, 1])
  879. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  880. self.setup_component_editor()
  881. # ###########################################################################################################
  882. # ####################################### Auto-complete KEYWORDS ############################################
  883. # ###########################################################################################################
  884. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  885. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  886. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  887. 'export_exc',
  888. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  889. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  890. 'interiors', 'isolate', 'join_excellon',
  891. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  892. 'mirror', 'ncc',
  893. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  894. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  895. 'options', 'origin',
  896. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  897. 'save', 'save_project',
  898. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  899. 'skew', 'subtract_poly', 'subtract_rectangle',
  900. 'version', 'write_gcode'
  901. ]
  902. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  903. 'Paste_1',
  904. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  905. 'Toolchange_manual', 'True', 'Users',
  906. 'all', 'auto', 'axis',
  907. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  908. 'contour', 'default',
  909. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  910. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  911. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  912. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  913. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  914. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  915. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  916. 'spacing_columns',
  917. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  918. 'toolchange_xy', 'toolchangez', 'travelz',
  919. 'tooldia', 'use_threads', 'value',
  920. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  921. ]
  922. self.tcl_keywords = [
  923. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  924. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  925. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  926. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  927. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  928. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  929. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  930. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  931. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  932. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  933. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  934. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  935. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  936. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  937. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  938. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  939. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  940. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  941. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  942. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  943. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  944. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  945. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  946. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  947. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  948. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  949. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  950. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  951. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  952. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  953. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  954. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  955. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  956. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  957. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  958. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  959. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  960. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  961. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  962. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  963. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  964. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  965. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  966. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  967. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  968. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  969. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  970. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  971. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  972. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  973. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  974. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  975. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  976. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  977. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  978. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  979. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  980. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  981. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  982. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  983. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  984. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  985. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  986. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  987. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  988. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  989. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  990. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  991. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  992. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  993. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  994. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  995. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  996. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  997. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  998. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  999. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1000. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1001. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1002. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1003. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1004. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1005. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1006. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1007. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1008. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1009. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1010. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1011. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1012. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1013. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1014. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1015. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1016. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1017. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1018. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1019. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1020. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1021. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1022. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1023. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1024. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1025. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1026. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1027. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1028. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1029. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1030. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1031. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1032. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1033. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1034. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1035. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1036. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1037. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1038. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1039. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1040. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1041. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1042. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1043. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1044. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1045. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1046. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1047. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1048. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1049. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1050. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1051. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1052. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1053. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1054. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1055. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1056. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1057. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1058. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1059. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1060. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1061. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1062. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1063. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1064. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1065. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1066. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1067. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1068. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1069. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1070. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1071. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1072. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1073. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1074. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1075. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1076. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1077. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1078. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1079. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1080. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1081. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1082. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1083. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1084. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1085. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1086. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1087. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1088. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1089. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1090. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1091. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1092. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1093. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1094. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1095. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1096. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1097. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1098. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1099. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1100. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1101. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1102. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1103. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1104. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1105. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1106. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1107. ]
  1108. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1109. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1110. # ###########################################################################################################
  1111. # ############################################## Shell SETUP ################################################
  1112. # ###########################################################################################################
  1113. self.shell = FCShell(app=self, version=self.version)
  1114. self.ui.shell_dock.setWidget(self.shell)
  1115. self.log.debug("TCL Shell has been initialized.")
  1116. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1117. if self.defaults["global_shell_at_startup"]:
  1118. self.ui.shell_dock.show()
  1119. else:
  1120. self.ui.shell_dock.hide()
  1121. # ###########################################################################################################
  1122. # ########################################## Tools and Plugins ##############################################
  1123. # ###########################################################################################################
  1124. self.dblsidedtool = None
  1125. self.distance_tool = None
  1126. self.distance_min_tool = None
  1127. self.panelize_tool = None
  1128. self.film_tool = None
  1129. self.paste_tool = None
  1130. self.calculator_tool = None
  1131. self.rules_tool = None
  1132. self.sub_tool = None
  1133. self.move_tool = None
  1134. self.cutout_tool = None
  1135. self.ncclear_tool = None
  1136. self.optimal_tool = None
  1137. self.paint_tool = None
  1138. self.transform_tool = None
  1139. self.properties_tool = None
  1140. self.pdf_tool = None
  1141. self.image_tool = None
  1142. self.pcb_wizard_tool = None
  1143. self.cal_exc_tool = None
  1144. self.qrcode_tool = None
  1145. self.copper_thieving_tool = None
  1146. self.fiducial_tool = None
  1147. self.edrills_tool = None
  1148. self.align_objects_tool = None
  1149. self.punch_tool = None
  1150. self.invert_tool = None
  1151. self.corners_tool = None
  1152. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1153. try:
  1154. self.install_tools()
  1155. except AttributeError as e:
  1156. log.debug("App.__init__() install tools() --> %s" % str(e))
  1157. # ###########################################################################################################
  1158. # ############################################ SETUP RECENT ITEMS ###########################################
  1159. # ###########################################################################################################
  1160. self.setup_recent_items()
  1161. # ###########################################################################################################
  1162. # ######################################### BookMarks Manager ###############################################
  1163. # ###########################################################################################################
  1164. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1165. self.install_bookmarks()
  1166. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1167. # ###########################################################################################################
  1168. # ########################################### Tools Database ################################################
  1169. # ###########################################################################################################
  1170. self.tools_db_tab = None
  1171. # ### System Font Parsing ###
  1172. # self.f_parse = ParseFont(self)
  1173. # self.parse_system_fonts()
  1174. # ###########################################################################################################
  1175. # ######################################### Check for updates ###############################################
  1176. # ###########################################################################################################
  1177. # Separate thread (Not worker)
  1178. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1179. if (self.beta is False or self.beta is None) and \
  1180. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1181. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1182. # self.thr2 = QtCore.QThread()
  1183. self.worker_task.emit({'fcn': self.version_check,
  1184. 'params': []})
  1185. # self.thr2.start(QtCore.QThread.LowPriority)
  1186. # ###########################################################################################################
  1187. # ##################################### Register files with FlatCAM; #######################################
  1188. # ################################### It works only for Windows for now ####################################
  1189. # ###########################################################################################################
  1190. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1191. self.on_register_files()
  1192. # ###########################################################################################################
  1193. # ######################################## Variables for global usage #######################################
  1194. # ###########################################################################################################
  1195. # hold the App units
  1196. self.units = 'MM'
  1197. # coordinates for relative position display
  1198. self.rel_point1 = (0, 0)
  1199. self.rel_point2 = (0, 0)
  1200. # variable to store coordinates
  1201. self.pos = (0, 0)
  1202. self.pos_canvas = (0, 0)
  1203. self.pos_jump = (0, 0)
  1204. # variable to store mouse coordinates
  1205. self.mouse = [0, 0]
  1206. # variable to store the delta positions on cavnas
  1207. self.dx = 0
  1208. self.dy = 0
  1209. # decide if we have a double click or single click
  1210. self.doubleclick = False
  1211. # store here the is_dragging value
  1212. self.event_is_dragging = False
  1213. # variable to store if a command is active (then the var is not None) and which one it is
  1214. self.command_active = None
  1215. # variable to store the status of moving selection action
  1216. # None value means that it's not an selection action
  1217. # True value = a selection from left to right
  1218. # False value = a selection from right to left
  1219. self.selection_type = None
  1220. # List to store the objects that are currently loaded in FlatCAM
  1221. # This list is updated on each object creation or object delete
  1222. self.all_objects_list = []
  1223. self.objects_under_the_click_list = []
  1224. # List to store the objects that are selected
  1225. self.sel_objects_list = []
  1226. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1227. self.key_modifiers = None
  1228. # Variable to hold the status of the axis
  1229. self.toggle_axis = True
  1230. # Variable to hold the status of the grid lines
  1231. self.toggle_grid_lines = True
  1232. # Variable to store the status of the fullscreen event
  1233. self.toggle_fscreen = False
  1234. # Variable to store the status of the code editor
  1235. self.toggle_codeeditor = False
  1236. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1237. self.click_noproject = False
  1238. self.cursor = None
  1239. # Variable to store the GCODE that was edited
  1240. self.gcode_edited = ""
  1241. self.text_editor_tab = None
  1242. # reference for the self.ui.code_editor
  1243. self.reference_code_editor = None
  1244. self.script_code = ''
  1245. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1246. self.tools_db_changed_flag = False
  1247. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1248. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1249. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1250. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1251. 'tsm']
  1252. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1253. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1254. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1255. 'sbp', 'tap', 'xpi']
  1256. self.svg_list = ['svg']
  1257. self.dxf_list = ['dxf']
  1258. self.pdf_list = ['pdf']
  1259. self.prj_list = ['flatprj']
  1260. self.conf_list = ['flatconfig']
  1261. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1262. # flag for polygons not cleared
  1263. self.poly_not_cleared = False
  1264. # VisPy visuals
  1265. self.isHovering = False
  1266. self.notHovering = True
  1267. # Window geometry
  1268. self.x_pos = None
  1269. self.y_pos = None
  1270. self.width = None
  1271. self.height = None
  1272. # when True, the app has to return from any thread
  1273. self.abort_flag = False
  1274. # set the value used in the Windows Title
  1275. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1276. # this holds a widget that is installed in the Plot Area when View Source option is used
  1277. self.source_editor_tab = None
  1278. self.pagesize = {}
  1279. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1280. # VisPy visuals
  1281. if self.is_legacy is False:
  1282. try:
  1283. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1284. except AttributeError:
  1285. self.tool_shapes = None
  1286. else:
  1287. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1288. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1289. # used in the delayed shutdown self.start_delayed_quit() method
  1290. self.save_timer = None
  1291. # ###########################################################################################################
  1292. # ################################## ADDING FlatCAM EDITORS section #########################################
  1293. # ###########################################################################################################
  1294. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1295. # at the first launch of the App , the editors will not be functional.
  1296. try:
  1297. self.geo_editor = FlatCAMGeoEditor(self)
  1298. except AttributeError:
  1299. pass
  1300. try:
  1301. self.exc_editor = FlatCAMExcEditor(self)
  1302. except AttributeError:
  1303. pass
  1304. try:
  1305. self.grb_editor = FlatCAMGrbEditor(self)
  1306. except AttributeError:
  1307. pass
  1308. self.log.debug("Finished adding FlatCAM Editor's.")
  1309. self.set_ui_title(name=_("New Project - Not saved"))
  1310. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1311. current_platform = platform.architecture()[0]
  1312. if current_platform != '64bit':
  1313. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1314. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1315. # ###########################################################################################################
  1316. # ########################################### EXCLUSION AREAS ###############################################
  1317. # ###########################################################################################################
  1318. self.exc_areas = ExclusionAreas(app=self)
  1319. # ###########################################################################################################
  1320. # ##################################### Finished the CONSTRUCTOR ############################################
  1321. # ###########################################################################################################
  1322. App.log.debug("END of constructor. Releasing control.")
  1323. # ###########################################################################################################
  1324. # ########################################## SHOW GUI #######################################################
  1325. # ###########################################################################################################
  1326. # if the app is not started as headless, show it
  1327. if self.cmd_line_headless != 1:
  1328. if show_splash:
  1329. # finish the splash
  1330. self.splash.finish(self.ui)
  1331. mgui_settings = QSettings("Open Source", "FlatCAM")
  1332. if mgui_settings.contains("maximized_gui"):
  1333. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1334. if maximized_ui is True:
  1335. self.ui.showMaximized()
  1336. else:
  1337. self.ui.show()
  1338. else:
  1339. self.ui.show()
  1340. if self.defaults["global_systray_icon"]:
  1341. self.trayIcon.show()
  1342. else:
  1343. log.warning("******************* RUNNING HEADLESS *******************")
  1344. # ###########################################################################################################
  1345. # ######################################## START-UP ARGUMENTS ###############################################
  1346. # ###########################################################################################################
  1347. # test if the program was started with a script as parameter
  1348. if self.cmd_line_shellvar:
  1349. try:
  1350. cnt = 0
  1351. command_tcl = 0
  1352. for i in self.cmd_line_shellvar.split(','):
  1353. if i is not None:
  1354. # noinspection PyBroadException
  1355. try:
  1356. command_tcl = eval(i)
  1357. except Exception:
  1358. command_tcl = i
  1359. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1360. cnt += 1
  1361. # if there are Windows paths then replace the path separator with a Unix like one
  1362. if sys.platform == 'win32':
  1363. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1364. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1365. except Exception as ext:
  1366. print("ERROR: ", ext)
  1367. sys.exit(2)
  1368. if self.cmd_line_shellfile:
  1369. if self.cmd_line_headless != 1:
  1370. if self.ui.shell_dock.isHidden():
  1371. self.ui.shell_dock.show()
  1372. try:
  1373. with open(self.cmd_line_shellfile, "r") as myfile:
  1374. # if show_splash:
  1375. # self.splash.showMessage('%s: %ssec\n%s' % (
  1376. # _("Canvas initialization started.\n"
  1377. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1378. # _("Executing Tcl Script ...")),
  1379. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1380. # color=QtGui.QColor("gray"))
  1381. cmd_line_shellfile_text = myfile.read()
  1382. if self.cmd_line_headless != 1:
  1383. self.shell.exec_command(cmd_line_shellfile_text)
  1384. else:
  1385. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1386. except Exception as ext:
  1387. print("ERROR: ", ext)
  1388. sys.exit(2)
  1389. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1390. # the path/file_name must be enclosed in quotes if it contain spaces
  1391. if App.args:
  1392. self.args_at_startup.emit(App.args)
  1393. if self.defaults.old_defaults_found is True:
  1394. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1395. "Please reboot the application to update."))
  1396. self.defaults.old_defaults_found = False
  1397. # ######################################### INIT FINISHED #######################################################
  1398. # #################################################################################################################
  1399. # #################################################################################################################
  1400. # #################################################################################################################
  1401. # #################################################################################################################
  1402. # #################################################################################################################
  1403. @staticmethod
  1404. def copy_and_overwrite(from_path, to_path):
  1405. """
  1406. From here:
  1407. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1408. :param from_path: source path
  1409. :param to_path: destination path
  1410. :return: None
  1411. """
  1412. if os.path.exists(to_path):
  1413. shutil.rmtree(to_path)
  1414. try:
  1415. shutil.copytree(from_path, to_path)
  1416. except FileNotFoundError:
  1417. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1418. shutil.copytree(from_new_path, to_path)
  1419. def on_startup_args(self, args, silent=False):
  1420. """
  1421. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1422. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1423. :param args: a list containing the application args at startup
  1424. :return: None
  1425. """
  1426. if args is not None:
  1427. args_to_process = args
  1428. else:
  1429. args_to_process = App.args
  1430. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1431. for argument in args_to_process:
  1432. if '.FlatPrj'.lower() in argument.lower():
  1433. try:
  1434. project_name = str(argument)
  1435. if project_name == "":
  1436. if silent is False:
  1437. self.inform.emit(_("Cancelled."))
  1438. else:
  1439. # self.open_project(project_name)
  1440. run_from_arg = True
  1441. # self.worker_task.emit({'fcn': self.open_project,
  1442. # 'params': [project_name, run_from_arg]})
  1443. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1444. except Exception as e:
  1445. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1446. elif '.FlatConfig'.lower() in argument.lower():
  1447. try:
  1448. file_name = str(argument)
  1449. if file_name == "":
  1450. if silent is False:
  1451. self.inform.emit(_("Open Config file failed."))
  1452. else:
  1453. run_from_arg = True
  1454. # self.worker_task.emit({'fcn': self.open_config_file,
  1455. # 'params': [file_name, run_from_arg]})
  1456. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1457. except Exception as e:
  1458. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1459. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1460. try:
  1461. file_name = str(argument)
  1462. if file_name == "":
  1463. if silent is False:
  1464. self.inform.emit(_("Open Script file failed."))
  1465. else:
  1466. if silent is False:
  1467. self.on_fileopenscript(name=file_name)
  1468. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1469. self.on_filerunscript(name=file_name)
  1470. except Exception as e:
  1471. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1472. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1473. log.debug("App.on_startup_args() --> Quit event.")
  1474. sys.exit()
  1475. elif 'save'.lower() in argument.lower():
  1476. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1477. self.preferencesUiManager.save_defaults()
  1478. else:
  1479. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1480. proc_arg = argument.lower()
  1481. for ext in exc_list:
  1482. proc_ext = ext.replace(' ', '')
  1483. proc_ext = '.%s' % proc_ext
  1484. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1485. file_name = str(argument)
  1486. if file_name == "":
  1487. if silent is False:
  1488. self.inform.emit(_("Open Excellon file failed."))
  1489. else:
  1490. self.on_fileopenexcellon(name=file_name, signal=None)
  1491. return
  1492. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1493. for ext in gco_list:
  1494. proc_ext = ext.replace(' ', '')
  1495. proc_ext = '.%s' % proc_ext
  1496. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1497. file_name = str(argument)
  1498. if file_name == "":
  1499. if silent is False:
  1500. self.inform.emit(_("Open GCode file failed."))
  1501. else:
  1502. self.on_fileopengcode(name=file_name, signal=None)
  1503. return
  1504. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1505. for ext in grb_list:
  1506. proc_ext = ext.replace(' ', '')
  1507. proc_ext = '.%s' % proc_ext
  1508. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1509. file_name = str(argument)
  1510. if file_name == "":
  1511. if silent is False:
  1512. self.inform.emit(_("Open Gerber file failed."))
  1513. else:
  1514. self.on_fileopengerber(name=file_name, signal=None)
  1515. return
  1516. # if it reached here without already returning then the app was registered with a file that it does not
  1517. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1518. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1519. # for arg in args_to_process:
  1520. # if 'FlatCAM.exe' in arg:
  1521. # continue
  1522. # else:
  1523. # sys.exit(2)
  1524. def set_ui_title(self, name):
  1525. """
  1526. Sets the title of the main window.
  1527. :param name: String that store the project path and project name
  1528. :return: None
  1529. """
  1530. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1531. (self.version,
  1532. ('BETA' if self.beta else ''),
  1533. platform.architecture()[0],
  1534. self.engine,
  1535. name)
  1536. )
  1537. def on_app_restart(self):
  1538. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1539. # be left in the SySTray
  1540. try:
  1541. self.trayIcon.hide()
  1542. except Exception:
  1543. pass
  1544. fcTranslate.restart_program(app=self)
  1545. def clear_pool(self):
  1546. """
  1547. Clear the multiprocessing pool and calls garbage collector.
  1548. :return: None
  1549. """
  1550. self.pool.close()
  1551. self.pool = Pool()
  1552. self.pool_recreated.emit(self.pool)
  1553. gc.collect()
  1554. def install_tools(self):
  1555. """
  1556. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1557. Instantiation of the Tools classes.
  1558. The order that the tools are installed is important as they can depend on each other install position.
  1559. :return: None
  1560. """
  1561. self.distance_tool = Distance(self)
  1562. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1563. before=self.ui.menueditorigin,
  1564. separator=False)
  1565. self.distance_min_tool = DistanceMin(self)
  1566. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1567. pos=self.ui.menuedit,
  1568. before=self.ui.menueditorigin,
  1569. separator=True)
  1570. self.dblsidedtool = DblSidedTool(self)
  1571. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1572. self.cal_exc_tool = ToolCalibration(self)
  1573. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1574. before=self.dblsidedtool.menuAction,
  1575. separator=False)
  1576. self.align_objects_tool = AlignObjects(self)
  1577. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1578. self.edrills_tool = ToolExtractDrills(self)
  1579. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1580. self.panelize_tool = Panelize(self)
  1581. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1582. self.film_tool = Film(self)
  1583. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1584. self.paste_tool = SolderPaste(self)
  1585. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1586. self.calculator_tool = ToolCalculator(self)
  1587. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1588. self.sub_tool = ToolSub(self)
  1589. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1590. pos=self.ui.menutool, separator=True)
  1591. self.rules_tool = RulesCheck(self)
  1592. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1593. pos=self.ui.menutool, separator=False)
  1594. self.optimal_tool = ToolOptimal(self)
  1595. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1596. pos=self.ui.menutool, separator=True)
  1597. self.move_tool = ToolMove(self)
  1598. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1599. before=self.ui.menueditorigin, separator=True)
  1600. self.cutout_tool = CutOut(self)
  1601. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1602. before=self.sub_tool.menuAction)
  1603. self.ncclear_tool = NonCopperClear(self)
  1604. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1605. before=self.sub_tool.menuAction, separator=True)
  1606. self.paint_tool = ToolPaint(self)
  1607. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1608. before=self.sub_tool.menuAction, separator=True)
  1609. self.copper_thieving_tool = ToolCopperThieving(self)
  1610. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1611. pos=self.ui.menutool)
  1612. self.fiducial_tool = ToolFiducials(self)
  1613. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1614. pos=self.ui.menutool)
  1615. self.qrcode_tool = QRCode(self)
  1616. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1617. pos=self.ui.menutool)
  1618. self.punch_tool = ToolPunchGerber(self)
  1619. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1620. self.invert_tool = ToolInvertGerber(self)
  1621. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1622. self.corners_tool = ToolCorners(self)
  1623. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1624. self.transform_tool = ToolTransform(self)
  1625. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1626. pos=self.ui.menuoptions, separator=True)
  1627. self.properties_tool = Properties(self)
  1628. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1629. pos=self.ui.menuoptions)
  1630. self.pdf_tool = ToolPDF(self)
  1631. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1632. pos=self.ui.menufileimport,
  1633. separator=True)
  1634. self.image_tool = ToolImage(self)
  1635. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1636. pos=self.ui.menufileimport,
  1637. separator=True)
  1638. self.pcb_wizard_tool = PcbWizard(self)
  1639. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1640. pos=self.ui.menufileimport)
  1641. self.log.debug("Tools are installed.")
  1642. def remove_tools(self):
  1643. """
  1644. Will remove all the actions in the Tool menu.
  1645. :return: None
  1646. """
  1647. for act in self.ui.menutool.actions():
  1648. self.ui.menutool.removeAction(act)
  1649. def init_tools(self):
  1650. """
  1651. Initialize the Tool tab in the notebook side of the central widget.
  1652. Remove the actions in the Tools menu.
  1653. Instantiate again the FlatCAM tools (plugins).
  1654. All this is required when changing the layout: standard, compact etc.
  1655. :return: None
  1656. """
  1657. log.debug("init_tools()")
  1658. # delete the data currently in the Tools Tab and the Tab itself
  1659. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1660. if widget is not None:
  1661. widget.deleteLater()
  1662. self.ui.notebook.removeTab(2)
  1663. # rebuild the Tools Tab
  1664. self.ui.tool_tab = QtWidgets.QWidget()
  1665. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1666. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1667. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1668. self.ui.tool_scroll_area = VerticalScrollArea()
  1669. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1670. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1671. # first remove all of them
  1672. self.remove_tools()
  1673. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1674. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1675. '&Command Line\tS')
  1676. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1677. # third install all of them
  1678. try:
  1679. self.install_tools()
  1680. except AttributeError:
  1681. pass
  1682. self.log.debug("Tools are initialized.")
  1683. # def parse_system_fonts(self):
  1684. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1685. # 'params': []})
  1686. def connect_toolbar_signals(self):
  1687. """
  1688. Reconnect the signals to the actions in the toolbar.
  1689. This has to be done each time after the FlatCAM tools are removed/installed.
  1690. :return: None
  1691. """
  1692. # Toolbar
  1693. # File Toolbar Signals
  1694. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1695. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1696. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1697. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1698. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1699. # View Toolbar Signals
  1700. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1701. self.ui.replot_btn.triggered.connect(self.plot_all)
  1702. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1703. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1704. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1705. # Edit Toolbar Signals
  1706. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1707. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1708. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1709. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1710. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1711. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1712. self.ui.delete_btn.triggered.connect(self.on_delete)
  1713. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1714. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1715. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1716. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1717. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1718. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1719. # Scripting Toolbar Signals
  1720. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1721. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1722. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1723. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1724. # Tools Toolbar Signals
  1725. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1726. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1727. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1728. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1729. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1730. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1731. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1732. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1733. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1734. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1735. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1736. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1737. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1738. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1739. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1740. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1741. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1742. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1743. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1744. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1745. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1746. def object2editor(self):
  1747. """
  1748. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1749. :return: None
  1750. """
  1751. self.defaults.report_usage("object2editor()")
  1752. # disable the objects menu as it may interfere with the Editors
  1753. self.ui.menuobjects.setDisabled(True)
  1754. edited_object = self.collection.get_active()
  1755. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1756. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1757. pass
  1758. else:
  1759. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1760. return
  1761. if isinstance(edited_object, GeometryObject):
  1762. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1763. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1764. # we set the notebook to hidden
  1765. # self.ui.splitter.setSizes([0, 1])
  1766. if edited_object.multigeo is True:
  1767. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1768. if len(sel_rows) > 1:
  1769. self.inform.emit('[WARNING_NOTCL] %s' %
  1770. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1771. "is not possible.\n"
  1772. "Edit only one geometry at a time."))
  1773. # determine the tool dia of the selected tool
  1774. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1775. # now find the key in the edited_object.tools that has this tooldia
  1776. multi_tool = 1
  1777. for tool in edited_object.tools:
  1778. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1779. multi_tool = tool
  1780. break
  1781. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1782. else:
  1783. self.geo_editor.edit_fcgeometry(edited_object)
  1784. # set call source to the Editor we go into
  1785. self.call_source = 'geo_editor'
  1786. elif isinstance(edited_object, ExcellonObject):
  1787. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1788. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1789. if self.ui.splitter.sizes()[0] == 0:
  1790. self.ui.splitter.setSizes([1, 1])
  1791. self.exc_editor.edit_fcexcellon(edited_object)
  1792. # set call source to the Editor we go into
  1793. self.call_source = 'exc_editor'
  1794. elif isinstance(edited_object, GerberObject):
  1795. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1796. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1797. if self.ui.splitter.sizes()[0] == 0:
  1798. self.ui.splitter.setSizes([1, 1])
  1799. self.grb_editor.edit_fcgerber(edited_object)
  1800. # set call source to the Editor we go into
  1801. self.call_source = 'grb_editor'
  1802. # reset the following variables so the UI is built again after edit
  1803. edited_object.ui_build = False
  1804. edited_object.build_aperture_storage = False
  1805. elif isinstance(edited_object, CNCJobObject):
  1806. if self.ui.splitter.sizes()[0] == 0:
  1807. self.ui.splitter.setSizes([1, 1])
  1808. edited_object.on_edit_code_click()
  1809. return
  1810. # make sure that we can't select another object while in Editor Mode:
  1811. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1812. self.ui.project_frame.setDisabled(True)
  1813. # delete any selection shape that might be active as they are not relevant in Editor
  1814. self.delete_selection_shape()
  1815. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1816. self.ui.plot_tab_area.protectTab(0)
  1817. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1818. self.should_we_save = True
  1819. def editor2object(self, cleanup=None):
  1820. """
  1821. Transfers the Geometry or Excellon from it's editor to the current object.
  1822. :return: None
  1823. """
  1824. self.defaults.report_usage("editor2object()")
  1825. # re-enable the objects menu that was disabled on entry in Editor mode
  1826. self.ui.menuobjects.setDisabled(False)
  1827. # do not update a geometry or excellon object unless it comes out of an editor
  1828. if self.call_source != 'app':
  1829. edited_obj = self.collection.get_active()
  1830. if cleanup is None:
  1831. msgbox = QtWidgets.QMessageBox()
  1832. msgbox.setText(_("Do you want to save the edited object?"))
  1833. msgbox.setWindowTitle(_("Close Editor"))
  1834. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1835. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1836. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1837. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1838. msgbox.setDefaultButton(bt_yes)
  1839. msgbox.exec_()
  1840. response = msgbox.clickedButton()
  1841. if response == bt_yes:
  1842. # clean the Tools Tab
  1843. self.ui.tool_scroll_area.takeWidget()
  1844. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1845. self.ui.notebook.setTabText(2, "Tool")
  1846. if isinstance(edited_obj, GeometryObject):
  1847. obj_type = "Geometry"
  1848. if cleanup is None:
  1849. self.geo_editor.update_fcgeometry(edited_obj)
  1850. # self.geo_editor.update_options(edited_obj)
  1851. self.geo_editor.deactivate()
  1852. # restore GUI to the Selected TAB
  1853. # Remove anything else in the GUI
  1854. self.ui.tool_scroll_area.takeWidget()
  1855. # update the geo object options so it is including the bounding box values
  1856. try:
  1857. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1858. edited_obj.options['xmin'] = xmin
  1859. edited_obj.options['ymin'] = ymin
  1860. edited_obj.options['xmax'] = xmax
  1861. edited_obj.options['ymax'] = ymax
  1862. except AttributeError as e:
  1863. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1864. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1865. edited_obj.build_ui()
  1866. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1867. elif isinstance(edited_obj, GerberObject):
  1868. obj_type = "Gerber"
  1869. if cleanup is None:
  1870. self.grb_editor.update_fcgerber()
  1871. self.grb_editor.update_options(edited_obj)
  1872. self.grb_editor.deactivate_grb_editor()
  1873. # delete the old object (the source object) if it was an empty one
  1874. try:
  1875. if len(edited_obj.solid_geometry) == 0:
  1876. old_name = edited_obj.options['name']
  1877. self.collection.set_active(old_name)
  1878. self.collection.delete_active()
  1879. except TypeError:
  1880. # if the solid_geometry is a single Polygon the len() will not work
  1881. # in any case, falling here means that we have something in the solid_geometry, even if only
  1882. # a single Polygon, therefore we pass this
  1883. pass
  1884. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1885. # restore GUI to the Selected TAB
  1886. # Remove anything else in the GUI
  1887. self.ui.selected_scroll_area.takeWidget()
  1888. elif isinstance(edited_obj, ExcellonObject):
  1889. obj_type = "Excellon"
  1890. if cleanup is None:
  1891. self.exc_editor.update_fcexcellon(edited_obj)
  1892. # self.exc_editor.update_options(edited_obj)
  1893. self.exc_editor.deactivate()
  1894. # restore GUI to the Selected TAB
  1895. # Remove anything else in the GUI
  1896. self.ui.tool_scroll_area.takeWidget()
  1897. # delete the old object (the source object) if it was an empty one
  1898. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1899. old_name = edited_obj.options['name']
  1900. self.collection.delete_by_name(name=old_name)
  1901. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1902. else:
  1903. self.inform.emit('[WARNING_NOTCL] %s' %
  1904. _("Select a Gerber, Geometry or Excellon Object to update."))
  1905. return
  1906. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1907. elif response == bt_no:
  1908. # clean the Tools Tab
  1909. self.ui.tool_scroll_area.takeWidget()
  1910. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1911. self.ui.notebook.setTabText(2, "Tool")
  1912. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1913. if isinstance(edited_obj, GeometryObject):
  1914. self.geo_editor.deactivate()
  1915. edited_obj.build_ui()
  1916. elif isinstance(edited_obj, GerberObject):
  1917. self.grb_editor.deactivate_grb_editor()
  1918. edited_obj.build_ui()
  1919. elif isinstance(edited_obj, ExcellonObject):
  1920. self.exc_editor.deactivate()
  1921. edited_obj.build_ui()
  1922. else:
  1923. self.inform.emit('[WARNING_NOTCL] %s' %
  1924. _("Select a Gerber, Geometry or Excellon Object to update."))
  1925. return
  1926. elif response == bt_cancel:
  1927. return
  1928. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1929. # edited_obj.build_ui()
  1930. # Switch notebook to Selected page
  1931. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1932. else:
  1933. if isinstance(edited_obj, GeometryObject):
  1934. self.geo_editor.deactivate()
  1935. elif isinstance(edited_obj, GerberObject):
  1936. self.grb_editor.deactivate_grb_editor()
  1937. elif isinstance(edited_obj, ExcellonObject):
  1938. self.exc_editor.deactivate()
  1939. else:
  1940. self.inform.emit('[WARNING_NOTCL] %s' %
  1941. _("Select a Gerber, Geometry or Excellon Object to update."))
  1942. return
  1943. # if notebook is hidden we show it
  1944. if self.ui.splitter.sizes()[0] == 0:
  1945. self.ui.splitter.setSizes([1, 1])
  1946. # restore the call_source to app
  1947. self.call_source = 'app'
  1948. edited_obj.plot()
  1949. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1950. self.ui.plot_tab_area.protectTab(0)
  1951. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1952. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1953. self.ui.project_frame.setDisabled(False)
  1954. def get_last_folder(self):
  1955. """
  1956. Get the folder path from where the last file was opened.
  1957. :return: String, last opened folder path
  1958. """
  1959. return self.defaults["global_last_folder"]
  1960. def get_last_save_folder(self):
  1961. """
  1962. Get the folder path from where the last file was saved.
  1963. :return: String, last saved folder path
  1964. """
  1965. loc = self.defaults["global_last_save_folder"]
  1966. if loc is None:
  1967. loc = self.defaults["global_last_folder"]
  1968. if loc is None:
  1969. loc = os.path.dirname(__file__)
  1970. return loc
  1971. def info(self, msg):
  1972. """
  1973. Informs the user. Normally on the status bar, optionally
  1974. also on the shell.
  1975. :param msg: Text to write.
  1976. :return: None
  1977. """
  1978. # Type of message in brackets at the beginning of the message.
  1979. match = re.search(r"\[(.*)\](.*)", msg)
  1980. if match:
  1981. level = match.group(1)
  1982. msg_ = match.group(2)
  1983. self.ui.fcinfo.set_status(str(msg_), level=level)
  1984. if level.lower() == "error":
  1985. self.shell_message(msg, error=True, show=True)
  1986. elif level.lower() == "warning":
  1987. self.shell_message(msg, warning=True, show=True)
  1988. elif level.lower() == "error_notcl":
  1989. self.shell_message(msg, error=True, show=False)
  1990. elif level.lower() == "warning_notcl":
  1991. self.shell_message(msg, warning=True, show=False)
  1992. elif level.lower() == "success":
  1993. self.shell_message(msg, success=True, show=False)
  1994. elif level.lower() == "selected":
  1995. self.shell_message(msg, selected=True, show=False)
  1996. else:
  1997. self.shell_message(msg, show=False)
  1998. else:
  1999. self.ui.fcinfo.set_status(str(msg), level="info")
  2000. # make sure that if the message is to clear the infobar with a space
  2001. # is not printed over and over on the shell
  2002. if msg != '':
  2003. self.shell_message(msg)
  2004. def restore_toolbar_view(self):
  2005. """
  2006. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2007. was saved in the defaults dictionary.
  2008. :return: None
  2009. """
  2010. tb = self.defaults["global_toolbar_view"]
  2011. if tb & 1:
  2012. self.ui.toolbarfile.setVisible(True)
  2013. else:
  2014. self.ui.toolbarfile.setVisible(False)
  2015. if tb & 2:
  2016. self.ui.toolbargeo.setVisible(True)
  2017. else:
  2018. self.ui.toolbargeo.setVisible(False)
  2019. if tb & 4:
  2020. self.ui.toolbarview.setVisible(True)
  2021. else:
  2022. self.ui.toolbarview.setVisible(False)
  2023. if tb & 8:
  2024. self.ui.toolbartools.setVisible(True)
  2025. else:
  2026. self.ui.toolbartools.setVisible(False)
  2027. if tb & 16:
  2028. self.ui.exc_edit_toolbar.setVisible(True)
  2029. else:
  2030. self.ui.exc_edit_toolbar.setVisible(False)
  2031. if tb & 32:
  2032. self.ui.geo_edit_toolbar.setVisible(True)
  2033. else:
  2034. self.ui.geo_edit_toolbar.setVisible(False)
  2035. if tb & 64:
  2036. self.ui.grb_edit_toolbar.setVisible(True)
  2037. else:
  2038. self.ui.grb_edit_toolbar.setVisible(False)
  2039. # if tb & 128:
  2040. # self.ui.snap_toolbar.setVisible(True)
  2041. # else:
  2042. # self.ui.snap_toolbar.setVisible(False)
  2043. # Grid Toolbar is always active now
  2044. self.ui.snap_toolbar.setVisible(True)
  2045. if tb & 256:
  2046. self.ui.toolbarshell.setVisible(True)
  2047. else:
  2048. self.ui.toolbarshell.setVisible(False)
  2049. def on_import_preferences(self):
  2050. """
  2051. Loads the application default settings from a saved file into
  2052. ``self.defaults`` dictionary.
  2053. :return: None
  2054. """
  2055. self.defaults.report_usage("on_import_preferences")
  2056. App.log.debug("App.on_import_preferences()")
  2057. # Show file chooser
  2058. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2059. try:
  2060. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2061. directory=self.data_path,
  2062. filter=filter_)
  2063. except TypeError:
  2064. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2065. filter=filter_)
  2066. filename = str(filename)
  2067. if filename == "":
  2068. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2069. return
  2070. # Load in the defaults from the chosen file
  2071. self.defaults.load(filename=filename)
  2072. self.preferencesUiManager.on_preferences_edited()
  2073. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2074. def on_export_preferences(self):
  2075. """
  2076. Save the defaults dictionary to a file.
  2077. :return: None
  2078. """
  2079. self.defaults.report_usage("on_export_preferences")
  2080. App.log.debug("on_export_preferences()")
  2081. # defaults_file_content = None
  2082. # Show file chooser
  2083. date = str(datetime.today()).rpartition('.')[0]
  2084. date = ''.join(c for c in date if c not in ':-')
  2085. date = date.replace(' ', '_')
  2086. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2087. try:
  2088. filename, _f = FCFileSaveDialog.get_saved_filename(
  2089. caption=_("Export FlatCAM Preferences"),
  2090. directory=self.data_path + '/preferences_' + date,
  2091. filter=filter__
  2092. )
  2093. except TypeError:
  2094. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2095. filename = str(filename)
  2096. if filename == "":
  2097. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2098. return
  2099. # Update options
  2100. self.preferencesUiManager.defaults_read_form()
  2101. self.defaults.propagate_defaults()
  2102. # Save update options
  2103. try:
  2104. self.defaults.write(filename=filename)
  2105. except Exception:
  2106. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2107. return
  2108. if self.defaults["global_open_style"] is False:
  2109. self.file_opened.emit("preferences", filename)
  2110. self.file_saved.emit("preferences", filename)
  2111. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2112. def save_to_file(self, content_to_save, txt_content):
  2113. """
  2114. Save something to a file.
  2115. :return: None
  2116. """
  2117. self.defaults.report_usage("save_to_file")
  2118. App.log.debug("save_to_file()")
  2119. self.date = str(datetime.today()).rpartition('.')[0]
  2120. self.date = ''.join(c for c in self.date if c not in ':-')
  2121. self.date = self.date.replace(' ', '_')
  2122. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2123. path_to_save = self.defaults["global_last_save_folder"] if \
  2124. self.defaults["global_last_save_folder"] is not None else self.data_path
  2125. try:
  2126. filename, _f = FCFileSaveDialog.get_saved_filename(
  2127. caption=_("Save to file"),
  2128. directory=path_to_save + '/file_' + self.date,
  2129. filter=filter__
  2130. )
  2131. except TypeError:
  2132. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2133. filename = str(filename)
  2134. if filename == "":
  2135. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2136. return
  2137. else:
  2138. try:
  2139. with open(filename, 'w') as f:
  2140. ___ = f.read()
  2141. except PermissionError:
  2142. self.inform.emit('[WARNING] %s' %
  2143. _("Permission denied, saving not possible.\n"
  2144. "Most likely another app is holding the file open and not accessible."))
  2145. return
  2146. except IOError:
  2147. App.log.debug('Creating a new file ...')
  2148. f = open(filename, 'w')
  2149. f.close()
  2150. except Exception:
  2151. e = sys.exc_info()[0]
  2152. App.log.error("Could not load the file.")
  2153. App.log.error(str(e))
  2154. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2155. return
  2156. # Save content
  2157. if filename.rpartition('.')[2].lower() == 'html':
  2158. file_content = content_to_save
  2159. else:
  2160. file_content = txt_content
  2161. try:
  2162. with open(filename, "w") as f:
  2163. f.write(file_content)
  2164. except Exception:
  2165. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2166. return
  2167. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2168. def save_geometry(self, x, y, width, height, notebook_width):
  2169. """
  2170. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2171. launch of the application.
  2172. :param x: X position of the main window
  2173. :param y: Y position of the main window
  2174. :param width: width of the main window
  2175. :param height: height of the main window
  2176. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2177. :return: None
  2178. """
  2179. self.defaults["global_def_win_x"] = x
  2180. self.defaults["global_def_win_y"] = y
  2181. self.defaults["global_def_win_w"] = width
  2182. self.defaults["global_def_win_h"] = height
  2183. self.defaults["global_def_notebook_width"] = notebook_width
  2184. self.preferencesUiManager.save_defaults()
  2185. def restore_main_win_geom(self):
  2186. try:
  2187. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2188. self.defaults["global_def_win_y"],
  2189. self.defaults["global_def_win_w"],
  2190. self.defaults["global_def_win_h"])
  2191. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2192. except KeyError as e:
  2193. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2194. def message_dialog(self, title, message, kind="info"):
  2195. """
  2196. Builds and show a custom QMessageBox to be used in FlatCAM.
  2197. :param title: title of the QMessageBox
  2198. :param message: message to be displayed
  2199. :param kind: type of QMessageBox; will display a specific icon.
  2200. :return:
  2201. """
  2202. icon = {"info": QtWidgets.QMessageBox.Information,
  2203. "warning": QtWidgets.QMessageBox.Warning,
  2204. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2205. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2206. dlg.setText(message)
  2207. dlg.exec_()
  2208. def register_recent(self, kind, filename):
  2209. """
  2210. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2211. dictionary.
  2212. :param kind: type of file that was opened
  2213. :param filename: the path and file name for the file that was opened
  2214. :return:
  2215. """
  2216. self.log.debug("register_recent()")
  2217. self.log.debug(" %s" % kind)
  2218. self.log.debug(" %s" % filename)
  2219. record = {'kind': str(kind), 'filename': str(filename)}
  2220. if record in self.recent:
  2221. return
  2222. if record in self.recent_projects:
  2223. return
  2224. if record['kind'] == 'project':
  2225. self.recent_projects.insert(0, record)
  2226. else:
  2227. self.recent.insert(0, record)
  2228. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2229. self.recent.pop()
  2230. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2231. self.recent_projects.pop()
  2232. try:
  2233. f = open(self.data_path + '/recent.json', 'w')
  2234. except IOError:
  2235. App.log.error("Failed to open recent items file for writing.")
  2236. self.inform.emit('[ERROR_NOTCL] %s' %
  2237. _('Failed to open recent files file for writing.'))
  2238. return
  2239. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2240. f.close()
  2241. try:
  2242. fp = open(self.data_path + '/recent_projects.json', 'w')
  2243. except IOError:
  2244. App.log.error("Failed to open recent items file for writing.")
  2245. self.inform.emit('[ERROR_NOTCL] %s' %
  2246. _('Failed to open recent projects file for writing.'))
  2247. return
  2248. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2249. fp.close()
  2250. # Re-build the recent items menu
  2251. self.setup_recent_items()
  2252. def new_object(self, kind, name, initialize, plot=True, autoselected=True):
  2253. """
  2254. Creates a new specialized FlatCAMObj and attaches it to the application,
  2255. this is, updates the GUI accordingly, any other records and plots it.
  2256. This method is thread-safe.
  2257. Notes:
  2258. * If the name is in use, the self.collection will modify it
  2259. when appending it to the collection. There is no need to handle
  2260. name conflicts here.
  2261. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2262. :type kind: str
  2263. :param name: Name for the object.
  2264. :type name: str
  2265. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2266. The function is called with 2 parameters: the new object and the App instance.
  2267. :type initialize: function
  2268. :param plot: If to plot the resulting object
  2269. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2270. self.collection
  2271. :return: None
  2272. :rtype: None
  2273. """
  2274. App.log.debug("new_object()")
  2275. obj_plot = plot
  2276. obj_autoselected = autoselected
  2277. t0 = time.time() # Debug
  2278. # ## Create object
  2279. classdict = {
  2280. "gerber": GerberObject,
  2281. "excellon": ExcellonObject,
  2282. "cncjob": CNCJobObject,
  2283. "geometry": GeometryObject,
  2284. "script": ScriptObject,
  2285. "document": DocumentObject
  2286. }
  2287. App.log.debug("Calling object constructor...")
  2288. # Object creation/instantiation
  2289. obj = classdict[kind](name)
  2290. obj.units = self.options["units"]
  2291. # IMPORTANT
  2292. # The key names in defaults and options dictionary's are not random:
  2293. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2294. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2295. # copied to self.options. After that, below, depending on the type of
  2296. # object that is created, it will strip the name of the object and the underline (if the original key was
  2297. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2298. # "toolchange"
  2299. for option in self.options:
  2300. if option.find(kind + "_") == 0:
  2301. oname = option[len(kind) + 1:]
  2302. obj.options[oname] = self.options[option]
  2303. obj.isHovering = False
  2304. obj.notHovering = True
  2305. # Initialize as per user request
  2306. # User must take care to implement initialize
  2307. # in a thread-safe way as is is likely that we
  2308. # have been invoked in a separate thread.
  2309. t1 = time.time()
  2310. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2311. try:
  2312. return_value = initialize(obj, self)
  2313. except Exception as e:
  2314. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2315. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2316. msg += traceback.format_exc()
  2317. self.inform.emit(msg)
  2318. return "fail"
  2319. t2 = time.time()
  2320. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2321. if return_value == 'fail':
  2322. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2323. return "fail"
  2324. # Check units and convert if necessary
  2325. # This condition CAN be true because initialize() can change obj.units
  2326. if self.options["units"].upper() != obj.units.upper():
  2327. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2328. obj.convert_units(self.options["units"])
  2329. t3 = time.time()
  2330. self.log.debug("%f seconds converting units." % (t3 - t2))
  2331. # Create the bounding box for the object and then add the results to the obj.options
  2332. # But not for Scripts or for Documents
  2333. if kind != 'document' and kind != 'script':
  2334. try:
  2335. xmin, ymin, xmax, ymax = obj.bounds()
  2336. obj.options['xmin'] = xmin
  2337. obj.options['ymin'] = ymin
  2338. obj.options['xmax'] = xmax
  2339. obj.options['ymax'] = ymax
  2340. except Exception as e:
  2341. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2342. return "fail"
  2343. try:
  2344. if kind == 'excellon':
  2345. obj.fill_color = self.defaults["excellon_plot_fill"]
  2346. obj.outline_color = self.defaults["excellon_plot_line"]
  2347. if kind == 'gerber':
  2348. obj.fill_color = self.defaults["gerber_plot_fill"]
  2349. obj.outline_color = self.defaults["gerber_plot_line"]
  2350. except Exception as e:
  2351. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2352. # update the KeyWords list with the name of the file
  2353. self.myKeywords.append(obj.options['name'])
  2354. log.debug("Moving new object back to main thread.")
  2355. # Move the object to the main thread and let the app know that it is available.
  2356. obj.moveToThread(self.main_thread)
  2357. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2358. return obj
  2359. def new_excellon_object(self):
  2360. """
  2361. Creates a new, blank Excellon object.
  2362. :return: None
  2363. """
  2364. self.defaults.report_usage("new_excellon_object()")
  2365. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2366. def new_geometry_object(self):
  2367. """
  2368. Creates a new, blank and single-tool Geometry object.
  2369. :return: None
  2370. """
  2371. self.defaults.report_usage("new_geometry_object()")
  2372. def initialize(obj, app):
  2373. obj.multitool = False
  2374. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2375. def new_gerber_object(self):
  2376. """
  2377. Creates a new, blank Gerber object.
  2378. :return: None
  2379. """
  2380. self.defaults.report_usage("new_gerber_object()")
  2381. def initialize(grb_obj, app):
  2382. grb_obj.multitool = False
  2383. grb_obj.source_file = []
  2384. grb_obj.multigeo = False
  2385. grb_obj.follow = False
  2386. grb_obj.apertures = {}
  2387. grb_obj.solid_geometry = []
  2388. try:
  2389. grb_obj.options['xmin'] = 0
  2390. grb_obj.options['ymin'] = 0
  2391. grb_obj.options['xmax'] = 0
  2392. grb_obj.options['ymax'] = 0
  2393. except KeyError:
  2394. pass
  2395. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2396. def new_script_object(self):
  2397. """
  2398. Creates a new, blank TCL Script object.
  2399. :return: None
  2400. """
  2401. self.defaults.report_usage("new_script_object()")
  2402. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2403. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2404. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2405. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2406. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2407. # "ListSys, MillDrills,\n" \
  2408. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2409. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2410. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2411. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2412. # "# SubtractRectangle, Version, WriteGCode\n"
  2413. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2414. '# %s:\n' % _('TCL Tutorial is here') + \
  2415. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2416. '# %s:\n' % _("FlatCAM commands list")
  2417. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2418. "(displayed in Tcl Shell).")
  2419. def initialize(obj, app):
  2420. obj.source_file = deepcopy(new_source_file)
  2421. outname = 'new_script'
  2422. self.new_object('script', outname, initialize, plot=False)
  2423. def new_document_object(self):
  2424. """
  2425. Creates a new, blank Document object.
  2426. :return: None
  2427. """
  2428. self.defaults.report_usage("new_document_object()")
  2429. def initialize(obj, app):
  2430. obj.source_file = ""
  2431. self.new_object('document', 'new_document', initialize, plot=False)
  2432. def on_object_created(self, obj, plot, auto_select):
  2433. """
  2434. Event callback for object creation.
  2435. It will add the new object to the collection. After that it will plot the object in a threaded way
  2436. :param obj: The newly created FlatCAM object.
  2437. :param plot: if the newly create object t obe plotted
  2438. :param auto_select: if the newly created object to be autoselected after creation
  2439. :return: None
  2440. """
  2441. t0 = time.time() # DEBUG
  2442. self.log.debug("on_object_created()")
  2443. # The Collection might change the name if there is a collision
  2444. self.collection.append(obj)
  2445. # after adding the object to the collection always update the list of objects that are in the collection
  2446. self.all_objects_list = self.collection.get_list()
  2447. # self.inform.emit('[selected] %s created & selected: %s' %
  2448. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2449. if obj.kind == 'gerber':
  2450. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2451. kind=obj.kind.capitalize(),
  2452. color='green',
  2453. name=str(obj.options['name']), tx=_("created/selected"))
  2454. )
  2455. elif obj.kind == 'excellon':
  2456. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2457. kind=obj.kind.capitalize(),
  2458. color='brown',
  2459. name=str(obj.options['name']), tx=_("created/selected"))
  2460. )
  2461. elif obj.kind == 'cncjob':
  2462. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2463. kind=obj.kind.capitalize(),
  2464. color='blue',
  2465. name=str(obj.options['name']), tx=_("created/selected"))
  2466. )
  2467. elif obj.kind == 'geometry':
  2468. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2469. kind=obj.kind.capitalize(),
  2470. color='red',
  2471. name=str(obj.options['name']), tx=_("created/selected"))
  2472. )
  2473. elif obj.kind == 'script':
  2474. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2475. kind=obj.kind.capitalize(),
  2476. color='orange',
  2477. name=str(obj.options['name']), tx=_("created/selected"))
  2478. )
  2479. elif obj.kind == 'document':
  2480. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2481. kind=obj.kind.capitalize(),
  2482. color='darkCyan',
  2483. name=str(obj.options['name']), tx=_("created/selected"))
  2484. )
  2485. # update the SHELL auto-completer model with the name of the new object
  2486. self.shell._edit.set_model_data(self.myKeywords)
  2487. if auto_select:
  2488. # select the just opened object but deselect the previous ones
  2489. self.collection.set_all_inactive()
  2490. self.collection.set_active(obj.options["name"])
  2491. else:
  2492. self.collection.set_all_inactive()
  2493. # here it is done the object plotting
  2494. def worker_task(t_obj):
  2495. with self.proc_container.new(_("Plotting")):
  2496. if isinstance(t_obj, CNCJobObject):
  2497. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2498. else:
  2499. t_obj.plot()
  2500. t1 = time.time() # DEBUG
  2501. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2502. self.object_plotted.emit(t_obj)
  2503. # Send to worker
  2504. # self.worker.add_task(worker_task, [self])
  2505. if plot is True:
  2506. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2507. def on_object_changed(self, obj):
  2508. """
  2509. Called whenever the geometry of the object was changed in some way.
  2510. This require the update of it's bounding values so it can be the selected on canvas.
  2511. Update the bounding box data from obj.options
  2512. :param obj: the object that was changed
  2513. :return: None
  2514. """
  2515. try:
  2516. xmin, ymin, xmax, ymax = obj.bounds()
  2517. except TypeError:
  2518. return
  2519. obj.options['xmin'] = xmin
  2520. obj.options['ymin'] = ymin
  2521. obj.options['xmax'] = xmax
  2522. obj.options['ymax'] = ymax
  2523. log.debug("Object changed, updating the bounding box data on self.options")
  2524. # delete the old selection shape
  2525. self.delete_selection_shape()
  2526. self.should_we_save = True
  2527. def on_object_plotted(self):
  2528. """
  2529. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2530. :return: None
  2531. """
  2532. self.on_zoom_fit(None)
  2533. def on_about(self):
  2534. """
  2535. Displays the "about" dialog found in the Menu --> Help.
  2536. :return: None
  2537. """
  2538. self.defaults.report_usage("on_about")
  2539. version = self.version
  2540. version_date = self.version_date
  2541. beta = self.beta
  2542. class AboutDialog(QtWidgets.QDialog):
  2543. def __init__(self, app, parent=None):
  2544. QtWidgets.QDialog.__init__(self, parent)
  2545. self.app = app
  2546. # Icon and title
  2547. self.setWindowIcon(parent.app_icon)
  2548. self.setWindowTitle(_("About FlatCAM"))
  2549. self.resize(600, 200)
  2550. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2551. # self.setStyleSheet(
  2552. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2553. # "background-attachment: fixed"
  2554. # )
  2555. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2556. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2557. # palette = QtGui.QPalette()
  2558. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2559. # self.setPalette(palette)
  2560. logo = QtWidgets.QLabel()
  2561. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2562. title = QtWidgets.QLabel(
  2563. "<font size=8><B>FlatCAM</B></font><BR>"
  2564. "{title}<BR>"
  2565. "<BR>"
  2566. "<BR>"
  2567. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2568. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2569. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2570. "<B>{issue}</B></a><BR>".format(
  2571. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2572. devel=_("Development"),
  2573. down=_("DOWNLOAD"),
  2574. issue=_("Issue tracker"))
  2575. )
  2576. title.setOpenExternalLinks(True)
  2577. closebtn = QtWidgets.QPushButton(_("Close"))
  2578. tab_widget = QtWidgets.QTabWidget()
  2579. description_label = QtWidgets.QLabel(
  2580. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2581. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2582. version=version,
  2583. beta=('BETA' if beta else ''),
  2584. date=version_date,
  2585. arch=platform.architecture()[0])
  2586. )
  2587. description_label.setOpenExternalLinks(True)
  2588. lic_lbl_header = QtWidgets.QLabel(
  2589. '%s:<br>%s<br>' % (
  2590. _('Licensed under the MIT license'),
  2591. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2592. "http://www.opensource.org/licenses/mit-license.php</a>"
  2593. )
  2594. )
  2595. lic_lbl_header.setOpenExternalLinks(True)
  2596. lic_lbl_body = QtWidgets.QLabel(
  2597. _(
  2598. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2599. 'of this software and associated documentation files (the "Software"), to deal\n'
  2600. 'in the Software without restriction, including without limitation the rights\n'
  2601. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2602. 'copies of the Software, and to permit persons to whom the Software is\n'
  2603. 'furnished to do so, subject to the following conditions:\n\n'
  2604. 'The above copyright notice and this permission notice shall be included in\n'
  2605. 'all copies or substantial portions of the Software.\n\n'
  2606. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2607. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2608. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2609. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2610. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2611. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2612. 'THE SOFTWARE.'
  2613. )
  2614. )
  2615. attributions_label = QtWidgets.QLabel(
  2616. _(
  2617. 'Some of the icons used are from the following sources:<br>'
  2618. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2619. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2620. 'title="Flaticon">www.flaticon.com</a></div>'
  2621. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2622. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2623. )
  2624. )
  2625. attributions_label.setOpenExternalLinks(True)
  2626. # layouts
  2627. layout1 = QtWidgets.QVBoxLayout()
  2628. layout1_1 = QtWidgets.QHBoxLayout()
  2629. layout1_2 = QtWidgets.QHBoxLayout()
  2630. layout2 = QtWidgets.QHBoxLayout()
  2631. layout3 = QtWidgets.QHBoxLayout()
  2632. self.setLayout(layout1)
  2633. layout1.addLayout(layout1_1)
  2634. layout1.addLayout(layout1_2)
  2635. layout1.addLayout(layout2)
  2636. layout1.addLayout(layout3)
  2637. layout1_1.addStretch()
  2638. layout1_1.addWidget(description_label)
  2639. layout1_2.addWidget(tab_widget)
  2640. self.splash_tab = QtWidgets.QWidget()
  2641. self.splash_tab.setObjectName("splash_about")
  2642. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2643. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2644. tab_widget.addTab(self.splash_tab, _("Splash"))
  2645. self.programmmers_tab = QtWidgets.QWidget()
  2646. self.programmmers_tab.setObjectName("programmers_about")
  2647. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2648. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2649. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2650. self.translators_tab = QtWidgets.QWidget()
  2651. self.translators_tab.setObjectName("translators_about")
  2652. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2653. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2654. tab_widget.addTab(self.translators_tab, _("Translators"))
  2655. self.license_tab = QtWidgets.QWidget()
  2656. self.license_tab.setObjectName("license_about")
  2657. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2658. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2659. tab_widget.addTab(self.license_tab, _("License"))
  2660. self.attributions_tab = QtWidgets.QWidget()
  2661. self.attributions_tab.setObjectName("attributions_about")
  2662. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2663. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2664. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2665. self.splash_tab_layout.addWidget(logo, stretch=0)
  2666. self.splash_tab_layout.addWidget(title, stretch=1)
  2667. pal = QtGui.QPalette()
  2668. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2669. self.prog_grid_lay = QtWidgets.QGridLayout()
  2670. self.prog_grid_lay.setHorizontalSpacing(20)
  2671. self.prog_grid_lay.setColumnStretch(0, 0)
  2672. self.prog_grid_lay.setColumnStretch(2, 1)
  2673. prog_widget = QtWidgets.QWidget()
  2674. prog_widget.setLayout(self.prog_grid_lay)
  2675. prog_scroll = QtWidgets.QScrollArea()
  2676. prog_scroll.setWidget(prog_widget)
  2677. prog_scroll.setWidgetResizable(True)
  2678. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2679. prog_scroll.setPalette(pal)
  2680. self.programmmers_tab_layout.addWidget(prog_scroll)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2704. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2705. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2706. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2707. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2708. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2709. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2710. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2711. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2712. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2713. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2714. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2715. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2716. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2717. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2718. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2719. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2720. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2721. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2722. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2723. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2724. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2725. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2726. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2727. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2728. self.translator_grid_lay = QtWidgets.QGridLayout()
  2729. self.translator_grid_lay.setColumnStretch(0, 0)
  2730. self.translator_grid_lay.setColumnStretch(1, 0)
  2731. self.translator_grid_lay.setColumnStretch(2, 1)
  2732. self.translator_grid_lay.setColumnStretch(3, 0)
  2733. # trans_widget = QtWidgets.QWidget()
  2734. # trans_widget.setLayout(self.translator_grid_lay)
  2735. # self.translators_tab_layout.addWidget(trans_widget)
  2736. # self.translators_tab_layout.addStretch()
  2737. trans_widget = QtWidgets.QWidget()
  2738. trans_widget.setLayout(self.translator_grid_lay)
  2739. trans_scroll = QtWidgets.QScrollArea()
  2740. trans_scroll.setWidget(trans_widget)
  2741. trans_scroll.setWidgetResizable(True)
  2742. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2743. trans_scroll.setPalette(pal)
  2744. self.translators_tab_layout.addWidget(trans_scroll)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2750. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2751. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2752. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2753. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2754. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2755. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2756. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2757. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2758. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2759. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2760. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2761. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2762. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2763. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2764. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2765. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2766. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2767. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2768. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2769. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2770. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2771. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2772. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2773. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2774. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2775. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2776. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2777. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2778. self.translator_grid_lay.setColumnStretch(0, 0)
  2779. self.translators_tab_layout.addStretch()
  2780. self.license_tab_layout.addWidget(lic_lbl_header)
  2781. self.license_tab_layout.addWidget(lic_lbl_body)
  2782. self.license_tab_layout.addStretch()
  2783. self.attributions_tab_layout.addWidget(attributions_label)
  2784. self.attributions_tab_layout.addStretch()
  2785. layout3.addStretch()
  2786. layout3.addWidget(closebtn)
  2787. closebtn.clicked.connect(self.accept)
  2788. AboutDialog(app=self, parent=self.ui).exec_()
  2789. def install_bookmarks(self, book_dict=None):
  2790. """
  2791. Install the bookmarks actions in the Help menu -> Bookmarks
  2792. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2793. :return: None
  2794. """
  2795. if book_dict is None:
  2796. self.defaults["global_bookmarks"].update(
  2797. {
  2798. '1': ['FlatCAM', "http://flatcam.org"],
  2799. '2': ['Backup Site', ""]
  2800. }
  2801. )
  2802. else:
  2803. self.defaults["global_bookmarks"].clear()
  2804. self.defaults["global_bookmarks"].update(book_dict)
  2805. # first try to disconnect if somehow they get connected from elsewhere
  2806. for act in self.ui.menuhelp_bookmarks.actions():
  2807. try:
  2808. act.triggered.disconnect()
  2809. except TypeError:
  2810. pass
  2811. # clear all actions except the last one who is the Bookmark manager
  2812. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2813. pass
  2814. else:
  2815. self.ui.menuhelp_bookmarks.removeAction(act)
  2816. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2817. if self.defaults["global_bookmarks"]:
  2818. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2819. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2820. # the JSON is first making the keys as strings (therefore I have to use strings too
  2821. # or do the conversion :(
  2822. # )
  2823. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2824. # the '10' entry jsut after '1' therefore ordering as strings
  2825. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2826. key=lambda x: int(x[0]))
  2827. for entry, bookmark in sorted_bookmarks:
  2828. title = bookmark[0]
  2829. weblink = bookmark[1]
  2830. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2831. act.setText(title)
  2832. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2833. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2834. if title == 'Backup Site' and weblink == "":
  2835. act.triggered.connect(self.on_backup_site)
  2836. else:
  2837. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2838. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2839. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2840. def on_bookmarks_manager(self):
  2841. """
  2842. Adds the bookmark manager in a Tab in Plot Area
  2843. :return:
  2844. """
  2845. for idx in range(self.ui.plot_tab_area.count()):
  2846. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2847. # there can be only one instance of Bookmark Manager at one time
  2848. return
  2849. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2850. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2851. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2852. # add the tab if it was closed
  2853. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2854. # delete the absolute and relative position and messages in the infobar
  2855. self.ui.position_label.setText("")
  2856. # self.ui.rel_position_label.setText("")
  2857. # Switch plot_area to preferences page
  2858. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2859. def on_backup_site(self):
  2860. msgbox = QtWidgets.QMessageBox()
  2861. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2862. "1. FlatCAM.org website is down\n"
  2863. "2. Someone forked FlatCAM project and wants to point\n"
  2864. "to his own website\n\n"
  2865. "If you can't get any informations about FlatCAM beta\n"
  2866. "use the YouTube channel link from the Help menu."))
  2867. msgbox.setWindowTitle(_("Alternative website"))
  2868. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2869. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2870. msgbox.setDefaultButton(bt_yes)
  2871. msgbox.exec_()
  2872. # response = msgbox.clickedButton()
  2873. def on_file_savedefaults(self):
  2874. """
  2875. Callback for menu item File->Save Defaults. Saves application default options
  2876. ``self.defaults`` to current_defaults.FlatConfig.
  2877. :return: None
  2878. """
  2879. self.preferencesUiManager.save_defaults()
  2880. def final_save(self):
  2881. """
  2882. Callback for doing a preferences save to file whenever the application is about to quit.
  2883. If the project has changes, it will ask the user to save the project.
  2884. :return: None
  2885. """
  2886. if self.save_in_progress:
  2887. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2888. return
  2889. if self.should_we_save and self.collection.get_list():
  2890. msgbox = QtWidgets.QMessageBox()
  2891. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2892. "\n"
  2893. "Do you want to Save the project?"))
  2894. msgbox.setWindowTitle(_("Save changes"))
  2895. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2896. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2897. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2898. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2899. msgbox.setDefaultButton(bt_yes)
  2900. msgbox.exec_()
  2901. response = msgbox.clickedButton()
  2902. if response == bt_yes:
  2903. try:
  2904. self.trayIcon.hide()
  2905. except Exception:
  2906. pass
  2907. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2908. elif response == bt_no:
  2909. try:
  2910. self.trayIcon.hide()
  2911. except Exception:
  2912. pass
  2913. self.quit_application()
  2914. elif response == bt_cancel:
  2915. return
  2916. else:
  2917. try:
  2918. self.trayIcon.hide()
  2919. except Exception:
  2920. pass
  2921. self.quit_application()
  2922. def quit_application(self):
  2923. """
  2924. Called (as a pyslot or not) when the application is quit.
  2925. :return: None
  2926. """
  2927. self.preferencesUiManager.save_defaults(silent=True)
  2928. log.debug("App.quit_application() --> App Defaults saved.")
  2929. if self.cmd_line_headless != 1:
  2930. # save app state to file
  2931. stgs = QSettings("Open Source", "FlatCAM")
  2932. stgs.setValue('saved_gui_state', self.ui.saveState())
  2933. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2934. stgs.setValue(
  2935. 'language',
  2936. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2937. )
  2938. stgs.setValue(
  2939. 'notebook_font_size',
  2940. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2941. )
  2942. stgs.setValue(
  2943. 'axis_font_size',
  2944. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2945. )
  2946. stgs.setValue(
  2947. 'textbox_font_size',
  2948. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2949. )
  2950. stgs.setValue(
  2951. 'hud_font_size',
  2952. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2953. )
  2954. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2955. stgs.setValue(
  2956. 'machinist',
  2957. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2958. )
  2959. # This will write the setting to the platform specific storage.
  2960. del stgs
  2961. log.debug("App.quit_application() --> App UI state saved.")
  2962. # try to quit the Socket opened by ArgsThread class
  2963. try:
  2964. self.new_launch.stop.emit()
  2965. except Exception as err:
  2966. log.debug("App.quit_application() --> %s" % str(err))
  2967. # try to quit the QThread that run ArgsThread class
  2968. try:
  2969. self.th.quit()
  2970. except Exception as e:
  2971. log.debug("App.quit_application() --> %s" % str(e))
  2972. # terminate workers
  2973. self.workers.__del__()
  2974. # quit app by signalling for self.kill_app() method
  2975. # self.close_app_signal.emit()
  2976. QtWidgets.qApp.quit()
  2977. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2978. # we use the following command
  2979. minor_v = sys.version_info.minor
  2980. if minor_v < 8:
  2981. sys.exit(0)
  2982. else:
  2983. os._exit(0) # fix to work with Python 3.8
  2984. @staticmethod
  2985. def kill_app():
  2986. QtWidgets.qApp.quit()
  2987. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2988. # we use the following command
  2989. sys.exit(0)
  2990. def on_portable_checked(self, state):
  2991. """
  2992. Callback called when the checkbox in Preferences GUI is checked.
  2993. It will set the application as portable by creating the preferences and recent files in the
  2994. 'config' folder found in the FlatCAM installation folder.
  2995. :param state: boolean, the state of the checkbox when clicked/checked
  2996. :return:
  2997. """
  2998. line_no = 0
  2999. data = None
  3000. if sys.platform != 'win32':
  3001. # this won't work in Linux or MacOS
  3002. return
  3003. # test if the app was frozen and choose the path for the configuration file
  3004. if getattr(sys, "frozen", False) is True:
  3005. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3006. else:
  3007. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3008. config_file = current_data_path + '\\configuration.txt'
  3009. try:
  3010. with open(config_file, 'r') as f:
  3011. try:
  3012. data = f.readlines()
  3013. except Exception as e:
  3014. log.debug('App.__init__() -->%s' % str(e))
  3015. return
  3016. except FileNotFoundError:
  3017. pass
  3018. for line in data:
  3019. line = line.strip('\n')
  3020. param = str(line).rpartition('=')
  3021. if param[0] == 'portable':
  3022. break
  3023. line_no += 1
  3024. if state:
  3025. data[line_no] = 'portable=True\n'
  3026. # create the new defauults files
  3027. # create current_defaults.FlatConfig file if there is none
  3028. try:
  3029. f = open(current_data_path + '/current_defaults.FlatConfig')
  3030. f.close()
  3031. except IOError:
  3032. App.log.debug('Creating empty current_defaults.FlatConfig')
  3033. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3034. json.dump({}, f)
  3035. f.close()
  3036. # create factory_defaults.FlatConfig file if there is none
  3037. try:
  3038. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3039. f.close()
  3040. except IOError:
  3041. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3042. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3043. json.dump({}, f)
  3044. f.close()
  3045. try:
  3046. f = open(current_data_path + '/recent.json')
  3047. f.close()
  3048. except IOError:
  3049. App.log.debug('Creating empty recent.json')
  3050. f = open(current_data_path + '/recent.json', 'w')
  3051. json.dump([], f)
  3052. f.close()
  3053. try:
  3054. fp = open(current_data_path + '/recent_projects.json')
  3055. fp.close()
  3056. except IOError:
  3057. App.log.debug('Creating empty recent_projects.json')
  3058. fp = open(current_data_path + '/recent_projects.json', 'w')
  3059. json.dump([], fp)
  3060. fp.close()
  3061. # save the current defaults to the new defaults file
  3062. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3063. else:
  3064. data[line_no] = 'portable=False\n'
  3065. with open(config_file, 'w') as f:
  3066. f.writelines(data)
  3067. def on_register_files(self, obj_type=None):
  3068. """
  3069. Called whenever there is a need to register file extensions with FlatCAM.
  3070. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3071. :param obj_type: the type of object to be register for.
  3072. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3073. :return: None
  3074. """
  3075. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3076. new_reg_path = 'Software\\Classes\\'
  3077. # find if the current user is admin
  3078. try:
  3079. is_admin = os.getuid() == 0
  3080. except AttributeError:
  3081. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3082. if is_admin is True:
  3083. root_path = winreg.HKEY_LOCAL_MACHINE
  3084. else:
  3085. root_path = winreg.HKEY_CURRENT_USER
  3086. # create the keys
  3087. def set_reg(name, root_pth, new_reg_path, value):
  3088. try:
  3089. winreg.CreateKey(root_pth, new_reg_path)
  3090. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3091. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3092. return True
  3093. except WindowsError:
  3094. return False
  3095. # delete key in registry
  3096. def delete_reg(root_pth, reg_path, key_to_del):
  3097. key_to_del_path = reg_path + key_to_del
  3098. try:
  3099. winreg.DeleteKey(root_pth, key_to_del_path)
  3100. return True
  3101. except WindowsError:
  3102. return False
  3103. if obj_type is None or obj_type == 'excellon':
  3104. exc_list = \
  3105. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3106. exc_list = [x for x in exc_list if x != '']
  3107. # register all keys in the Preferences window
  3108. for ext in exc_list:
  3109. new_k = new_reg_path + '.%s' % ext
  3110. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3111. # and unregister those that are no longer in the Preferences windows but are in the file
  3112. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3113. if ext not in exc_list:
  3114. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3115. # now write the updated extensions to the self.defaults
  3116. # new_ext = ''
  3117. # for ext in exc_list:
  3118. # new_ext = new_ext + ext + ', '
  3119. # self.defaults["fa_excellon"] = new_ext
  3120. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3121. if obj_type is None or obj_type == 'gcode':
  3122. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3123. gco_list = [x for x in gco_list if x != '']
  3124. # register all keys in the Preferences window
  3125. for ext in gco_list:
  3126. new_k = new_reg_path + '.%s' % ext
  3127. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3128. # and unregister those that are no longer in the Preferences windows but are in the file
  3129. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3130. if ext not in gco_list:
  3131. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3132. # now write the updated extensions to the self.defaults
  3133. # new_ext = ''
  3134. # for ext in gco_list:
  3135. # new_ext = new_ext + ext + ', '
  3136. # self.defaults["fa_gcode"] = new_ext
  3137. self.inform.emit('[success] %s' %
  3138. _("Selected GCode file extensions registered with FlatCAM."))
  3139. if obj_type is None or obj_type == 'gerber':
  3140. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3141. grb_list = [x for x in grb_list if x != '']
  3142. # register all keys in the Preferences window
  3143. for ext in grb_list:
  3144. new_k = new_reg_path + '.%s' % ext
  3145. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3146. # and unregister those that are no longer in the Preferences windows but are in the file
  3147. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3148. if ext not in grb_list:
  3149. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3150. # now write the updated extensions to the self.defaults
  3151. # new_ext = ''
  3152. # for ext in grb_list:
  3153. # new_ext = new_ext + ext + ', '
  3154. # self.defaults["fa_gerber"] = new_ext
  3155. self.inform.emit('[success] %s' %
  3156. _("Selected Gerber file extensions registered with FlatCAM."))
  3157. def add_extension(self, ext_type):
  3158. """
  3159. Add a file extension to the list for a specific object
  3160. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3161. :return:
  3162. """
  3163. if ext_type == 'excellon':
  3164. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3165. if new_ext == '':
  3166. return
  3167. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3168. if new_ext in old_val:
  3169. return
  3170. old_val.append(new_ext)
  3171. old_val.sort()
  3172. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3173. if ext_type == 'gcode':
  3174. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3175. if new_ext == '':
  3176. return
  3177. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3178. if new_ext in old_val:
  3179. return
  3180. old_val.append(new_ext)
  3181. old_val.sort()
  3182. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3183. if ext_type == 'gerber':
  3184. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3185. if new_ext == '':
  3186. return
  3187. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3188. if new_ext in old_val:
  3189. return
  3190. old_val.append(new_ext)
  3191. old_val.sort()
  3192. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3193. if ext_type == 'keyword':
  3194. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3195. if new_kw == '':
  3196. return
  3197. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3198. if new_kw in old_val:
  3199. return
  3200. old_val.append(new_kw)
  3201. old_val.sort()
  3202. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3203. # update the self.myKeywords so the model is updated
  3204. self.autocomplete_kw_list = \
  3205. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3206. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3207. self.shell._edit.set_model_data(self.myKeywords)
  3208. def del_extension(self, ext_type):
  3209. """
  3210. Remove a file extension from the list for a specific object
  3211. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3212. :return:
  3213. """
  3214. if ext_type == 'excellon':
  3215. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3216. if new_ext == '':
  3217. return
  3218. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3219. if new_ext not in old_val:
  3220. return
  3221. old_val.remove(new_ext)
  3222. old_val.sort()
  3223. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3224. if ext_type == 'gcode':
  3225. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3226. if new_ext == '':
  3227. return
  3228. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3229. if new_ext not in old_val:
  3230. return
  3231. old_val.remove(new_ext)
  3232. old_val.sort()
  3233. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3234. if ext_type == 'gerber':
  3235. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3236. if new_ext == '':
  3237. return
  3238. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3239. if new_ext not in old_val:
  3240. return
  3241. old_val.remove(new_ext)
  3242. old_val.sort()
  3243. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3244. if ext_type == 'keyword':
  3245. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3246. if new_kw == '':
  3247. return
  3248. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3249. if new_kw not in old_val:
  3250. return
  3251. old_val.remove(new_kw)
  3252. old_val.sort()
  3253. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3254. # update the self.myKeywords so the model is updated
  3255. self.autocomplete_kw_list = \
  3256. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3257. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3258. self.shell._edit.set_model_data(self.myKeywords)
  3259. def restore_extensions(self, ext_type):
  3260. """
  3261. Restore all file extensions associations with FlatCAM, for a specific object
  3262. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3263. :return:
  3264. """
  3265. if ext_type == 'excellon':
  3266. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3267. # for the ability to open Excellon files with .txt extension
  3268. new_exc_list = deepcopy(self.exc_list)
  3269. try:
  3270. new_exc_list.remove('txt')
  3271. except ValueError:
  3272. pass
  3273. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3274. if ext_type == 'gcode':
  3275. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3276. if ext_type == 'gerber':
  3277. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3278. if ext_type == 'keyword':
  3279. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3280. # update the self.myKeywords so the model is updated
  3281. self.autocomplete_kw_list = self.default_keywords
  3282. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3283. self.shell._edit.set_model_data(self.myKeywords)
  3284. def delete_all_extensions(self, ext_type):
  3285. """
  3286. Delete all file extensions associations with FlatCAM, for a specific object
  3287. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3288. :return:
  3289. """
  3290. if ext_type == 'excellon':
  3291. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3292. if ext_type == 'gcode':
  3293. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3294. if ext_type == 'gerber':
  3295. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3296. if ext_type == 'keyword':
  3297. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3298. # update the self.myKeywords so the model is updated
  3299. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3300. self.shell._edit.set_model_data(self.myKeywords)
  3301. def on_edit_join(self, name=None):
  3302. """
  3303. Callback for Edit->Join. Joins the selected geometry objects into
  3304. a new one.
  3305. :return: None
  3306. """
  3307. self.defaults.report_usage("on_edit_join()")
  3308. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3309. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3310. geo_type_set = set()
  3311. objs = self.collection.get_selected()
  3312. if len(objs) < 2:
  3313. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3314. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3315. return 'fail'
  3316. for obj in objs:
  3317. geo_type_set.add(obj.multigeo)
  3318. # if len(geo_type_list) == 1 means that all list elements are the same
  3319. if len(geo_type_set) != 1:
  3320. self.inform.emit('[ERROR] %s' %
  3321. _("Failed join. The Geometry objects are of different types.\n"
  3322. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3323. "convert from one to another and retry joining \n"
  3324. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3325. "the result may not be what was expected. \n"
  3326. "Check the generated GCODE."))
  3327. return
  3328. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3329. if True in geo_type_set:
  3330. def initialize(geo_obj, app):
  3331. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3332. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3333. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3334. for v in geo_obj.tools.values():
  3335. v['data']['name'] = obj_name_multi
  3336. self.new_object("geometry", obj_name_multi, initialize)
  3337. else:
  3338. def initialize(geo_obj, app):
  3339. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3340. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3341. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3342. for v in geo_obj.tools.values():
  3343. v['data']['name'] = obj_name_single
  3344. self.new_object("geometry", obj_name_single, initialize)
  3345. self.should_we_save = True
  3346. def on_edit_join_exc(self):
  3347. """
  3348. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3349. a new Excellon.
  3350. :return: None
  3351. """
  3352. self.defaults.report_usage("on_edit_join_exc()")
  3353. objs = self.collection.get_selected()
  3354. for obj in objs:
  3355. if not isinstance(obj, ExcellonObject):
  3356. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3357. return
  3358. if len(objs) < 2:
  3359. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3360. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3361. return 'fail'
  3362. def initialize(exc_obj, app):
  3363. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3364. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3365. self.new_object("excellon", 'Combo_Excellon', initialize)
  3366. self.should_we_save = True
  3367. def on_edit_join_grb(self):
  3368. """
  3369. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3370. a new Gerber object.
  3371. :return: None
  3372. """
  3373. self.defaults.report_usage("on_edit_join_grb()")
  3374. objs = self.collection.get_selected()
  3375. for obj in objs:
  3376. if not isinstance(obj, GerberObject):
  3377. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3378. return
  3379. if len(objs) < 2:
  3380. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3381. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3382. return 'fail'
  3383. def initialize(grb_obj, app):
  3384. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3385. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3386. self.new_object("gerber", 'Combo_Gerber', initialize)
  3387. self.should_we_save = True
  3388. def on_convert_singlegeo_to_multigeo(self):
  3389. """
  3390. Called for converting a Geometry object from single-geo to multi-geo.
  3391. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3392. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3393. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3394. the solid-geometry of that tool.
  3395. :return: None
  3396. """
  3397. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3398. obj = self.collection.get_active()
  3399. if obj is None:
  3400. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3401. return
  3402. if not isinstance(obj, GeometryObject):
  3403. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3404. return
  3405. obj.multigeo = True
  3406. for tooluid, dict_value in obj.tools.items():
  3407. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3408. if not isinstance(obj.solid_geometry, list):
  3409. obj.solid_geometry = [obj.solid_geometry]
  3410. # obj.solid_geometry[:] = []
  3411. obj.plot()
  3412. self.should_we_save = True
  3413. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3414. def on_convert_multigeo_to_singlegeo(self):
  3415. """
  3416. Called for converting a Geometry object from multi-geo to single-geo.
  3417. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3418. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3419. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3420. the solid-geometry of that tool.
  3421. :return: None
  3422. """
  3423. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3424. obj = self.collection.get_active()
  3425. if obj is None:
  3426. self.inform.emit('[ERROR_NOTCL] %s' %
  3427. _("Failed. Select a Geometry Object and try again."))
  3428. return
  3429. if not isinstance(obj, GeometryObject):
  3430. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3431. (_("Expected a GeometryObject, got"), type(obj)))
  3432. return
  3433. obj.multigeo = False
  3434. total_solid_geometry = []
  3435. for tooluid, dict_value in obj.tools.items():
  3436. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3437. # clear the original geometry
  3438. dict_value['solid_geometry'][:] = []
  3439. obj.solid_geometry = deepcopy(total_solid_geometry)
  3440. obj.plot()
  3441. self.should_we_save = True
  3442. self.inform.emit('[success] %s' %
  3443. _("A Geometry object was converted to SingleGeo type."))
  3444. def on_defaults_dict_change(self, field):
  3445. """
  3446. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3447. Edit -> Preferences tab window.
  3448. :param field: the key of the self.defaults dictionary that was changed.
  3449. :return: None
  3450. """
  3451. self.preferencesUiManager.defaults_write_form_field(field=field)
  3452. if field == "units":
  3453. self.set_screen_units(self.defaults['units'])
  3454. def set_screen_units(self, units):
  3455. """
  3456. Set the FlatCAM units on the status bar.
  3457. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3458. :return: None
  3459. """
  3460. self.ui.units_label.setText("[" + units.lower() + "]")
  3461. def on_toggle_units_click(self):
  3462. try:
  3463. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3464. except (TypeError, AttributeError):
  3465. pass
  3466. if self.defaults["units"] == 'MM':
  3467. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3468. else:
  3469. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3470. self.on_toggle_units(no_pref=True)
  3471. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3472. lambda: self.on_toggle_units(no_pref=False))
  3473. def on_toggle_units(self, no_pref=False):
  3474. """
  3475. Callback for the Units radio-button change in the Preferences tab.
  3476. Changes the application's default units adn for the project too.
  3477. If changing the project's units, the change propagates to all of
  3478. the objects in the project.
  3479. :return: None
  3480. """
  3481. self.defaults.report_usage("on_toggle_units")
  3482. if self.toggle_units_ignore:
  3483. return
  3484. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3485. # If option is the same, then ignore
  3486. if new_units == self.defaults["units"].upper():
  3487. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3488. return
  3489. # Keys in self.defaults for which to scale their values
  3490. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3491. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3492. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3493. "gerber_editor_ma_high",
  3494. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3495. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3496. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3497. "excellon_feedrate_probe", "excellon_milling_dia",
  3498. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3499. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3500. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3501. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3502. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3503. "geometry_extracut_length", "geometry_z_pdepth",
  3504. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3505. 'cncjob_tooldia',
  3506. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3507. "tools_paintnewdia",
  3508. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3509. "tools_nccnewdia", "tools_ncc_offset_value",
  3510. "tools_2sided_drilldia",
  3511. "tools_film_boundary", "tools_film_scale_stroke",
  3512. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3513. "tools_cutout_depthperpass",
  3514. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3515. "tools_panelize_spacing_rows",
  3516. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3517. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3518. "tools_transform_buffer_dis",
  3519. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3520. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3521. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3522. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3523. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3524. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3525. "tools_cr_h2h_val", "tools_cr_dh_val",
  3526. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3527. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3528. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3529. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3530. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3531. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3532. "tools_copper_thieving_mask_clearance",
  3533. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3534. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3535. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3536. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3537. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3538. "tools_invert_margin",
  3539. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3540. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3541. def scale_defaults(sfactor):
  3542. for dim in dimensions:
  3543. if dim in [
  3544. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3545. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3546. 'tools_transform_mirror_point'
  3547. ]:
  3548. if self.defaults[dim] is None or self.defaults[dim] == '':
  3549. continue
  3550. try:
  3551. coordinates = self.defaults[dim].split(",")
  3552. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3553. coords_xy[0] *= sfactor
  3554. coords_xy[1] *= sfactor
  3555. self.defaults[dim] = "%.*f, %.*f" % (
  3556. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3557. except Exception as e:
  3558. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3559. elif dim in [
  3560. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3561. ]:
  3562. if self.defaults[dim] is None or self.defaults[dim] == '':
  3563. continue
  3564. try:
  3565. self.defaults[dim] = float(self.defaults[dim])
  3566. tools_diameters = [self.defaults[dim]]
  3567. except ValueError:
  3568. try:
  3569. tools_string = self.defaults[dim].split(",")
  3570. tools_diameters = [eval(a) for a in tools_string if a != '']
  3571. except Exception as e:
  3572. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3573. continue
  3574. self.defaults[dim] = ''
  3575. td_len = len(tools_diameters)
  3576. if td_len > 1:
  3577. for t in range(td_len):
  3578. tools_diameters[t] *= sfactor
  3579. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3580. else:
  3581. tools_diameters[0] *= sfactor
  3582. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3583. elif dim in ['global_gridx', 'global_gridy']:
  3584. # format the number of decimals to the one specified in self.decimals
  3585. try:
  3586. val = float(self.defaults[dim]) * sfactor
  3587. except Exception as e:
  3588. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3589. continue
  3590. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3591. else:
  3592. # the number of decimals for the rest is kept unchanged
  3593. if self.defaults[dim]:
  3594. try:
  3595. val = float(self.defaults[dim]) * sfactor
  3596. except Exception as e:
  3597. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3598. continue
  3599. self.defaults[dim] = val
  3600. # The scaling factor depending on choice of units.
  3601. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3602. # Changing project units. Warn user.
  3603. msgbox = QtWidgets.QMessageBox()
  3604. msgbox.setWindowTitle(_("Toggle Units"))
  3605. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3606. msgbox.setText(_("Changing the units of the project\n"
  3607. "will scale all objects.\n\n"
  3608. "Do you want to continue?"))
  3609. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3610. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3611. msgbox.setDefaultButton(bt_ok)
  3612. msgbox.exec_()
  3613. response = msgbox.clickedButton()
  3614. if response == bt_ok:
  3615. if no_pref is False:
  3616. self.preferencesUiManager.defaults_read_form()
  3617. scale_defaults(factor)
  3618. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3619. self.defaults["units"] = new_units
  3620. # update the defaults from form, some may assume that the conversion is enough and it's not
  3621. self.on_options_app2project()
  3622. # update the objects
  3623. for obj in self.collection.get_list():
  3624. obj.convert_units(new_units)
  3625. # make that the properties stored in the object are also updated
  3626. self.object_changed.emit(obj)
  3627. # rebuild the object UI
  3628. obj.build_ui()
  3629. # change this only if the workspace is active
  3630. if self.defaults['global_workspace'] is True:
  3631. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3632. # adjust the grid values on the main toolbar
  3633. val_x = float(self.defaults['global_gridx']) * factor
  3634. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3635. current = self.collection.get_active()
  3636. if current is not None:
  3637. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3638. if not isinstance(current, GeometryObject):
  3639. current.to_form()
  3640. # replot all objects
  3641. self.plot_all()
  3642. # set the status labels to reflect the current FlatCAM units
  3643. self.set_screen_units(new_units)
  3644. # signal to the app that we changed the object properties and it should save the project
  3645. self.should_we_save = True
  3646. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3647. else:
  3648. # Undo toggling
  3649. self.toggle_units_ignore = True
  3650. if self.defaults['units'].upper() == 'MM':
  3651. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3652. else:
  3653. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3654. self.toggle_units_ignore = False
  3655. # store the grid values so they are not changed in the next step
  3656. val_x = float(self.defaults['global_gridx'])
  3657. val_y = float(self.defaults['global_gridy'])
  3658. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3659. self.preferencesUiManager.defaults_read_form()
  3660. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3661. # in self.defaults from the GUI elements but
  3662. # I don't want it for the grid values, so I update them here
  3663. self.defaults['global_gridx'] = val_x
  3664. self.defaults['global_gridy'] = val_y
  3665. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3666. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3667. def on_fullscreen(self, disable=False):
  3668. self.defaults.report_usage("on_fullscreen()")
  3669. flags = self.ui.windowFlags()
  3670. if self.toggle_fscreen is False and disable is False:
  3671. # self.ui.showFullScreen()
  3672. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3673. a = self.ui.geometry()
  3674. self.x_pos = a.x()
  3675. self.y_pos = a.y()
  3676. self.width = a.width()
  3677. self.height = a.height()
  3678. # set new geometry to full desktop rect
  3679. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3680. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3681. # everything else will not work without this hack. This happen in Windows.
  3682. # https://bugreports.qt.io/browse/QTBUG-41309
  3683. desktop = QtWidgets.QApplication.desktop()
  3684. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3685. rec = desktop.screenGeometry(screen)
  3686. x = rec.x() - 1
  3687. y = rec.y() - 1
  3688. h = rec.height() + 2
  3689. w = rec.width() + 2
  3690. self.ui.setGeometry(x, y, w, h)
  3691. self.ui.show()
  3692. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3693. tb.setVisible(False)
  3694. self.ui.snap_toolbar.setVisible(True) # This is always visible
  3695. # self.ui.splitter_left.setVisible(False)
  3696. self.ui.splitter.setSizes([0, 1])
  3697. self.toggle_fscreen = True
  3698. elif self.toggle_fscreen is True or disable is True:
  3699. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3700. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3701. self.ui.showNormal()
  3702. self.restore_toolbar_view()
  3703. # self.ui.splitter_left.setVisible(True)
  3704. self.toggle_fscreen = False
  3705. def on_toggle_plotarea(self):
  3706. self.defaults.report_usage("on_toggle_plotarea()")
  3707. try:
  3708. name = self.ui.plot_tab_area.widget(0).objectName()
  3709. except AttributeError:
  3710. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3711. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3712. self.ui.plot_tab_area.protectTab(0)
  3713. return
  3714. if name != 'plotarea_tab':
  3715. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3716. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3717. self.ui.plot_tab_area.protectTab(0)
  3718. else:
  3719. self.ui.plot_tab_area.closeTab(0)
  3720. def on_toggle_notebook(self):
  3721. if self.ui.splitter.sizes()[0] == 0:
  3722. self.ui.splitter.setSizes([1, 1])
  3723. self.ui.menu_toggle_nb.setChecked(True)
  3724. else:
  3725. self.ui.splitter.setSizes([0, 1])
  3726. self.ui.menu_toggle_nb.setChecked(False)
  3727. def on_toggle_axis(self):
  3728. self.defaults.report_usage("on_toggle_axis()")
  3729. if self.toggle_axis is False:
  3730. if self.is_legacy is False:
  3731. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3732. parent=self.plotcanvas.view.scene)
  3733. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3734. parent=self.plotcanvas.view.scene)
  3735. else:
  3736. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3737. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3738. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3739. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3740. self.plotcanvas.canvas.draw()
  3741. self.toggle_axis = True
  3742. else:
  3743. if self.is_legacy is False:
  3744. self.plotcanvas.v_line.parent = None
  3745. self.plotcanvas.h_line.parent = None
  3746. else:
  3747. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3748. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3749. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3750. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3751. self.plotcanvas.canvas.draw()
  3752. self.toggle_axis = False
  3753. def on_toggle_hud(self):
  3754. self.plotcanvas.on_toggle_hud(state=False if self.plotcanvas.hud_enabled else True)
  3755. def on_toggle_grid(self):
  3756. self.defaults.report_usage("on_toggle_grid()")
  3757. self.ui.grid_snap_btn.trigger()
  3758. def on_toggle_grid_lines(self):
  3759. self.defaults.report_usage("on_toggle_grd_lines()")
  3760. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3761. if tt_settings.contains("theme"):
  3762. theme = tt_settings.value('theme', type=str)
  3763. else:
  3764. theme = 'white'
  3765. if self.toggle_grid_lines is False:
  3766. if self.is_legacy is False:
  3767. if theme == 'white':
  3768. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3769. else:
  3770. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3771. else:
  3772. self.plotcanvas.axes.grid(True)
  3773. try:
  3774. self.plotcanvas.canvas.draw()
  3775. except IndexError:
  3776. pass
  3777. pass
  3778. self.toggle_grid_lines = True
  3779. else:
  3780. if self.is_legacy is False:
  3781. if theme == 'white':
  3782. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3783. else:
  3784. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3785. else:
  3786. self.plotcanvas.axes.grid(False)
  3787. try:
  3788. self.plotcanvas.canvas.draw()
  3789. except IndexError:
  3790. pass
  3791. self.toggle_grid_lines = False
  3792. if self.is_legacy is False:
  3793. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3794. # - perhaps is a bug in VisPy implementation
  3795. if self.grid_status():
  3796. self.app_cursor.enabled = False
  3797. self.app_cursor.enabled = True
  3798. else:
  3799. self.app_cursor.enabled = True
  3800. self.app_cursor.enabled = False
  3801. def on_update_exc_export(self, state):
  3802. """
  3803. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3804. if the update_excellon_cb checkbox is checked
  3805. :param state: state of the checkbox whose signals is tied to his slot
  3806. :return:
  3807. """
  3808. if state:
  3809. # first try to disconnect
  3810. try:
  3811. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3812. disconnect(self.on_excellon_format_changed)
  3813. except TypeError:
  3814. pass
  3815. try:
  3816. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3817. disconnect(self.on_excellon_format_changed)
  3818. except TypeError:
  3819. pass
  3820. try:
  3821. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3822. disconnect(self.on_excellon_format_changed)
  3823. except TypeError:
  3824. pass
  3825. try:
  3826. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3827. disconnect(self.on_excellon_format_changed)
  3828. except TypeError:
  3829. pass
  3830. try:
  3831. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3832. disconnect(self.on_excellon_zeros_changed)
  3833. except TypeError:
  3834. pass
  3835. try:
  3836. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3837. disconnect(self.on_excellon_zeros_changed)
  3838. except TypeError:
  3839. pass
  3840. # the connect them
  3841. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3842. self.on_excellon_format_changed)
  3843. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3844. self.on_excellon_format_changed)
  3845. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3846. self.on_excellon_format_changed)
  3847. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3848. self.on_excellon_format_changed)
  3849. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3850. self.on_excellon_zeros_changed)
  3851. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3852. self.on_excellon_units_changed)
  3853. else:
  3854. # disconnect the signals
  3855. try:
  3856. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3857. disconnect(self.on_excellon_format_changed)
  3858. except TypeError:
  3859. pass
  3860. try:
  3861. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3862. disconnect(self.on_excellon_format_changed)
  3863. except TypeError:
  3864. pass
  3865. try:
  3866. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3867. disconnect(self.on_excellon_format_changed)
  3868. except TypeError:
  3869. pass
  3870. try:
  3871. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3872. disconnect(self.on_excellon_format_changed)
  3873. except TypeError:
  3874. pass
  3875. try:
  3876. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3877. disconnect(self.on_excellon_zeros_changed)
  3878. except TypeError:
  3879. pass
  3880. try:
  3881. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3882. disconnect(self.on_excellon_zeros_changed)
  3883. except TypeError:
  3884. pass
  3885. def on_excellon_format_changed(self):
  3886. """
  3887. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3888. :return: None
  3889. """
  3890. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3891. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3892. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3893. )
  3894. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3895. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3896. )
  3897. else:
  3898. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3899. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3900. )
  3901. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3902. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3903. )
  3904. def on_excellon_zeros_changed(self):
  3905. """
  3906. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3907. :return: None
  3908. """
  3909. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3910. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3911. )
  3912. def on_excellon_units_changed(self):
  3913. """
  3914. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3915. :return: None
  3916. """
  3917. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3918. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3919. )
  3920. self.on_excellon_format_changed()
  3921. def on_film_color_entry(self):
  3922. self.defaults['tools_film_color'] = \
  3923. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3924. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3925. "background-color:%s;"
  3926. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3927. )
  3928. def on_film_color_button(self):
  3929. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3930. c_dialog = QtWidgets.QColorDialog()
  3931. film_color = c_dialog.getColor(initial=current_color)
  3932. if film_color.isValid() is False:
  3933. return
  3934. # if new color is different then mark that the Preferences are changed
  3935. if film_color != current_color:
  3936. self.preferencesUiManager.on_preferences_edited()
  3937. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3938. "background-color:%s;"
  3939. "border-color: dimgray" % str(film_color.name())
  3940. )
  3941. new_val_sel = str(film_color.name())
  3942. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3943. self.defaults['tools_film_color'] = new_val_sel
  3944. def on_qrcode_fill_color_entry(self):
  3945. self.defaults['tools_qrcode_fill_color'] = \
  3946. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3947. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3948. "background-color:%s;"
  3949. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3950. )
  3951. def on_qrcode_fill_color_button(self):
  3952. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3953. c_dialog = QtWidgets.QColorDialog()
  3954. fill_color = c_dialog.getColor(initial=current_color)
  3955. if fill_color.isValid() is False:
  3956. return
  3957. # if new color is different then mark that the Preferences are changed
  3958. if fill_color != current_color:
  3959. self.preferencesUiManager.on_preferences_edited()
  3960. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3961. "background-color:%s;"
  3962. "border-color: dimgray" % str(fill_color.name())
  3963. )
  3964. new_val_sel = str(fill_color.name())
  3965. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3966. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3967. def on_qrcode_back_color_entry(self):
  3968. self.defaults['tools_qrcode_back_color'] = \
  3969. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3970. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3971. "background-color:%s;"
  3972. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3973. )
  3974. def on_qrcode_back_color_button(self):
  3975. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3976. c_dialog = QtWidgets.QColorDialog()
  3977. back_color = c_dialog.getColor(initial=current_color)
  3978. if back_color.isValid() is False:
  3979. return
  3980. # if new color is different then mark that the Preferences are changed
  3981. if back_color != current_color:
  3982. self.preferencesUiManager.on_preferences_edited()
  3983. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3984. "background-color:%s;"
  3985. "border-color: dimgray" % str(back_color.name())
  3986. )
  3987. new_val_sel = str(back_color.name())
  3988. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3989. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3990. def on_tab_rmb_click(self, checked):
  3991. self.ui.notebook.set_detachable(val=checked)
  3992. self.defaults["global_tabs_detachable"] = checked
  3993. self.ui.plot_tab_area.set_detachable(val=checked)
  3994. self.defaults["global_tabs_detachable"] = checked
  3995. def on_tab_setup_context_menu(self):
  3996. initial_checked = self.defaults["global_tabs_detachable"]
  3997. action_name = str(_("Detachable Tabs"))
  3998. action = QtWidgets.QAction(self)
  3999. action.setCheckable(True)
  4000. action.setText(action_name)
  4001. action.setChecked(initial_checked)
  4002. self.ui.notebook.tabBar.addAction(action)
  4003. self.ui.plot_tab_area.tabBar.addAction(action)
  4004. try:
  4005. action.triggered.disconnect()
  4006. except TypeError:
  4007. pass
  4008. action.triggered.connect(self.on_tab_rmb_click)
  4009. def on_deselect_all(self):
  4010. self.collection.set_all_inactive()
  4011. self.delete_selection_shape()
  4012. def on_workspace_modified(self):
  4013. # self.save_defaults(silent=True)
  4014. self.plotcanvas.delete_workspace()
  4015. self.preferencesUiManager.defaults_read_form()
  4016. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4017. def on_workspace(self):
  4018. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4019. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4020. self.inform.emit(_("Workspace enabled."))
  4021. else:
  4022. self.plotcanvas.delete_workspace()
  4023. self.inform.emit(_("Workspace disabled."))
  4024. self.preferencesUiManager.defaults_read_form()
  4025. # self.save_defaults(silent=True)
  4026. def on_workspace_toggle(self):
  4027. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4028. try:
  4029. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4030. except TypeError:
  4031. pass
  4032. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4033. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4034. self.on_workspace()
  4035. def on_cursor_type(self, val):
  4036. """
  4037. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4038. :return: None
  4039. """
  4040. self.app_cursor.enabled = False
  4041. if val == 'small':
  4042. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4043. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4044. self.app_cursor = self.plotcanvas.new_cursor()
  4045. else:
  4046. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4047. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4048. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4049. if self.ui.grid_snap_btn.isChecked():
  4050. self.app_cursor.enabled = True
  4051. else:
  4052. self.app_cursor.enabled = False
  4053. def on_tool_add_keypress(self):
  4054. # ## Current application units in Upper Case
  4055. self.units = self.defaults['units'].upper()
  4056. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4057. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4058. if notebook_widget_name == 'selected_tab':
  4059. if self.collection.get_active().kind == 'geometry':
  4060. # Tool add works for Geometry only if Advanced is True in Preferences
  4061. if self.defaults["global_app_level"] == 'a':
  4062. tool_add_popup = FCInputDialog(title="New Tool ...",
  4063. text='Enter a Tool Diameter:',
  4064. min=0.0000, max=99.9999, decimals=4)
  4065. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4066. val, ok = tool_add_popup.get_value()
  4067. if ok:
  4068. if float(val) == 0:
  4069. self.inform.emit('[WARNING_NOTCL] %s' %
  4070. _("Please enter a tool diameter with non-zero value, in Float format."))
  4071. return
  4072. self.collection.get_active().on_tool_add(dia=float(val))
  4073. else:
  4074. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4075. else:
  4076. msgbox = QtWidgets.QMessageBox()
  4077. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4078. "Go to Preferences -> General - Show Advanced Options."))
  4079. msgbox.setWindowTitle("Tool adding ...")
  4080. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4081. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4082. msgbox.setDefaultButton(bt_ok)
  4083. msgbox.exec_()
  4084. # work only if the notebook tab on focus is the Tools_Tab
  4085. if notebook_widget_name == 'tool_tab':
  4086. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4087. # and only if the tool is NCC Tool
  4088. if tool_widget == self.ncclear_tool.toolName:
  4089. self.ncclear_tool.on_add_tool_by_key()
  4090. # and only if the tool is Paint Area Tool
  4091. elif tool_widget == self.paint_tool.toolName:
  4092. self.paint_tool.on_add_tool_by_key()
  4093. # and only if the tool is Solder Paste Dispensing Tool
  4094. elif tool_widget == self.paste_tool.toolName:
  4095. self.paste_tool.on_add_tool_by_key()
  4096. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4097. # See description below.
  4098. def on_delete_keypress(self):
  4099. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4100. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4101. if notebook_widget_name == 'selected_tab':
  4102. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4103. self.collection.get_active().on_tool_delete()
  4104. # work only if the notebook tab on focus is the Tools_Tab
  4105. elif notebook_widget_name == 'tool_tab':
  4106. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4107. # and only if the tool is NCC Tool
  4108. if tool_widget == self.ncclear_tool.toolName:
  4109. self.ncclear_tool.on_tool_delete()
  4110. # and only if the tool is Paint Tool
  4111. elif tool_widget == self.paint_tool.toolName:
  4112. self.paint_tool.on_tool_delete()
  4113. # and only if the tool is Solder Paste Dispensing Tool
  4114. elif tool_widget == self.paste_tool.toolName:
  4115. self.paste_tool.on_tool_delete()
  4116. else:
  4117. self.on_delete()
  4118. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4119. # some screens you have to be careful where you hover with your mouse.
  4120. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4121. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4122. # Complicated, I know :)
  4123. def on_delete(self, force_deletion=False):
  4124. """
  4125. Delete the currently selected FlatCAMObjs.
  4126. :param force_deletion: used by Tcl command
  4127. :return: None
  4128. """
  4129. self.defaults.report_usage("on_delete()")
  4130. response = None
  4131. bt_ok = None
  4132. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4133. # a geometry object before we update it.
  4134. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4135. and self.grb_editor.editor_active is False:
  4136. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4137. msgbox = QtWidgets.QMessageBox()
  4138. msgbox.setWindowTitle(_("Delete objects"))
  4139. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4140. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4141. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4142. "the selected objects?"))
  4143. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4144. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4145. msgbox.setDefaultButton(bt_ok)
  4146. msgbox.exec_()
  4147. response = msgbox.clickedButton()
  4148. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4149. response = bt_ok
  4150. if response == bt_ok:
  4151. if self.collection.get_active():
  4152. self.log.debug("App.on_delete()")
  4153. for obj_active in self.collection.get_selected():
  4154. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4155. if obj_active.kind == 'gerber':
  4156. for el in obj_active.mark_shapes:
  4157. obj_active.mark_shapes[el].clear(update=True)
  4158. obj_active.mark_shapes[el].enabled = False
  4159. # obj_active.mark_shapes[el] = None
  4160. del el
  4161. elif isinstance(obj_active, CNCJobObject):
  4162. try:
  4163. obj_active.text_col.enabled = False
  4164. del obj_active.text_col
  4165. obj_active.annotation.clear(update=True)
  4166. del obj_active.annotation
  4167. except AttributeError as e:
  4168. log.debug(
  4169. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4170. )
  4171. while self.collection.get_selected():
  4172. self.delete_first_selected()
  4173. self.inform.emit('%s...' % _("Object(s) deleted"))
  4174. # make sure that the selection shape is deleted, too
  4175. self.delete_selection_shape()
  4176. # if there are no longer objects delete also the exclusion areas shapes
  4177. if not self.collection.get_list():
  4178. self.exc_areas.clear_shapes()
  4179. else:
  4180. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4181. else:
  4182. self.inform.emit(_("Save the work in Editor and try again ..."))
  4183. def delete_first_selected(self):
  4184. # Keep this for later
  4185. try:
  4186. sel_obj = self.collection.get_active()
  4187. name = sel_obj.options["name"]
  4188. isPlotted = sel_obj.options["plot"]
  4189. except AttributeError:
  4190. self.log.debug("Nothing selected for deletion")
  4191. return
  4192. if self.is_legacy is True:
  4193. # Remove plot only if the object was plotted otherwise delaxes will fail
  4194. if isPlotted:
  4195. try:
  4196. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4197. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4198. except Exception as e:
  4199. log.debug("App.delete_first_selected() --> %s" % str(e))
  4200. self.plotcanvas.auto_adjust_axes()
  4201. # Remove from dictionary
  4202. self.collection.delete_active()
  4203. # Clear form
  4204. self.setup_component_editor()
  4205. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4206. def on_set_origin(self):
  4207. """
  4208. Set the origin to the left mouse click position
  4209. :return: None
  4210. """
  4211. # display the message for the user
  4212. # and ask him to click on the desired position
  4213. self.defaults.report_usage("on_set_origin()")
  4214. def origin_replot():
  4215. def worker_task():
  4216. with self.proc_container.new('%s...' % _("Plotting")):
  4217. for obj in self.collection.get_list():
  4218. obj.plot()
  4219. self.plotcanvas.fit_view()
  4220. if self.is_legacy:
  4221. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4222. else:
  4223. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4224. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4225. self.inform.emit(_('Click to set the origin ...'))
  4226. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4227. # first disconnect it as it may have been used by something else
  4228. try:
  4229. self.replot_signal.disconnect()
  4230. except TypeError:
  4231. pass
  4232. self.replot_signal[list].connect(origin_replot)
  4233. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4234. """
  4235. :param event:
  4236. :param location:
  4237. :param noplot:
  4238. :param use_thread:
  4239. :return:
  4240. """
  4241. noplot_sig = noplot
  4242. def worker_task():
  4243. with self.proc_container.new(_("Setting Origin...")):
  4244. obj_list = self.collection.get_list()
  4245. for obj in obj_list:
  4246. obj.offset((x, y))
  4247. self.object_changed.emit(obj)
  4248. # Update the object bounding box options
  4249. a, b, c, d = obj.bounds()
  4250. obj.options['xmin'] = a
  4251. obj.options['ymin'] = b
  4252. obj.options['xmax'] = c
  4253. obj.options['ymax'] = d
  4254. self.inform.emit('[success] %s...' % _('Origin set'))
  4255. for obj in obj_list:
  4256. out_name = obj.options["name"]
  4257. if obj.kind == 'gerber':
  4258. obj.source_file = self.export_gerber(
  4259. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4260. elif obj.kind == 'excellon':
  4261. obj.source_file = self.export_excellon(
  4262. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4263. if noplot_sig is False:
  4264. self.replot_signal.emit([])
  4265. if location is not None:
  4266. if len(location) != 2:
  4267. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4268. return 'fail'
  4269. x, y = location
  4270. if use_thread is True:
  4271. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4272. else:
  4273. worker_task()
  4274. self.should_we_save = True
  4275. return
  4276. if event is not None and event.button == 1:
  4277. if self.is_legacy is False:
  4278. event_pos = event.pos
  4279. else:
  4280. event_pos = (event.xdata, event.ydata)
  4281. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4282. if self.grid_status():
  4283. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4284. else:
  4285. pos = pos_canvas
  4286. x = 0 - pos[0]
  4287. y = 0 - pos[1]
  4288. if use_thread is True:
  4289. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4290. else:
  4291. worker_task()
  4292. self.should_we_save = True
  4293. def on_move2origin(self, use_thread=True):
  4294. """
  4295. Move selected objects to origin.
  4296. :param use_thread: Control if to use threaded operation. Boolean.
  4297. :return:
  4298. """
  4299. def worker_task():
  4300. with self.proc_container.new(_("Moving to Origin...")):
  4301. obj_list = self.collection.get_selected()
  4302. if not obj_list:
  4303. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4304. return
  4305. xminlist = []
  4306. yminlist = []
  4307. # first get a bounding box to fit all
  4308. for obj in obj_list:
  4309. xmin, ymin, xmax, ymax = obj.bounds()
  4310. xminlist.append(xmin)
  4311. yminlist.append(ymin)
  4312. # get the minimum x,y for all objects selected
  4313. x = min(xminlist)
  4314. y = min(yminlist)
  4315. for obj in obj_list:
  4316. obj.offset((-x, -y))
  4317. self.object_changed.emit(obj)
  4318. # Update the object bounding box options
  4319. a, b, c, d = obj.bounds()
  4320. obj.options['xmin'] = a
  4321. obj.options['ymin'] = b
  4322. obj.options['xmax'] = c
  4323. obj.options['ymax'] = d
  4324. for obj in obj_list:
  4325. obj.plot()
  4326. for obj in obj_list:
  4327. out_name = obj.options["name"]
  4328. if obj.kind == 'gerber':
  4329. obj.source_file = self.export_gerber(
  4330. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4331. elif obj.kind == 'excellon':
  4332. obj.source_file = self.export_excellon(
  4333. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4334. self.inform.emit('[success] %s...' % _('Origin set'))
  4335. if use_thread is True:
  4336. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4337. else:
  4338. worker_task()
  4339. self.should_we_save = True
  4340. def on_jump_to(self, custom_location=None, fit_center=True):
  4341. """
  4342. Jump to a location by setting the mouse cursor location.
  4343. :param custom_location: Jump to a specified point. (x, y) tuple.
  4344. :param fit_center: If to fit view. Boolean.
  4345. :return:
  4346. """
  4347. self.defaults.report_usage("on_jump_to()")
  4348. if not custom_location:
  4349. dia_box_location = None
  4350. try:
  4351. dia_box_location = eval(self.clipboard.text())
  4352. except Exception:
  4353. pass
  4354. if type(dia_box_location) == tuple:
  4355. dia_box_location = str(dia_box_location)
  4356. else:
  4357. dia_box_location = None
  4358. # dia_box = Dialog_box(title=_("Jump to ..."),
  4359. # label=_("Enter the coordinates in format X,Y:"),
  4360. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4361. # initial_text=dia_box_location)
  4362. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4363. label=_("Enter the coordinates in format X,Y:"),
  4364. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4365. initial_text=dia_box_location,
  4366. reference=self.defaults['global_jump_ref'])
  4367. if dia_box.ok is True:
  4368. try:
  4369. location = eval(dia_box.location)
  4370. if not isinstance(location, tuple):
  4371. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4372. return
  4373. if dia_box.reference == 'rel':
  4374. rel_x = self.mouse[0] + location[0]
  4375. rel_y = self.mouse[1] + location[1]
  4376. location = (rel_x, rel_y)
  4377. self.defaults['global_jump_ref'] = dia_box.reference
  4378. except Exception:
  4379. return
  4380. else:
  4381. return
  4382. else:
  4383. location = custom_location
  4384. self.jump_signal.emit(location)
  4385. if fit_center:
  4386. self.plotcanvas.fit_center(loc=location)
  4387. cursor = QtGui.QCursor()
  4388. if self.is_legacy is False:
  4389. # I don't know where those differences come from but they are constant for the current
  4390. # execution of the application and they are multiples of a value around 0.0263mm.
  4391. # In a random way sometimes they are more sometimes they are less
  4392. # if units == 'MM':
  4393. # cal_factor = 0.0263
  4394. # else:
  4395. # cal_factor = 0.0263 / 25.4
  4396. cal_location = (location[0], location[1])
  4397. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4398. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4399. j_pos = (
  4400. int(canvas_origin.x() + round(jump_loc[0])),
  4401. int(canvas_origin.y() + round(jump_loc[1]))
  4402. )
  4403. cursor.setPos(j_pos[0], j_pos[1])
  4404. else:
  4405. # find the canvas origin which is in the top left corner
  4406. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4407. # determine the coordinates for the lowest left point of the canvas
  4408. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4409. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4410. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4411. # canvas) and the point (width, height) is in the top-right location
  4412. loc = self.plotcanvas.axes.transData.transform_point(location)
  4413. j_pos = (
  4414. int(x0 + loc[0]),
  4415. int(y0 - loc[1])
  4416. )
  4417. cursor.setPos(j_pos[0], j_pos[1])
  4418. self.plotcanvas.mouse = [location[0], location[1]]
  4419. if self.defaults["global_cursor_color_enabled"] is True:
  4420. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4421. else:
  4422. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4423. if self.grid_status():
  4424. # Update cursor
  4425. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4426. symbol='++', edge_color=self.cursor_color_3D,
  4427. edge_width=self.defaults["global_cursor_width"],
  4428. size=self.defaults["global_cursor_size"])
  4429. # Set the relative position label
  4430. dx = location[0] - float(self.rel_point1[0])
  4431. dy = location[1] - float(self.rel_point1[1])
  4432. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4433. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4434. # # Set the position label
  4435. #
  4436. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4437. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4438. units = self.defaults["units"].lower()
  4439. self.plotcanvas.text_hud.text = \
  4440. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4441. dx, units, dy, units, location[0], units, location[1], units)
  4442. self.inform.emit('[success] %s' % _("Done."))
  4443. return location
  4444. def on_locate(self, obj, fit_center=True):
  4445. """
  4446. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4447. :param obj: The object on which to locate certain points
  4448. :param fit_center: If to fit view. Boolean.
  4449. :return: A point location. (x, y) tuple.
  4450. """
  4451. self.defaults.report_usage("on_locate()")
  4452. if obj is None:
  4453. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4454. return 'fail'
  4455. class DialogBoxChoice(QtWidgets.QDialog):
  4456. def __init__(self, title=None, icon=None, choice='bl'):
  4457. """
  4458. :param title: string with the window title
  4459. """
  4460. super(DialogBoxChoice, self).__init__()
  4461. self.ok = False
  4462. self.setWindowIcon(icon)
  4463. self.setWindowTitle(str(title))
  4464. self.form = QtWidgets.QFormLayout(self)
  4465. self.ref_radio = RadioSet([
  4466. {"label": _("Bottom-Left"), "value": "bl"},
  4467. {"label": _("Top-Left"), "value": "tl"},
  4468. {"label": _("Bottom-Right"), "value": "br"},
  4469. {"label": _("Top-Right"), "value": "tr"},
  4470. {"label": _("Center"), "value": "c"}
  4471. ], orientation='vertical', stretch=False)
  4472. self.ref_radio.set_value(choice)
  4473. self.form.addRow(self.ref_radio)
  4474. self.button_box = QtWidgets.QDialogButtonBox(
  4475. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4476. Qt.Horizontal, parent=self)
  4477. self.form.addRow(self.button_box)
  4478. self.button_box.accepted.connect(self.accept)
  4479. self.button_box.rejected.connect(self.reject)
  4480. if self.exec_() == QtWidgets.QDialog.Accepted:
  4481. self.ok = True
  4482. self.location_point = self.ref_radio.get_value()
  4483. else:
  4484. self.ok = False
  4485. self.location_point = None
  4486. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4487. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4488. choice=self.defaults['global_locate_pt'])
  4489. if dia_box.ok is True:
  4490. try:
  4491. location_point = dia_box.location_point
  4492. self.defaults['global_locate_pt'] = dia_box.location_point
  4493. except Exception:
  4494. return
  4495. else:
  4496. return
  4497. loc_b = obj.bounds()
  4498. if location_point == 'bl':
  4499. location = (loc_b[0], loc_b[1])
  4500. elif location_point == 'tl':
  4501. location = (loc_b[0], loc_b[3])
  4502. elif location_point == 'br':
  4503. location = (loc_b[2], loc_b[1])
  4504. elif location_point == 'tr':
  4505. location = (loc_b[2], loc_b[3])
  4506. else:
  4507. # center
  4508. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4509. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4510. location = (cx, cy)
  4511. self.locate_signal.emit(location, location_point)
  4512. if fit_center:
  4513. self.plotcanvas.fit_center(loc=location)
  4514. cursor = QtGui.QCursor()
  4515. if self.is_legacy is False:
  4516. # I don't know where those differences come from but they are constant for the current
  4517. # execution of the application and they are multiples of a value around 0.0263mm.
  4518. # In a random way sometimes they are more sometimes they are less
  4519. # if units == 'MM':
  4520. # cal_factor = 0.0263
  4521. # else:
  4522. # cal_factor = 0.0263 / 25.4
  4523. cal_location = (location[0], location[1])
  4524. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4525. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4526. j_pos = (
  4527. int(canvas_origin.x() + round(jump_loc[0])),
  4528. int(canvas_origin.y() + round(jump_loc[1]))
  4529. )
  4530. cursor.setPos(j_pos[0], j_pos[1])
  4531. else:
  4532. # find the canvas origin which is in the top left corner
  4533. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4534. # determine the coordinates for the lowest left point of the canvas
  4535. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4536. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4537. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4538. # canvas) and the point (width, height) is in the top-right location
  4539. loc = self.plotcanvas.axes.transData.transform_point(location)
  4540. j_pos = (
  4541. int(x0 + loc[0]),
  4542. int(y0 - loc[1])
  4543. )
  4544. cursor.setPos(j_pos[0], j_pos[1])
  4545. self.plotcanvas.mouse = [location[0], location[1]]
  4546. if self.defaults["global_cursor_color_enabled"] is True:
  4547. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4548. else:
  4549. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4550. if self.grid_status():
  4551. # Update cursor
  4552. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4553. symbol='++', edge_color=self.cursor_color_3D,
  4554. edge_width=self.defaults["global_cursor_width"],
  4555. size=self.defaults["global_cursor_size"])
  4556. # Set the relative position label
  4557. self.dx = location[0] - float(self.rel_point1[0])
  4558. self.dy = location[1] - float(self.rel_point1[1])
  4559. # Set the position label
  4560. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4561. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4562. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4563. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4564. units = self.defaults["units"].lower()
  4565. self.plotcanvas.text_hud.text = \
  4566. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4567. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4568. self.inform.emit('[success] %s' % _("Done."))
  4569. return location
  4570. def on_copy_command(self):
  4571. """
  4572. Will copy a selection of objects, creating new objects.
  4573. :return:
  4574. """
  4575. self.defaults.report_usage("on_copy_command()")
  4576. def initialize(obj_init, app):
  4577. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4578. try:
  4579. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4580. except AttributeError:
  4581. pass
  4582. try:
  4583. obj_init.apertures = deepcopy(obj.apertures)
  4584. except AttributeError:
  4585. pass
  4586. try:
  4587. if obj.tools:
  4588. obj_init.tools = deepcopy(obj.tools)
  4589. except Exception as err:
  4590. log.debug("App.on_copy_command() --> %s" % str(err))
  4591. try:
  4592. obj_init.source_file = deepcopy(obj.source_file)
  4593. except (AttributeError, TypeError):
  4594. pass
  4595. def initialize_excellon(obj_init, app):
  4596. obj_init.source_file = deepcopy(obj.source_file)
  4597. obj_init.tools = deepcopy(obj.tools)
  4598. # drills are offset, so they need to be deep copied
  4599. obj_init.drills = deepcopy(obj.drills)
  4600. # slots are offset, so they need to be deep copied
  4601. obj_init.slots = deepcopy(obj.slots)
  4602. obj_init.create_geometry()
  4603. def initialize_script(obj_init, app_obj):
  4604. obj_init.source_file = deepcopy(obj.source_file)
  4605. def initialize_document(obj_init, app_obj):
  4606. obj_init.source_file = deepcopy(obj.source_file)
  4607. for obj in self.collection.get_selected():
  4608. obj_name = obj.options["name"]
  4609. try:
  4610. if isinstance(obj, ExcellonObject):
  4611. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4612. elif isinstance(obj, GerberObject):
  4613. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4614. elif isinstance(obj, GeometryObject):
  4615. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4616. elif isinstance(obj, ScriptObject):
  4617. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4618. elif isinstance(obj, DocumentObject):
  4619. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4620. except Exception as e:
  4621. return "Operation failed: %s" % str(e)
  4622. def on_copy_object2(self, custom_name):
  4623. def initialize_geometry(obj_init, app):
  4624. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4625. try:
  4626. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4627. except AttributeError:
  4628. pass
  4629. try:
  4630. obj_init.apertures = deepcopy(obj.apertures)
  4631. except AttributeError:
  4632. pass
  4633. try:
  4634. if obj.tools:
  4635. obj_init.tools = deepcopy(obj.tools)
  4636. except Exception as ee:
  4637. log.debug("on_copy_object2() --> %s" % str(ee))
  4638. def initialize_gerber(obj_init, app):
  4639. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4640. obj_init.apertures = deepcopy(obj.apertures)
  4641. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4642. def initialize_excellon(obj_init, app):
  4643. obj_init.tools = deepcopy(obj.tools)
  4644. # drills are offset, so they need to be deep copied
  4645. obj_init.drills = deepcopy(obj.drills)
  4646. # slots are offset, so they need to be deep copied
  4647. obj_init.slots = deepcopy(obj.slots)
  4648. obj_init.create_geometry()
  4649. for obj in self.collection.get_selected():
  4650. obj_name = obj.options["name"]
  4651. try:
  4652. if isinstance(obj, ExcellonObject):
  4653. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4654. elif isinstance(obj, GerberObject):
  4655. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4656. elif isinstance(obj, GeometryObject):
  4657. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4658. except Exception as er:
  4659. return "Operation failed: %s" % str(er)
  4660. def on_rename_object(self, text):
  4661. """
  4662. Will rename an object.
  4663. :param text: New name for the object.
  4664. :return:
  4665. """
  4666. self.defaults.report_usage("on_rename_object()")
  4667. named_obj = self.collection.get_active()
  4668. for obj in named_obj:
  4669. if obj is list:
  4670. self.on_rename_object(text)
  4671. else:
  4672. try:
  4673. obj.options['name'] = text
  4674. except Exception as e:
  4675. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4676. def convert_any2geo(self):
  4677. """
  4678. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4679. :return:
  4680. """
  4681. self.defaults.report_usage("convert_any2geo()")
  4682. def initialize(obj_init, app):
  4683. obj_init.solid_geometry = obj.solid_geometry
  4684. try:
  4685. obj_init.follow_geometry = obj.follow_geometry
  4686. except AttributeError:
  4687. pass
  4688. try:
  4689. obj_init.apertures = obj.apertures
  4690. except AttributeError:
  4691. pass
  4692. try:
  4693. if obj.tools:
  4694. obj_init.tools = obj.tools
  4695. except AttributeError:
  4696. pass
  4697. def initialize_excellon(obj_init, app):
  4698. # objs = self.collection.get_selected()
  4699. # GeometryObject.merge(objs, obj)
  4700. solid_geo = []
  4701. for tool in obj.tools:
  4702. for geo in obj.tools[tool]['solid_geometry']:
  4703. solid_geo.append(geo)
  4704. obj_init.solid_geometry = deepcopy(solid_geo)
  4705. if not self.collection.get_selected():
  4706. log.warning("App.convert_any2geo --> No object selected")
  4707. self.inform.emit('[WARNING_NOTCL] %s' %
  4708. _("No object is selected. Select an object and try again."))
  4709. return
  4710. for obj in self.collection.get_selected():
  4711. obj_name = obj.options["name"]
  4712. try:
  4713. if isinstance(obj, ExcellonObject):
  4714. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4715. else:
  4716. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4717. except Exception as e:
  4718. return "Operation failed: %s" % str(e)
  4719. def convert_any2gerber(self):
  4720. """
  4721. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4722. :return:
  4723. """
  4724. self.defaults.report_usage("convert_any2gerber()")
  4725. def initialize_geometry(obj_init, app):
  4726. apertures = {}
  4727. apid = 0
  4728. apertures[str(apid)] = {}
  4729. apertures[str(apid)]['geometry'] = []
  4730. for obj_orig in obj.solid_geometry:
  4731. new_elem = {}
  4732. new_elem['solid'] = obj_orig
  4733. try:
  4734. new_elem['follow'] = obj_orig.exterior
  4735. except AttributeError:
  4736. pass
  4737. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4738. apertures[str(apid)]['size'] = 0.0
  4739. apertures[str(apid)]['type'] = 'C'
  4740. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4741. obj_init.apertures = deepcopy(apertures)
  4742. def initialize_excellon(obj_init, app):
  4743. apertures = {}
  4744. apid = 10
  4745. for tool in obj.tools:
  4746. apertures[str(apid)] = {}
  4747. apertures[str(apid)]['geometry'] = []
  4748. for geo in obj.tools[tool]['solid_geometry']:
  4749. new_el = {}
  4750. new_el['solid'] = geo
  4751. new_el['follow'] = geo.exterior
  4752. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4753. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4754. apertures[str(apid)]['type'] = 'C'
  4755. apid += 1
  4756. # create solid_geometry
  4757. solid_geometry = []
  4758. for apid in apertures:
  4759. for geo_el in apertures[apid]['geometry']:
  4760. solid_geometry.append(geo_el['solid'])
  4761. solid_geometry = MultiPolygon(solid_geometry)
  4762. solid_geometry = solid_geometry.buffer(0.0000001)
  4763. obj_init.solid_geometry = deepcopy(solid_geometry)
  4764. obj_init.apertures = deepcopy(apertures)
  4765. # clear the working objects (perhaps not necessary due of Python GC)
  4766. apertures.clear()
  4767. if not self.collection.get_selected():
  4768. log.warning("App.convert_any2gerber --> No object selected")
  4769. self.inform.emit('[WARNING_NOTCL] %s' %
  4770. _("No object is selected. Select an object and try again."))
  4771. return
  4772. for obj in self.collection.get_selected():
  4773. obj_name = obj.options["name"]
  4774. try:
  4775. if isinstance(obj, ExcellonObject):
  4776. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4777. elif isinstance(obj, GeometryObject):
  4778. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4779. else:
  4780. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4781. except Exception as e:
  4782. return "Operation failed: %s" % str(e)
  4783. def abort_all_tasks(self):
  4784. """
  4785. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4786. on the first possible occasion.
  4787. :return:
  4788. """
  4789. if self.abort_flag is False:
  4790. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4791. self.abort_flag = True
  4792. self.cleanup.emit()
  4793. def app_is_idle(self):
  4794. if self.abort_flag:
  4795. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4796. self.abort_flag = False
  4797. def on_selectall(self):
  4798. """
  4799. Will draw a selection box shape around the selected objects.
  4800. :return:
  4801. """
  4802. self.defaults.report_usage("on_selectall()")
  4803. # delete the possible selection box around a possible selected object
  4804. self.delete_selection_shape()
  4805. for name in self.collection.get_names():
  4806. self.collection.set_active(name)
  4807. curr_sel_obj = self.collection.get_by_name(name)
  4808. # create the selection box around the selected object
  4809. if self.defaults['global_selection_shape'] is True:
  4810. self.draw_selection_shape(curr_sel_obj)
  4811. def on_preferences(self):
  4812. """
  4813. Adds the Preferences in a Tab in Plot Area
  4814. :return:
  4815. """
  4816. # add the tab if it was closed
  4817. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4818. # delete the absolute and relative position and messages in the infobar
  4819. self.ui.position_label.setText("")
  4820. # self.ui.rel_position_label.setText("")
  4821. # Switch plot_area to preferences page
  4822. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4823. # self.ui.show()
  4824. # detect changes in the preferences
  4825. for idx in range(self.ui.pref_tab_area.count()):
  4826. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4827. try:
  4828. try:
  4829. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4830. except (TypeError, AttributeError):
  4831. pass
  4832. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4833. except AttributeError:
  4834. pass
  4835. try:
  4836. try:
  4837. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4838. except (TypeError, AttributeError):
  4839. pass
  4840. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4841. except AttributeError:
  4842. pass
  4843. try:
  4844. try:
  4845. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4846. except (TypeError, AttributeError):
  4847. pass
  4848. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4849. except AttributeError:
  4850. pass
  4851. try:
  4852. try:
  4853. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4854. except (TypeError, AttributeError):
  4855. pass
  4856. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4857. except AttributeError:
  4858. pass
  4859. try:
  4860. try:
  4861. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4862. except (TypeError, AttributeError):
  4863. pass
  4864. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4865. except AttributeError:
  4866. pass
  4867. def on_tools_database(self, source='app'):
  4868. """
  4869. Adds the Tools Database in a Tab in Plot Area.
  4870. :return:
  4871. """
  4872. for idx in range(self.ui.plot_tab_area.count()):
  4873. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4874. # there can be only one instance of Tools Database at one time
  4875. return
  4876. if source == 'app':
  4877. self.tools_db_tab = ToolsDB2(
  4878. app=self,
  4879. parent=self.ui,
  4880. callback_on_edited=self.on_tools_db_edited,
  4881. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4882. )
  4883. elif source == 'ncc':
  4884. self.tools_db_tab = ToolsDB2(
  4885. app=self,
  4886. parent=self.ui,
  4887. callback_on_edited=self.on_tools_db_edited,
  4888. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4889. )
  4890. elif source == 'paint':
  4891. self.tools_db_tab = ToolsDB2(
  4892. app=self,
  4893. parent=self.ui,
  4894. callback_on_edited=self.on_tools_db_edited,
  4895. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4896. )
  4897. # add the tab if it was closed
  4898. try:
  4899. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4900. self.tools_db_tab.setObjectName("database_tab")
  4901. except Exception as e:
  4902. log.debug("App.on_tools_database() --> %s" % str(e))
  4903. return
  4904. # delete the absolute and relative position and messages in the infobar
  4905. self.ui.position_label.setText("")
  4906. # self.ui.rel_position_label.setText("")
  4907. # Switch plot_area to preferences page
  4908. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4909. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4910. self.tools_db_tab.ui_connect()
  4911. def on_tools_db_edited(self):
  4912. """
  4913. Executed whenever a tool is edited in Tools Database.
  4914. Will color the text of the Tools Database tab to Red color.
  4915. :return:
  4916. """
  4917. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4918. for idx in range(self.ui.plot_tab_area.count()):
  4919. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4920. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4921. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4922. self.tools_db_changed_flag = True
  4923. def on_geometry_tool_add_from_db_executed(self, tool):
  4924. """
  4925. Here add the tool from DB in the selected geometry object.
  4926. :return:
  4927. """
  4928. tool_from_db = deepcopy(tool)
  4929. obj = self.collection.get_active()
  4930. if isinstance(obj, GeometryObject):
  4931. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4932. # close the tab and delete it
  4933. for idx in range(self.ui.plot_tab_area.count()):
  4934. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4935. wdg = self.ui.plot_tab_area.widget(idx)
  4936. wdg.deleteLater()
  4937. self.ui.plot_tab_area.removeTab(idx)
  4938. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4939. else:
  4940. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4941. def on_plot_area_tab_closed(self, tab_obj_name):
  4942. """
  4943. Executed whenever a QTab is closed in the Plot Area.
  4944. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4945. :return:
  4946. """
  4947. if tab_obj_name == "preferences_tab":
  4948. self.preferencesUiManager.on_close_preferences_tab()
  4949. elif tab_obj_name == "database_tab":
  4950. # disconnect the signals from the table widget in tab
  4951. self.tools_db_tab.ui_disconnect()
  4952. if self.tools_db_changed_flag is True:
  4953. msgbox = QtWidgets.QMessageBox()
  4954. msgbox.setText(_("One or more Tools are edited.\n"
  4955. "Do you want to update the Tools Database?"))
  4956. msgbox.setWindowTitle(_("Save Tools Database"))
  4957. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4958. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4959. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4960. msgbox.setDefaultButton(bt_yes)
  4961. msgbox.exec_()
  4962. response = msgbox.clickedButton()
  4963. if response == bt_yes:
  4964. self.tools_db_tab.on_save_tools_db()
  4965. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4966. else:
  4967. self.tools_db_changed_flag = False
  4968. self.inform.emit('')
  4969. return
  4970. self.tools_db_tab.deleteLater()
  4971. elif tab_obj_name == "text_editor_tab":
  4972. self.toggle_codeeditor = False
  4973. elif tab_obj_name == "bookmarks_tab":
  4974. self.book_dialog_tab.rebuild_actions()
  4975. self.book_dialog_tab.deleteLater()
  4976. else:
  4977. return
  4978. # def on_plotarea_tab_closed(self, tab_idx):
  4979. # """
  4980. #
  4981. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4982. # :return:
  4983. # """
  4984. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4985. #
  4986. # if widget is not None:
  4987. # widget.deleteLater()
  4988. # self.ui.plot_tab_area.removeTab(tab_idx)
  4989. def on_flipy(self):
  4990. """
  4991. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4992. :return:
  4993. """
  4994. self.defaults.report_usage("on_flipy()")
  4995. obj_list = self.collection.get_selected()
  4996. xminlist = []
  4997. yminlist = []
  4998. xmaxlist = []
  4999. ymaxlist = []
  5000. if not obj_list:
  5001. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  5002. else:
  5003. try:
  5004. # first get a bounding box to fit all
  5005. for obj in obj_list:
  5006. xmin, ymin, xmax, ymax = obj.bounds()
  5007. xminlist.append(xmin)
  5008. yminlist.append(ymin)
  5009. xmaxlist.append(xmax)
  5010. ymaxlist.append(ymax)
  5011. # get the minimum x,y and maximum x,y for all objects selected
  5012. xminimal = min(xminlist)
  5013. yminimal = min(yminlist)
  5014. xmaximal = max(xmaxlist)
  5015. ymaximal = max(ymaxlist)
  5016. px = 0.5 * (xminimal + xmaximal)
  5017. py = 0.5 * (yminimal + ymaximal)
  5018. # execute mirroring
  5019. for obj in obj_list:
  5020. obj.mirror('X', [px, py])
  5021. obj.plot()
  5022. self.object_changed.emit(obj)
  5023. self.inform.emit('[success] %s' %
  5024. _("Flip on Y axis done."))
  5025. except Exception as e:
  5026. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5027. return
  5028. def on_flipx(self):
  5029. """
  5030. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5031. :return:
  5032. """
  5033. self.defaults.report_usage("on_flipx()")
  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' %
  5041. _("No object selected to Flip on X axis."))
  5042. else:
  5043. try:
  5044. # first get a bounding box to fit all
  5045. for obj in obj_list:
  5046. xmin, ymin, xmax, ymax = obj.bounds()
  5047. xminlist.append(xmin)
  5048. yminlist.append(ymin)
  5049. xmaxlist.append(xmax)
  5050. ymaxlist.append(ymax)
  5051. # get the minimum x,y and maximum x,y for all objects selected
  5052. xminimal = min(xminlist)
  5053. yminimal = min(yminlist)
  5054. xmaximal = max(xmaxlist)
  5055. ymaximal = max(ymaxlist)
  5056. px = 0.5 * (xminimal + xmaximal)
  5057. py = 0.5 * (yminimal + ymaximal)
  5058. # execute mirroring
  5059. for obj in obj_list:
  5060. obj.mirror('Y', [px, py])
  5061. obj.plot()
  5062. self.object_changed.emit(obj)
  5063. self.inform.emit('[success] %s' %
  5064. _("Flip on X axis done."))
  5065. except Exception as e:
  5066. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5067. return
  5068. def on_rotate(self, silent=False, preset=None):
  5069. """
  5070. Executed when Options -> Rotate Selection menu entry is clicked.
  5071. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5072. :param preset: A value to be used as predefined angle for rotation.
  5073. :return:
  5074. """
  5075. self.defaults.report_usage("on_rotate()")
  5076. obj_list = self.collection.get_selected()
  5077. xminlist = []
  5078. yminlist = []
  5079. xmaxlist = []
  5080. ymaxlist = []
  5081. if not obj_list:
  5082. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5083. else:
  5084. if silent is False:
  5085. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5086. min=-360, max=360, decimals=4,
  5087. init_val=float(self.defaults['tools_transform_rotate']))
  5088. num, ok = rotatebox.get_value()
  5089. else:
  5090. num = preset
  5091. ok = True
  5092. if ok:
  5093. try:
  5094. # first get a bounding box to fit all
  5095. for obj in obj_list:
  5096. xmin, ymin, xmax, ymax = obj.bounds()
  5097. xminlist.append(xmin)
  5098. yminlist.append(ymin)
  5099. xmaxlist.append(xmax)
  5100. ymaxlist.append(ymax)
  5101. # get the minimum x,y and maximum x,y for all objects selected
  5102. xminimal = min(xminlist)
  5103. yminimal = min(yminlist)
  5104. xmaximal = max(xmaxlist)
  5105. ymaximal = max(ymaxlist)
  5106. px = 0.5 * (xminimal + xmaximal)
  5107. py = 0.5 * (yminimal + ymaximal)
  5108. for sel_obj in obj_list:
  5109. sel_obj.rotate(-float(num), point=(px, py))
  5110. sel_obj.plot()
  5111. self.object_changed.emit(sel_obj)
  5112. self.inform.emit('[success] %s' %
  5113. _("Rotation done."))
  5114. except Exception as e:
  5115. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5116. return
  5117. def on_skewx(self):
  5118. """
  5119. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5120. :return:
  5121. """
  5122. self.defaults.report_usage("on_skewx()")
  5123. obj_list = self.collection.get_selected()
  5124. xminlist = []
  5125. yminlist = []
  5126. if not obj_list:
  5127. self.inform.emit('[WARNING_NOTCL] %s' %
  5128. _("No object selected to Skew/Shear on X axis."))
  5129. else:
  5130. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5131. min=-360, max=360, decimals=4,
  5132. init_val=float(self.defaults['tools_transform_skew_x']))
  5133. num, ok = skewxbox.get_value()
  5134. if ok:
  5135. # first get a bounding box to fit all
  5136. for obj in obj_list:
  5137. xmin, ymin, xmax, ymax = obj.bounds()
  5138. xminlist.append(xmin)
  5139. yminlist.append(ymin)
  5140. # get the minimum x,y and maximum x,y for all objects selected
  5141. xminimal = min(xminlist)
  5142. yminimal = min(yminlist)
  5143. for obj in obj_list:
  5144. obj.skew(num, 0, point=(xminimal, yminimal))
  5145. obj.plot()
  5146. self.object_changed.emit(obj)
  5147. self.inform.emit('[success] %s' %
  5148. _("Skew on X axis done."))
  5149. def on_skewy(self):
  5150. """
  5151. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5152. :return:
  5153. """
  5154. self.defaults.report_usage("on_skewy()")
  5155. obj_list = self.collection.get_selected()
  5156. xminlist = []
  5157. yminlist = []
  5158. if not obj_list:
  5159. self.inform.emit('[WARNING_NOTCL] %s' %
  5160. _("No object selected to Skew/Shear on Y axis."))
  5161. else:
  5162. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5163. min=-360, max=360, decimals=4,
  5164. init_val=float(self.defaults['tools_transform_skew_y']))
  5165. num, ok = skewybox.get_value()
  5166. if ok:
  5167. # first get a bounding box to fit all
  5168. for obj in obj_list:
  5169. xmin, ymin, xmax, ymax = obj.bounds()
  5170. xminlist.append(xmin)
  5171. yminlist.append(ymin)
  5172. # get the minimum x,y and maximum x,y for all objects selected
  5173. xminimal = min(xminlist)
  5174. yminimal = min(yminlist)
  5175. for obj in obj_list:
  5176. obj.skew(0, num, point=(xminimal, yminimal))
  5177. obj.plot()
  5178. self.object_changed.emit(obj)
  5179. self.inform.emit('[success] %s' %
  5180. _("Skew on Y axis done."))
  5181. def on_plots_updated(self):
  5182. """
  5183. Callback used to report when the plots have changed.
  5184. Adjust axes and zooms to fit.
  5185. :return: None
  5186. """
  5187. if self.is_legacy is False:
  5188. self.plotcanvas.update()
  5189. else:
  5190. self.plotcanvas.auto_adjust_axes()
  5191. self.on_zoom_fit(None)
  5192. self.collection.update_view()
  5193. # self.inform.emit(_("Plots updated ..."))
  5194. def on_toolbar_replot(self):
  5195. """
  5196. Callback for toolbar button. Re-plots all objects.
  5197. :return: None
  5198. """
  5199. self.defaults.report_usage("on_toolbar_replot")
  5200. self.log.debug("on_toolbar_replot()")
  5201. try:
  5202. self.collection.get_active().read_form()
  5203. except AttributeError:
  5204. self.log.debug("on_toolbar_replot(): AttributeError")
  5205. pass
  5206. self.plot_all()
  5207. def on_row_activated(self, index):
  5208. if index.isValid():
  5209. if index.internalPointer().parent_item != self.collection.root_item:
  5210. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5211. self.collection.on_item_activated(index)
  5212. def on_row_selected(self, obj_name):
  5213. """
  5214. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5215. It mean we clicked outside of the items and deselected all
  5216. :param obj_name:
  5217. :return:
  5218. """
  5219. if obj_name == 'none':
  5220. for act in self.ui.menuobjects.actions():
  5221. act.setChecked(False)
  5222. return
  5223. # get the name of the selected objects and add them to a list
  5224. name_list = []
  5225. for obj in self.collection.get_selected():
  5226. name_list.append(obj.options['name'])
  5227. # set all actions as unchecked but the ones selected make them checked
  5228. for act in self.ui.menuobjects.actions():
  5229. act.setChecked(False)
  5230. if act.text() in name_list:
  5231. act.setChecked(True)
  5232. def on_collection_updated(self, obj, state, old_name):
  5233. """
  5234. Create a menu from the object loaded in the collection.
  5235. :param obj: object that was changed (added, deleted, renamed)
  5236. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5237. :param old_name: the old name of the object before the action that triggered this slot happened
  5238. :return: None
  5239. """
  5240. icon_files = {
  5241. "gerber": self.resource_location + "/flatcam_icon16.png",
  5242. "excellon": self.resource_location + "/drill16.png",
  5243. "cncjob": self.resource_location + "/cnc16.png",
  5244. "geometry": self.resource_location + "/geometry16.png",
  5245. "script": self.resource_location + "/script_new16.png",
  5246. "document": self.resource_location + "/notes16_1.png"
  5247. }
  5248. if state == 'append':
  5249. for act in self.ui.menuobjects.actions():
  5250. try:
  5251. act.triggered.disconnect()
  5252. except TypeError:
  5253. pass
  5254. self.ui.menuobjects.clear()
  5255. gerber_list = []
  5256. exc_list = []
  5257. cncjob_list = []
  5258. geo_list = []
  5259. script_list = []
  5260. doc_list = []
  5261. for name in self.collection.get_names():
  5262. obj_named = self.collection.get_by_name(name)
  5263. if obj_named.kind == 'gerber':
  5264. gerber_list.append(name)
  5265. elif obj_named.kind == 'excellon':
  5266. exc_list.append(name)
  5267. elif obj_named.kind == 'cncjob':
  5268. cncjob_list.append(name)
  5269. elif obj_named.kind == 'geometry':
  5270. geo_list.append(name)
  5271. elif obj_named.kind == 'script':
  5272. script_list.append(name)
  5273. elif obj_named.kind == 'document':
  5274. doc_list.append(name)
  5275. def add_act(o_name):
  5276. obj_for_icon = self.collection.get_by_name(o_name)
  5277. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5278. add_action.setCheckable(True)
  5279. add_action.setText(o_name)
  5280. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5281. add_action.triggered.connect(
  5282. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5283. self.collection.set_inactive(o_name))
  5284. self.ui.menuobjects.addAction(add_action)
  5285. for name in gerber_list:
  5286. add_act(name)
  5287. self.ui.menuobjects.addSeparator()
  5288. for name in exc_list:
  5289. add_act(name)
  5290. self.ui.menuobjects.addSeparator()
  5291. for name in cncjob_list:
  5292. add_act(name)
  5293. self.ui.menuobjects.addSeparator()
  5294. for name in geo_list:
  5295. add_act(name)
  5296. self.ui.menuobjects.addSeparator()
  5297. for name in script_list:
  5298. add_act(name)
  5299. self.ui.menuobjects.addSeparator()
  5300. for name in doc_list:
  5301. add_act(name)
  5302. self.ui.menuobjects.addSeparator()
  5303. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5304. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5305. _('Select All')
  5306. )
  5307. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5308. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5309. _('Deselect All')
  5310. )
  5311. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5312. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5313. elif state == 'delete':
  5314. for act in self.ui.menuobjects.actions():
  5315. if act.text() == obj.options['name']:
  5316. try:
  5317. act.triggered.disconnect()
  5318. except TypeError:
  5319. pass
  5320. self.ui.menuobjects.removeAction(act)
  5321. break
  5322. elif state == 'rename':
  5323. for act in self.ui.menuobjects.actions():
  5324. if act.text() == old_name:
  5325. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5326. add_action.setText(obj.options['name'])
  5327. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5328. add_action.triggered.connect(
  5329. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5330. self.collection.set_inactive(obj.options['name']))
  5331. self.ui.menuobjects.insertAction(act, add_action)
  5332. try:
  5333. act.triggered.disconnect()
  5334. except TypeError:
  5335. pass
  5336. self.ui.menuobjects.removeAction(act)
  5337. break
  5338. elif state == 'delete_all':
  5339. for act in self.ui.menuobjects.actions():
  5340. try:
  5341. act.triggered.disconnect()
  5342. except TypeError:
  5343. pass
  5344. self.ui.menuobjects.clear()
  5345. self.ui.menuobjects.addSeparator()
  5346. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5347. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5348. _('Select All')
  5349. )
  5350. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5351. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5352. _('Deselect All')
  5353. )
  5354. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5355. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5356. def on_objects_selection(self, on_off):
  5357. obj_list = self.collection.get_names()
  5358. if on_off is True:
  5359. self.collection.set_all_active()
  5360. for act in self.ui.menuobjects.actions():
  5361. try:
  5362. act.setChecked(True)
  5363. except Exception:
  5364. pass
  5365. if obj_list:
  5366. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5367. else:
  5368. self.collection.set_all_inactive()
  5369. for act in self.ui.menuobjects.actions():
  5370. try:
  5371. act.setChecked(False)
  5372. except Exception:
  5373. pass
  5374. if obj_list:
  5375. self.inform.emit('%s' % _("Objects selection is cleared."))
  5376. else:
  5377. self.inform.emit('')
  5378. def grid_status(self):
  5379. return True if self.ui.grid_snap_btn.isChecked() else False
  5380. def populate_cmenu_grids(self):
  5381. units = self.defaults['units'].lower()
  5382. # for act in self.ui.cmenu_gridmenu.actions():
  5383. # act.triggered.disconnect()
  5384. self.ui.cmenu_gridmenu.clear()
  5385. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5386. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5387. _("Grid On/Off"))
  5388. grid_toggle.setCheckable(True)
  5389. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5390. self.ui.cmenu_gridmenu.addSeparator()
  5391. for grid in sorted_list:
  5392. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5393. "%s" % str(grid))
  5394. action.triggered.connect(self.set_grid)
  5395. self.ui.cmenu_gridmenu.addSeparator()
  5396. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5397. _("Add"))
  5398. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5399. _("Delete"))
  5400. grid_add.triggered.connect(self.on_grid_add)
  5401. grid_delete.triggered.connect(self.on_grid_delete)
  5402. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5403. def set_grid(self):
  5404. menu_action = self.sender()
  5405. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5406. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5407. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5408. def on_grid_add(self):
  5409. # ## Current application units in lower Case
  5410. units = self.defaults['units'].lower()
  5411. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5412. text=_('Enter a Grid Value:'),
  5413. min=0.0000, max=99.9999, decimals=4)
  5414. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5415. val, ok = grid_add_popup.get_value()
  5416. if ok:
  5417. if float(val) == 0:
  5418. self.inform.emit('[WARNING_NOTCL] %s' %
  5419. _("Please enter a grid value with non-zero value, in Float format."))
  5420. return
  5421. else:
  5422. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5423. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5424. self.inform.emit('[success] %s...' % _("New Grid added"))
  5425. else:
  5426. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  5427. else:
  5428. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  5429. def on_grid_delete(self):
  5430. # ## Current application units in lower Case
  5431. units = self.defaults['units'].lower()
  5432. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5433. text='Enter a Grid Value:',
  5434. min=0.0000, max=99.9999, decimals=4)
  5435. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5436. val, ok = grid_del_popup.get_value()
  5437. if ok:
  5438. if float(val) == 0:
  5439. self.inform.emit('[WARNING_NOTCL] %s' %
  5440. _("Please enter a grid value with non-zero value, in Float format."))
  5441. return
  5442. else:
  5443. try:
  5444. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5445. except ValueError:
  5446. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  5447. return
  5448. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5449. else:
  5450. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5451. def on_shortcut_list(self):
  5452. self.defaults.report_usage("on_shortcut_list()")
  5453. # add the tab if it was closed
  5454. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5455. # delete the absolute and relative position and messages in the infobar
  5456. self.ui.position_label.setText("")
  5457. # self.ui.rel_position_label.setText("")
  5458. # Switch plot_area to preferences page
  5459. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5460. # self.ui.show()
  5461. def on_select_tab(self, name):
  5462. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5463. if self.ui.splitter.sizes()[0] == 0:
  5464. self.ui.splitter.setSizes([1, 1])
  5465. else:
  5466. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5467. self.ui.splitter.setSizes([0, 1])
  5468. if name == 'project':
  5469. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5470. elif name == 'selected':
  5471. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5472. elif name == 'tool':
  5473. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5474. def on_copy_name(self):
  5475. self.defaults.report_usage("on_copy_name()")
  5476. obj = self.collection.get_active()
  5477. try:
  5478. name = obj.options["name"]
  5479. except AttributeError:
  5480. log.debug("on_copy_name() --> No object selected to copy it's name")
  5481. self.inform.emit('[WARNING_NOTCL]%s' %
  5482. _(" No object selected to copy it's name"))
  5483. return
  5484. self.clipboard.setText(name)
  5485. self.inform.emit(_("Name copied on clipboard ..."))
  5486. def on_mouse_click_over_plot(self, event):
  5487. """
  5488. Default actions are:
  5489. :param event: Contains information about the event, like which button
  5490. was clicked, the pixel coordinates and the axes coordinates.
  5491. :return: None
  5492. """
  5493. self.pos = []
  5494. if self.is_legacy is False:
  5495. event_pos = event.pos
  5496. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5497. # # Set the mouse button for panning
  5498. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5499. else:
  5500. event_pos = (event.xdata, event.ydata)
  5501. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5502. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5503. # So it can receive key presses
  5504. self.plotcanvas.native.setFocus()
  5505. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5506. if self.grid_status():
  5507. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5508. else:
  5509. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5510. try:
  5511. if event.button == 1:
  5512. # Reset here the relative coordinates so there is a new reference on the click position
  5513. if self.rel_point1 is None:
  5514. self.rel_point1 = self.pos
  5515. else:
  5516. self.rel_point2 = copy(self.rel_point1)
  5517. self.rel_point1 = self.pos
  5518. self.on_mouse_move_over_plot(event, origin_click=True)
  5519. except Exception as e:
  5520. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5521. def on_mouse_double_click_over_plot(self, event):
  5522. if event.button == 1:
  5523. self.doubleclick = True
  5524. def on_mouse_move_over_plot(self, event, origin_click=None):
  5525. """
  5526. Callback for the mouse motion event over the plot.
  5527. :param event: Contains information about the event.
  5528. :param origin_click
  5529. :return: None
  5530. """
  5531. if self.is_legacy is False:
  5532. event_pos = event.pos
  5533. if self.defaults["global_pan_button"] == '2':
  5534. pan_button = 2
  5535. else:
  5536. pan_button = 3
  5537. self.event_is_dragging = event.is_dragging
  5538. else:
  5539. event_pos = (event.xdata, event.ydata)
  5540. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5541. if self.defaults["global_pan_button"] == '2':
  5542. pan_button = 3
  5543. else:
  5544. pan_button = 2
  5545. self.event_is_dragging = self.plotcanvas.is_dragging
  5546. # So it can receive key presses but not when the Tcl Shell is active
  5547. if not self.ui.shell_dock.isVisible():
  5548. if not self.plotcanvas.native.hasFocus():
  5549. self.plotcanvas.native.setFocus()
  5550. self.pos_jump = event_pos
  5551. self.ui.popMenu.mouse_is_panning = False
  5552. if origin_click is None:
  5553. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5554. if event.button == pan_button and self.event_is_dragging == 1:
  5555. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5556. if self.ui.popMenu.popup_active:
  5557. self.ui.popMenu.popup_active = False
  5558. return
  5559. self.ui.popMenu.mouse_is_panning = True
  5560. return
  5561. if self.rel_point1 is not None:
  5562. try: # May fail in case mouse not within axes
  5563. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5564. if pos_canvas[0] is None or pos_canvas[1] is None:
  5565. return
  5566. if self.grid_status():
  5567. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5568. # Update cursor
  5569. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5570. symbol='++', edge_color=self.cursor_color_3D,
  5571. edge_width=self.defaults["global_cursor_width"],
  5572. size=self.defaults["global_cursor_size"])
  5573. else:
  5574. pos = (pos_canvas[0], pos_canvas[1])
  5575. self.dx = pos[0] - float(self.rel_point1[0])
  5576. self.dy = pos[1] - float(self.rel_point1[1])
  5577. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5578. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5579. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5580. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5581. units = self.defaults["units"].lower()
  5582. self.plotcanvas.text_hud.text = \
  5583. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5584. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5585. self.mouse = [pos[0], pos[1]]
  5586. # if the mouse is moved and the LMB is clicked then the action is a selection
  5587. if self.event_is_dragging == 1 and event.button == 1:
  5588. self.delete_selection_shape()
  5589. if self.dx < 0:
  5590. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5591. face_color=self.defaults['global_alt_sel_fill'])
  5592. self.selection_type = False
  5593. elif self.dx >= 0:
  5594. self.draw_moving_selection_shape(self.pos, pos)
  5595. self.selection_type = True
  5596. else:
  5597. self.selection_type = None
  5598. else:
  5599. self.selection_type = None
  5600. # hover effect - enabled in Preferences -> General -> GUI Settings
  5601. if self.defaults['global_hover']:
  5602. for obj in self.collection.get_list():
  5603. try:
  5604. # select the object(s) only if it is enabled (plotted)
  5605. if obj.options['plot']:
  5606. if obj not in self.collection.get_selected():
  5607. poly_obj = Polygon(
  5608. [(obj.options['xmin'], obj.options['ymin']),
  5609. (obj.options['xmax'], obj.options['ymin']),
  5610. (obj.options['xmax'], obj.options['ymax']),
  5611. (obj.options['xmin'], obj.options['ymax'])]
  5612. )
  5613. if Point(pos).within(poly_obj):
  5614. if obj.isHovering is False:
  5615. obj.isHovering = True
  5616. obj.notHovering = True
  5617. # create the selection box around the selected object
  5618. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5619. else:
  5620. if obj.notHovering is True:
  5621. obj.notHovering = False
  5622. obj.isHovering = False
  5623. self.delete_hover_shape()
  5624. except Exception:
  5625. # the Exception here will happen if we try to select on screen and we have an
  5626. # newly (and empty) just created Geometry or Excellon object that do not have the
  5627. # xmin, xmax, ymin, ymax options.
  5628. # In this case poly_obj creation (see above) will fail
  5629. pass
  5630. except Exception as e:
  5631. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5632. self.ui.position_label.setText("")
  5633. # self.ui.rel_position_label.setText("")
  5634. self.mouse = None
  5635. def on_mouse_click_release_over_plot(self, event):
  5636. """
  5637. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5638. and has been registered in ''self.__init__()''.
  5639. :param event: contains information about the event.
  5640. :return:
  5641. """
  5642. if self.is_legacy is False:
  5643. event_pos = event.pos
  5644. right_button = 2
  5645. else:
  5646. event_pos = (event.xdata, event.ydata)
  5647. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5648. right_button = 3
  5649. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5650. if self.grid_status():
  5651. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5652. else:
  5653. pos = (pos_canvas[0], pos_canvas[1])
  5654. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5655. # canvas menu
  5656. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5657. self.ui.popMenu.mouse_is_panning = False
  5658. self.cursor = QtGui.QCursor()
  5659. self.populate_cmenu_grids()
  5660. self.ui.popMenu.popup(self.cursor.pos())
  5661. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5662. # selection and then select a type of selection ("enclosing" or "touching")
  5663. if event.button == 1: # left click
  5664. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5665. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5666. if modifiers == QtCore.Qt.ShiftModifier:
  5667. # do not auto open the Project Tab
  5668. self.click_noproject = True
  5669. self.clipboard.setText(
  5670. self.defaults["global_point_clipboard_format"] %
  5671. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5672. )
  5673. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5674. return
  5675. if self.doubleclick is True:
  5676. self.doubleclick = False
  5677. if self.collection.get_selected():
  5678. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5679. if self.ui.splitter.sizes()[0] == 0:
  5680. self.ui.splitter.setSizes([1, 1])
  5681. try:
  5682. # delete the selection shape(S) as it may be in the way
  5683. self.delete_selection_shape()
  5684. self.delete_hover_shape()
  5685. except Exception as e:
  5686. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5687. return
  5688. else:
  5689. # WORKAROUND for LEGACY MODE
  5690. if self.is_legacy is True:
  5691. # if there is no move on canvas then we have no dragging selection
  5692. if self.dx == 0 or self.dy == 0:
  5693. self.selection_type = None
  5694. if self.selection_type is not None:
  5695. try:
  5696. self.selection_area_handler(self.pos, pos, self.selection_type)
  5697. self.selection_type = None
  5698. except Exception as e:
  5699. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5700. return
  5701. else:
  5702. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5703. if key_modifier == QtCore.Qt.ShiftModifier:
  5704. mod_key = 'Shift'
  5705. elif key_modifier == QtCore.Qt.ControlModifier:
  5706. mod_key = 'Control'
  5707. else:
  5708. mod_key = None
  5709. try:
  5710. if self.command_active is None:
  5711. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5712. # deselect, and if it's not selected then it will be selected
  5713. # If there is no active command (self.command_active is None) then we check if we clicked
  5714. # on a object by checking the bounding limits against mouse click position
  5715. if mod_key == self.defaults["global_mselect_key"]:
  5716. self.select_objects(key='multisel')
  5717. else:
  5718. # If there is no active command (self.command_active is None) then we check if
  5719. # we clicked on a object by checking the bounding limits against mouse click position
  5720. self.select_objects()
  5721. self.delete_hover_shape()
  5722. except Exception as e:
  5723. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5724. return
  5725. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5726. """
  5727. :param start_pos: mouse position when the selection LMB click was done
  5728. :param end_pos: mouse position when the left mouse button is released
  5729. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5730. :return:
  5731. """
  5732. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5733. # delete previous selection shape
  5734. self.delete_selection_shape()
  5735. # make all objects inactive
  5736. self.collection.set_all_inactive()
  5737. for obj in self.collection.get_list():
  5738. try:
  5739. # select the object(s) only if it is enabled (plotted)
  5740. if obj.options['plot']:
  5741. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5742. (obj.options['xmax'], obj.options['ymin']),
  5743. (obj.options['xmax'], obj.options['ymax']),
  5744. (obj.options['xmin'], obj.options['ymax'])])
  5745. if sel_type is True:
  5746. if poly_obj.within(poly_selection):
  5747. # create the selection box around the selected object
  5748. if self.defaults['global_selection_shape'] is True:
  5749. self.draw_selection_shape(obj)
  5750. self.collection.set_active(obj.options['name'])
  5751. else:
  5752. if poly_selection.intersects(poly_obj):
  5753. # create the selection box around the selected object
  5754. if self.defaults['global_selection_shape'] is True:
  5755. self.draw_selection_shape(obj)
  5756. self.collection.set_active(obj.options['name'])
  5757. obj.selection_shape_drawn = True
  5758. except Exception as e:
  5759. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5760. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5761. # In this case poly_obj creation (see above) will fail
  5762. log.debug("App.selection_area_handler() --> %s" % str(e))
  5763. def select_objects(self, key=None):
  5764. """
  5765. Will select objects clicked on canvas
  5766. :param key: for future use in cumulative selection
  5767. :return:
  5768. """
  5769. # list where we store the overlapped objects under our mouse left click position
  5770. if key is None:
  5771. self.objects_under_the_click_list = []
  5772. # Populate the list with the overlapped objects on the click position
  5773. curr_x, curr_y = self.pos
  5774. for obj in self.all_objects_list:
  5775. # ScriptObject and DocumentObject objects can't be selected
  5776. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5777. continue
  5778. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5779. continue
  5780. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5781. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5782. if obj.options['name'] not in self.objects_under_the_click_list:
  5783. if obj.options['plot']:
  5784. # add objects to the objects_under_the_click list only if the object is plotted
  5785. # (active and not disabled)
  5786. self.objects_under_the_click_list.append(obj.options['name'])
  5787. try:
  5788. if self.objects_under_the_click_list:
  5789. curr_sel_obj = self.collection.get_active()
  5790. # case when there is only an object under the click and we toggle it
  5791. if len(self.objects_under_the_click_list) == 1:
  5792. if curr_sel_obj is None:
  5793. self.collection.set_active(self.objects_under_the_click_list[0])
  5794. curr_sel_obj = self.collection.get_active()
  5795. # create the selection box around the selected object
  5796. if self.defaults['global_selection_shape'] is True:
  5797. self.draw_selection_shape(curr_sel_obj)
  5798. curr_sel_obj.selection_shape_drawn = True
  5799. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5800. self.on_objects_selection(False)
  5801. self.delete_selection_shape()
  5802. curr_sel_obj.selection_shape_drawn = False
  5803. self.collection.set_active(self.objects_under_the_click_list[0])
  5804. curr_sel_obj = self.collection.get_active()
  5805. # create the selection box around the selected object
  5806. if self.defaults['global_selection_shape'] is True:
  5807. self.draw_selection_shape(curr_sel_obj)
  5808. curr_sel_obj.selection_shape_drawn = True
  5809. self.selected_message(curr_sel_obj=curr_sel_obj)
  5810. elif curr_sel_obj.selection_shape_drawn is False:
  5811. if self.defaults['global_selection_shape'] is True:
  5812. self.draw_selection_shape(curr_sel_obj)
  5813. curr_sel_obj.selection_shape_drawn = True
  5814. else:
  5815. self.on_objects_selection(False)
  5816. self.delete_selection_shape()
  5817. if self.call_source != 'app':
  5818. self.call_source = 'app'
  5819. self.selected_message(curr_sel_obj=curr_sel_obj)
  5820. else:
  5821. # If there is no selected object
  5822. # make active the first element of the overlapped objects list
  5823. if self.collection.get_active() is None:
  5824. self.collection.set_active(self.objects_under_the_click_list[0])
  5825. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5826. name_sel_obj = self.collection.get_active().options['name']
  5827. # In case that there is a selected object but it is not in the overlapped object list
  5828. # make that object inactive and activate the first element in the overlapped object list
  5829. if name_sel_obj not in self.objects_under_the_click_list:
  5830. self.collection.set_inactive(name_sel_obj)
  5831. name_sel_obj = self.objects_under_the_click_list[0]
  5832. self.collection.set_active(name_sel_obj)
  5833. else:
  5834. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5835. self.collection.set_all_inactive()
  5836. self.collection.set_active(
  5837. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5838. curr_sel_obj = self.collection.get_active()
  5839. # delete the possible selection box around a possible selected object
  5840. self.delete_selection_shape()
  5841. curr_sel_obj.selection_shape_drawn = False
  5842. # create the selection box around the selected object
  5843. if self.defaults['global_selection_shape'] is True:
  5844. self.draw_selection_shape(curr_sel_obj)
  5845. curr_sel_obj.selection_shape_drawn = True
  5846. self.selected_message(curr_sel_obj=curr_sel_obj)
  5847. else:
  5848. # deselect everything
  5849. self.on_objects_selection(False)
  5850. # delete the possible selection box around a possible selected object
  5851. self.delete_selection_shape()
  5852. for o in self.collection.get_list():
  5853. o.selection_shape_drawn = False
  5854. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5855. # only when working on App
  5856. if self.call_source == 'app':
  5857. if self.click_noproject is False:
  5858. # if the Tool Tab is in focus don't change focus to Project Tab
  5859. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5860. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5861. else:
  5862. # restore auto open the Project Tab
  5863. self.click_noproject = False
  5864. # delete any text in the status bar, implicitly the last object name that was selected
  5865. # self.inform.emit("")
  5866. else:
  5867. self.call_source = 'app'
  5868. except Exception as e:
  5869. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5870. def selected_message(self, curr_sel_obj):
  5871. if curr_sel_obj:
  5872. if curr_sel_obj.kind == 'gerber':
  5873. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5874. color='green',
  5875. name=str(curr_sel_obj.options['name']),
  5876. tx=_("selected"))
  5877. )
  5878. elif curr_sel_obj.kind == 'excellon':
  5879. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5880. color='brown',
  5881. name=str(curr_sel_obj.options['name']),
  5882. tx=_("selected"))
  5883. )
  5884. elif curr_sel_obj.kind == 'cncjob':
  5885. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5886. color='blue',
  5887. name=str(curr_sel_obj.options['name']),
  5888. tx=_("selected"))
  5889. )
  5890. elif curr_sel_obj.kind == 'geometry':
  5891. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5892. color='red',
  5893. name=str(curr_sel_obj.options['name']),
  5894. tx=_("selected"))
  5895. )
  5896. def delete_hover_shape(self):
  5897. self.hover_shapes.clear()
  5898. self.hover_shapes.redraw()
  5899. def draw_hover_shape(self, sel_obj, color=None):
  5900. """
  5901. :param sel_obj: The object for which the hover shape must be drawn
  5902. :param color: The color of the hover shape
  5903. :return: None
  5904. """
  5905. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5906. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5907. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5908. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5909. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5910. if self.defaults['units'].upper() == 'MM':
  5911. hover_rect = hover_rect.buffer(-0.1)
  5912. hover_rect = hover_rect.buffer(0.2)
  5913. else:
  5914. hover_rect = hover_rect.buffer(-0.00393)
  5915. hover_rect = hover_rect.buffer(0.00787)
  5916. # if color:
  5917. # face = Color(color)
  5918. # face.alpha = 0.2
  5919. # outline = Color(color, alpha=0.8)
  5920. # else:
  5921. # face = Color(self.defaults['global_sel_fill'])
  5922. # face.alpha = 0.2
  5923. # outline = self.defaults['global_sel_line']
  5924. if color:
  5925. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5926. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5927. else:
  5928. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5929. outline = self.defaults['global_sel_line']
  5930. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5931. if self.is_legacy is True:
  5932. self.hover_shapes.redraw()
  5933. def delete_selection_shape(self):
  5934. self.move_tool.sel_shapes.clear()
  5935. self.move_tool.sel_shapes.redraw()
  5936. def draw_selection_shape(self, sel_obj, color=None):
  5937. """
  5938. Will draw a selection shape around the selected object.
  5939. :param sel_obj: The object for which the selection shape must be drawn
  5940. :param color: The color for the selection shape.
  5941. :return: None
  5942. """
  5943. if sel_obj is None:
  5944. return
  5945. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5946. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5947. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5948. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5949. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5950. if self.defaults['units'].upper() == 'MM':
  5951. sel_rect = sel_rect.buffer(-0.1)
  5952. sel_rect = sel_rect.buffer(0.2)
  5953. else:
  5954. sel_rect = sel_rect.buffer(-0.00393)
  5955. sel_rect = sel_rect.buffer(0.00787)
  5956. if color:
  5957. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5958. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5959. else:
  5960. if self.is_legacy is False:
  5961. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5962. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5963. else:
  5964. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5965. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5966. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5967. color=outline,
  5968. face_color=face,
  5969. update=True,
  5970. layer=0,
  5971. tolerance=None))
  5972. if self.is_legacy is True:
  5973. self.move_tool.sel_shapes.redraw()
  5974. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5975. """
  5976. Will draw a selection shape when dragging mouse on canvas.
  5977. :param old_coords: Old coordinates
  5978. :param coords: New coordinates
  5979. :param kwargs: Keyword arguments
  5980. :return:
  5981. """
  5982. if 'color' in kwargs:
  5983. color = kwargs['color']
  5984. else:
  5985. color = self.defaults['global_sel_line']
  5986. if 'face_color' in kwargs:
  5987. face_color = kwargs['face_color']
  5988. else:
  5989. face_color = self.defaults['global_sel_fill']
  5990. if 'face_alpha' in kwargs:
  5991. face_alpha = kwargs['face_alpha']
  5992. else:
  5993. face_alpha = 0.3
  5994. x0, y0 = old_coords
  5995. x1, y1 = coords
  5996. pt1 = (x0, y0)
  5997. pt2 = (x1, y0)
  5998. pt3 = (x1, y1)
  5999. pt4 = (x0, y1)
  6000. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6001. # color_t = Color(face_color)
  6002. # color_t.alpha = face_alpha
  6003. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  6004. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6005. layer=0, tolerance=None)
  6006. if self.is_legacy is True:
  6007. self.move_tool.sel_shapes.redraw()
  6008. def on_file_new_click(self):
  6009. """
  6010. Callback for menu item File -> New.
  6011. Executed on clicking the Menu -> File -> New Project
  6012. :return:
  6013. """
  6014. if self.collection.get_list() and self.should_we_save:
  6015. msgbox = QtWidgets.QMessageBox()
  6016. # msgbox.setText("<B>Save changes ...</B>")
  6017. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6018. "Creating a New project will delete them.\n"
  6019. "Do you want to Save the project?"))
  6020. msgbox.setWindowTitle(_("Save changes"))
  6021. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6022. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6023. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6024. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6025. msgbox.setDefaultButton(bt_yes)
  6026. msgbox.exec_()
  6027. response = msgbox.clickedButton()
  6028. if response == bt_yes:
  6029. self.on_file_saveprojectas()
  6030. elif response == bt_cancel:
  6031. return
  6032. elif response == bt_no:
  6033. self.on_file_new()
  6034. else:
  6035. self.on_file_new()
  6036. self.inform.emit('[success] %s...' % _("New Project created"))
  6037. def on_file_new(self, cli=None):
  6038. """
  6039. Returns the application to its startup state. This method is thread-safe.
  6040. :param cli: Boolean. If True this method was run from command line
  6041. :return: None
  6042. """
  6043. self.defaults.report_usage("on_file_new")
  6044. # Remove everything from memory
  6045. App.log.debug("on_file_new()")
  6046. # close any editor that might be open
  6047. if self.call_source != 'app':
  6048. self.editor2object(cleanup=True)
  6049. # ## EDITOR section
  6050. self.geo_editor = FlatCAMGeoEditor(self)
  6051. self.exc_editor = FlatCAMExcEditor(self)
  6052. self.grb_editor = FlatCAMGrbEditor(self)
  6053. # Clear pool
  6054. self.clear_pool()
  6055. for obj in self.collection.get_list():
  6056. # delete shapes left drawn from mark shape_collections, if any
  6057. if isinstance(obj, GerberObject):
  6058. try:
  6059. for el in obj.mark_shapes:
  6060. obj.mark_shapes[el].clear(update=True)
  6061. obj.mark_shapes[el].enabled = False
  6062. del el
  6063. except AttributeError:
  6064. pass
  6065. # also delete annotation shapes, if any
  6066. elif isinstance(obj, CNCJobObject):
  6067. try:
  6068. obj.text_col.enabled = False
  6069. del obj.text_col
  6070. obj.annotation.clear(update=True)
  6071. del obj.annotation
  6072. except AttributeError:
  6073. pass
  6074. # delete the exclusion areas
  6075. self.exc_areas.clear_shapes()
  6076. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6077. self.shell.init_tcl()
  6078. # delete any selection shape on canvas
  6079. self.delete_selection_shape()
  6080. # delete all FlatCAM objects
  6081. self.collection.delete_all()
  6082. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  6083. self.setup_component_editor()
  6084. # Clear project filename
  6085. self.project_filename = None
  6086. # Load the application defaults
  6087. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6088. # Re-fresh project options
  6089. self.on_options_app2project()
  6090. # Init FlatCAMTools
  6091. self.init_tools()
  6092. # Try to close all tabs in the PlotArea but only if the GUI is active (CLI is None)
  6093. if cli is None:
  6094. # we need to go in reverse because once we remove a tab then the index changes
  6095. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  6096. # and so on. Therefore the deletion should be done in reverse
  6097. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  6098. for index in range(wdg_count, -1, -1):
  6099. try:
  6100. self.ui.plot_tab_area.closeTab(index)
  6101. except Exception as e:
  6102. log.debug("App.on_file_new() --> %s" % str(e))
  6103. # # And then add again the Plot Area
  6104. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  6105. self.ui.plot_tab_area.protectTab(0)
  6106. # take the focus of the Notebook on Project Tab.
  6107. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6108. self.set_ui_title(name=_("New Project - Not saved"))
  6109. def obj_properties(self):
  6110. """
  6111. Will launch the object Properties Tool
  6112. :return:
  6113. """
  6114. self.defaults.report_usage("obj_properties()")
  6115. self.properties_tool.run(toggle=False)
  6116. def on_project_context_save(self):
  6117. """
  6118. Wrapper, will save the object function of it's type
  6119. :return:
  6120. """
  6121. obj = self.collection.get_active()
  6122. if type(obj) == GeometryObject:
  6123. self.on_file_exportdxf()
  6124. elif type(obj) == ExcellonObject:
  6125. self.on_file_saveexcellon()
  6126. elif type(obj) == CNCJobObject:
  6127. obj.on_exportgcode_button_click()
  6128. elif type(obj) == GerberObject:
  6129. self.on_file_savegerber()
  6130. elif type(obj) == ScriptObject:
  6131. self.on_file_savescript()
  6132. elif type(obj) == DocumentObject:
  6133. self.on_file_savedocument()
  6134. def obj_move(self):
  6135. """
  6136. Callback for the Move menu entry in various Context Menu's.
  6137. :return:
  6138. """
  6139. self.defaults.report_usage("obj_move()")
  6140. self.move_tool.run(toggle=False)
  6141. def on_fileopengerber(self, signal, name=None):
  6142. """
  6143. File menu callback for opening a Gerber.
  6144. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6145. :param name:
  6146. :return: None
  6147. """
  6148. self.defaults.report_usage("on_fileopengerber")
  6149. App.log.debug("on_fileopengerber()")
  6150. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6151. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6152. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6153. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6154. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6155. "*.mil);;" \
  6156. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6157. "Allegro Files (*.art);;" \
  6158. "Mentor Files (*.pho *.gdo);;" \
  6159. "All Files (*.*)"
  6160. if name is None:
  6161. try:
  6162. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6163. directory=self.get_last_folder(),
  6164. filter=_filter_)
  6165. except TypeError:
  6166. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6167. filenames = [str(filename) for filename in filenames]
  6168. else:
  6169. filenames = [name]
  6170. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6171. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6172. _("Opening Gerber file.")),
  6173. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6174. color=QtGui.QColor("gray"))
  6175. if len(filenames) == 0:
  6176. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6177. else:
  6178. for filename in filenames:
  6179. if filename != '':
  6180. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6181. def on_fileopenexcellon(self, signal, name=None):
  6182. """
  6183. File menu callback for opening an Excellon file.
  6184. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6185. :param name:
  6186. :return: None
  6187. """
  6188. self.defaults.report_usage("on_fileopenexcellon")
  6189. App.log.debug("on_fileopenexcellon()")
  6190. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6191. "All Files (*.*)"
  6192. if name is None:
  6193. try:
  6194. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6195. directory=self.get_last_folder(),
  6196. filter=_filter_)
  6197. except TypeError:
  6198. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6199. filenames = [str(filename) for filename in filenames]
  6200. else:
  6201. filenames = [str(name)]
  6202. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6203. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6204. _("Opening Excellon file.")),
  6205. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6206. color=QtGui.QColor("gray"))
  6207. if len(filenames) == 0:
  6208. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6209. else:
  6210. for filename in filenames:
  6211. if filename != '':
  6212. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6213. def on_fileopengcode(self, signal, name=None):
  6214. """
  6215. File menu call back for opening gcode.
  6216. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6217. :param name:
  6218. :return:
  6219. """
  6220. self.defaults.report_usage("on_fileopengcode")
  6221. App.log.debug("on_fileopengcode()")
  6222. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6223. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6224. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6225. "All Files (*.*)"
  6226. if name is None:
  6227. try:
  6228. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6229. directory=self.get_last_folder(),
  6230. filter=_filter_)
  6231. except TypeError:
  6232. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6233. filenames = [str(filename) for filename in filenames]
  6234. else:
  6235. filenames = [name]
  6236. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6237. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6238. _("Opening G-Code file.")),
  6239. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6240. color=QtGui.QColor("gray"))
  6241. if len(filenames) == 0:
  6242. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6243. else:
  6244. for filename in filenames:
  6245. if filename != '':
  6246. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6247. def on_file_openproject(self, signal):
  6248. """
  6249. File menu callback for opening a project.
  6250. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6251. :return: None
  6252. """
  6253. self.defaults.report_usage("on_file_openproject")
  6254. App.log.debug("on_file_openproject()")
  6255. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6256. try:
  6257. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6258. directory=self.get_last_folder(), filter=_filter_)
  6259. except TypeError:
  6260. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6261. # The Qt methods above will return a QString which can cause problems later.
  6262. # So far json.dump() will fail to serialize it.
  6263. # TODO: Improve the serialization methods and remove this fix.
  6264. filename = str(filename)
  6265. if filename == "":
  6266. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6267. else:
  6268. # self.worker_task.emit({'fcn': self.open_project,
  6269. # 'params': [filename]})
  6270. # The above was failing because open_project() is not
  6271. # thread safe. The new_project()
  6272. self.open_project(filename)
  6273. def on_fileopenhpgl2(self, signal, name=None):
  6274. """
  6275. File menu callback for opening a HPGL2.
  6276. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6277. :param name:
  6278. :return: None
  6279. """
  6280. self.defaults.report_usage("on_fileopenhpgl2")
  6281. App.log.debug("on_fileopenhpgl2()")
  6282. _filter_ = "HPGL2 Files (*.plt);;" \
  6283. "All Files (*.*)"
  6284. if name is None:
  6285. try:
  6286. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6287. directory=self.get_last_folder(),
  6288. filter=_filter_)
  6289. except TypeError:
  6290. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6291. filenames = [str(filename) for filename in filenames]
  6292. else:
  6293. filenames = [name]
  6294. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6295. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6296. _("Opening HPGL2 file.")),
  6297. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6298. color=QtGui.QColor("gray"))
  6299. if len(filenames) == 0:
  6300. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6301. else:
  6302. for filename in filenames:
  6303. if filename != '':
  6304. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6305. def on_file_openconfig(self, signal):
  6306. """
  6307. File menu callback for opening a config file.
  6308. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6309. :return: None
  6310. """
  6311. self.defaults.report_usage("on_file_openconfig")
  6312. App.log.debug("on_file_openconfig()")
  6313. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6314. try:
  6315. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6316. directory=self.data_path, filter=_filter_)
  6317. except TypeError:
  6318. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6319. filter=_filter_)
  6320. if filename == "":
  6321. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6322. else:
  6323. self.open_config_file(filename)
  6324. def on_file_exportsvg(self):
  6325. """
  6326. Callback for menu item File->Export SVG.
  6327. :return: None
  6328. """
  6329. self.defaults.report_usage("on_file_exportsvg")
  6330. App.log.debug("on_file_exportsvg()")
  6331. obj = self.collection.get_active()
  6332. if obj is None:
  6333. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6334. msg = _("Please Select a Geometry object to export")
  6335. msgbox = QtWidgets.QMessageBox()
  6336. msgbox.setInformativeText(msg)
  6337. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6338. msgbox.setDefaultButton(bt_ok)
  6339. msgbox.exec_()
  6340. return
  6341. # Check for more compatible types and add as required
  6342. if (not isinstance(obj, GeometryObject)
  6343. and not isinstance(obj, GerberObject)
  6344. and not isinstance(obj, CNCJobObject)
  6345. and not isinstance(obj, ExcellonObject)):
  6346. msg = '[ERROR_NOTCL] %s' % \
  6347. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6348. msgbox = QtWidgets.QMessageBox()
  6349. msgbox.setInformativeText(msg)
  6350. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6351. msgbox.setDefaultButton(bt_ok)
  6352. msgbox.exec_()
  6353. return
  6354. name = obj.options["name"]
  6355. _filter = "SVG File (*.svg);;All Files (*.*)"
  6356. try:
  6357. filename, _f = FCFileSaveDialog.get_saved_filename(
  6358. caption=_("Export SVG"),
  6359. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6360. filter=_filter)
  6361. except TypeError:
  6362. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6363. filename = str(filename)
  6364. if filename == "":
  6365. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6366. return
  6367. else:
  6368. self.export_svg(name, filename)
  6369. if self.defaults["global_open_style"] is False:
  6370. self.file_opened.emit("SVG", filename)
  6371. self.file_saved.emit("SVG", filename)
  6372. def on_file_exportpng(self):
  6373. self.defaults.report_usage("on_file_exportpng")
  6374. App.log.debug("on_file_exportpng()")
  6375. self.date = str(datetime.today()).rpartition('.')[0]
  6376. self.date = ''.join(c for c in self.date if c not in ':-')
  6377. self.date = self.date.replace(' ', '_')
  6378. if self.is_legacy is False:
  6379. image = _screenshot()
  6380. data = np.asarray(image)
  6381. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6382. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6383. return
  6384. filter_ = "PNG File (*.png);;All Files (*.*)"
  6385. try:
  6386. filename, _f = FCFileSaveDialog.get_saved_filename(
  6387. caption=_("Export PNG Image"),
  6388. directory=self.get_last_save_folder() + '/png_' + self.date,
  6389. filter=filter_)
  6390. except TypeError:
  6391. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6392. filename = str(filename)
  6393. if filename == "":
  6394. self.inform.emit(_("Cancelled."))
  6395. return
  6396. else:
  6397. if self.is_legacy is False:
  6398. write_png(filename, data)
  6399. else:
  6400. self.plotcanvas.figure.savefig(filename)
  6401. if self.defaults["global_open_style"] is False:
  6402. self.file_opened.emit("png", filename)
  6403. self.file_saved.emit("png", filename)
  6404. def on_file_savegerber(self):
  6405. """
  6406. Callback for menu item in Project context menu.
  6407. :return: None
  6408. """
  6409. self.defaults.report_usage("on_file_savegerber")
  6410. App.log.debug("on_file_savegerber()")
  6411. obj = self.collection.get_active()
  6412. if obj is None:
  6413. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6414. return
  6415. # Check for more compatible types and add as required
  6416. if not isinstance(obj, GerberObject):
  6417. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6418. return
  6419. name = self.collection.get_active().options["name"]
  6420. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6421. try:
  6422. filename, _f = FCFileSaveDialog.get_saved_filename(
  6423. caption="Save Gerber source file",
  6424. directory=self.get_last_save_folder() + '/' + name,
  6425. filter=_filter)
  6426. except TypeError:
  6427. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6428. filename = str(filename)
  6429. if filename == "":
  6430. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6431. return
  6432. else:
  6433. self.save_source_file(name, filename)
  6434. if self.defaults["global_open_style"] is False:
  6435. self.file_opened.emit("Gerber", filename)
  6436. self.file_saved.emit("Gerber", filename)
  6437. def on_file_savescript(self):
  6438. """
  6439. Callback for menu item in Project context menu.
  6440. :return: None
  6441. """
  6442. self.defaults.report_usage("on_file_savescript")
  6443. App.log.debug("on_file_savescript()")
  6444. obj = self.collection.get_active()
  6445. if obj is None:
  6446. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6447. return
  6448. # Check for more compatible types and add as required
  6449. if not isinstance(obj, ScriptObject):
  6450. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6451. return
  6452. name = self.collection.get_active().options["name"]
  6453. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6454. try:
  6455. filename, _f = FCFileSaveDialog.get_saved_filename(
  6456. caption="Save Script source file",
  6457. directory=self.get_last_save_folder() + '/' + name,
  6458. filter=_filter)
  6459. except TypeError:
  6460. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6461. filename = str(filename)
  6462. if filename == "":
  6463. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6464. return
  6465. else:
  6466. self.save_source_file(name, filename)
  6467. if self.defaults["global_open_style"] is False:
  6468. self.file_opened.emit("Script", filename)
  6469. self.file_saved.emit("Script", filename)
  6470. def on_file_savedocument(self):
  6471. """
  6472. Callback for menu item in Project context menu.
  6473. :return: None
  6474. """
  6475. self.defaults.report_usage("on_file_savedocument")
  6476. App.log.debug("on_file_savedocument()")
  6477. obj = self.collection.get_active()
  6478. if obj is None:
  6479. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6480. return
  6481. # Check for more compatible types and add as required
  6482. if not isinstance(obj, ScriptObject):
  6483. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6484. return
  6485. name = self.collection.get_active().options["name"]
  6486. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6487. try:
  6488. filename, _f = FCFileSaveDialog.get_saved_filename(
  6489. caption="Save Document source file",
  6490. directory=self.get_last_save_folder() + '/' + name,
  6491. filter=_filter)
  6492. except TypeError:
  6493. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6494. filename = str(filename)
  6495. if filename == "":
  6496. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6497. return
  6498. else:
  6499. self.save_source_file(name, filename)
  6500. if self.defaults["global_open_style"] is False:
  6501. self.file_opened.emit("Document", filename)
  6502. self.file_saved.emit("Document", filename)
  6503. def on_file_saveexcellon(self):
  6504. """
  6505. Callback for menu item in project context menu.
  6506. :return: None
  6507. """
  6508. self.defaults.report_usage("on_file_saveexcellon")
  6509. App.log.debug("on_file_saveexcellon()")
  6510. obj = self.collection.get_active()
  6511. if obj is None:
  6512. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6513. return
  6514. # Check for more compatible types and add as required
  6515. if not isinstance(obj, ExcellonObject):
  6516. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6517. return
  6518. name = self.collection.get_active().options["name"]
  6519. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6520. try:
  6521. filename, _f = FCFileSaveDialog.get_saved_filename(
  6522. caption=_("Save Excellon source file"),
  6523. directory=self.get_last_save_folder() + '/' + name,
  6524. filter=_filter)
  6525. except TypeError:
  6526. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6527. filename = str(filename)
  6528. if filename == "":
  6529. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6530. return
  6531. else:
  6532. self.save_source_file(name, filename)
  6533. if self.defaults["global_open_style"] is False:
  6534. self.file_opened.emit("Excellon", filename)
  6535. self.file_saved.emit("Excellon", filename)
  6536. def on_file_exportexcellon(self):
  6537. """
  6538. Callback for menu item File->Export->Excellon.
  6539. :return: None
  6540. """
  6541. self.defaults.report_usage("on_file_exportexcellon")
  6542. App.log.debug("on_file_exportexcellon()")
  6543. obj = self.collection.get_active()
  6544. if obj is None:
  6545. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6546. return
  6547. # Check for more compatible types and add as required
  6548. if not isinstance(obj, ExcellonObject):
  6549. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6550. return
  6551. name = self.collection.get_active().options["name"]
  6552. _filter = self.defaults["excellon_save_filters"]
  6553. try:
  6554. filename, _f = FCFileSaveDialog.get_saved_filename(
  6555. caption=_("Export Excellon"),
  6556. directory=self.get_last_save_folder() + '/' + name,
  6557. filter=_filter)
  6558. except TypeError:
  6559. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6560. filename = str(filename)
  6561. if filename == "":
  6562. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6563. return
  6564. else:
  6565. used_extension = filename.rpartition('.')[2]
  6566. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6567. self.export_excellon(name, filename)
  6568. if self.defaults["global_open_style"] is False:
  6569. self.file_opened.emit("Excellon", filename)
  6570. self.file_saved.emit("Excellon", filename)
  6571. def on_file_exportgerber(self):
  6572. """
  6573. Callback for menu item File->Export->Gerber.
  6574. :return: None
  6575. """
  6576. self.defaults.report_usage("on_file_exportgerber")
  6577. App.log.debug("on_file_exportgerber()")
  6578. obj = self.collection.get_active()
  6579. if obj is None:
  6580. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6581. return
  6582. # Check for more compatible types and add as required
  6583. if not isinstance(obj, GerberObject):
  6584. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6585. return
  6586. name = self.collection.get_active().options["name"]
  6587. _filter_ = self.defaults['gerber_save_filters']
  6588. try:
  6589. filename, _f = FCFileSaveDialog.get_saved_filename(
  6590. caption=_("Export Gerber"),
  6591. directory=self.get_last_save_folder() + '/' + name,
  6592. filter=_filter_)
  6593. except TypeError:
  6594. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6595. filename = str(filename)
  6596. if filename == "":
  6597. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6598. return
  6599. else:
  6600. used_extension = filename.rpartition('.')[2]
  6601. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6602. self.export_gerber(name, filename)
  6603. if self.defaults["global_open_style"] is False:
  6604. self.file_opened.emit("Gerber", filename)
  6605. self.file_saved.emit("Gerber", filename)
  6606. def on_file_exportdxf(self):
  6607. """
  6608. Callback for menu item File->Export DXF.
  6609. :return: None
  6610. """
  6611. self.defaults.report_usage("on_file_exportdxf")
  6612. App.log.debug("on_file_exportdxf()")
  6613. obj = self.collection.get_active()
  6614. if obj is None:
  6615. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6616. msg = _("Please Select a Geometry object to export")
  6617. msgbox = QtWidgets.QMessageBox()
  6618. msgbox.setInformativeText(msg)
  6619. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6620. msgbox.setDefaultButton(bt_ok)
  6621. msgbox.exec_()
  6622. return
  6623. # Check for more compatible types and add as required
  6624. if not isinstance(obj, GeometryObject):
  6625. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6626. msgbox = QtWidgets.QMessageBox()
  6627. msgbox.setInformativeText(msg)
  6628. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6629. msgbox.setDefaultButton(bt_ok)
  6630. msgbox.exec_()
  6631. return
  6632. name = self.collection.get_active().options["name"]
  6633. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6634. try:
  6635. filename, _f = FCFileSaveDialog.get_saved_filename(
  6636. caption=_("Export DXF"),
  6637. directory=self.get_last_save_folder() + '/' + name,
  6638. filter=_filter_)
  6639. except TypeError:
  6640. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6641. filename = str(filename)
  6642. if filename == "":
  6643. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6644. return
  6645. else:
  6646. self.export_dxf(name, filename)
  6647. if self.defaults["global_open_style"] is False:
  6648. self.file_opened.emit("DXF", filename)
  6649. self.file_saved.emit("DXF", filename)
  6650. def on_file_importsvg(self, type_of_obj):
  6651. """
  6652. Callback for menu item File->Import SVG.
  6653. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6654. :type type_of_obj: str
  6655. :return: None
  6656. """
  6657. self.defaults.report_usage("on_file_importsvg")
  6658. App.log.debug("on_file_importsvg()")
  6659. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6660. try:
  6661. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6662. directory=self.get_last_folder(), filter=_filter_)
  6663. except TypeError:
  6664. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6665. filter=_filter_)
  6666. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6667. type_of_obj = "geometry"
  6668. filenames = [str(filename) for filename in filenames]
  6669. if len(filenames) == 0:
  6670. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6671. else:
  6672. for filename in filenames:
  6673. if filename != '':
  6674. self.worker_task.emit({'fcn': self.import_svg,
  6675. 'params': [filename, type_of_obj]})
  6676. def on_file_importdxf(self, type_of_obj):
  6677. """
  6678. Callback for menu item File->Import DXF.
  6679. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6680. :type type_of_obj: str
  6681. :return: None
  6682. """
  6683. self.defaults.report_usage("on_file_importdxf")
  6684. App.log.debug("on_file_importdxf()")
  6685. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6686. try:
  6687. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6688. directory=self.get_last_folder(),
  6689. filter=_filter_)
  6690. except TypeError:
  6691. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6692. filter=_filter_)
  6693. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6694. type_of_obj = "geometry"
  6695. filenames = [str(filename) for filename in filenames]
  6696. if len(filenames) == 0:
  6697. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6698. else:
  6699. for filename in filenames:
  6700. if filename != '':
  6701. self.worker_task.emit({'fcn': self.import_dxf,
  6702. 'params': [filename, type_of_obj]})
  6703. # ###############################################################################################################
  6704. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6705. # ###############################################################################################################
  6706. def init_code_editor(self, name):
  6707. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6708. # add the tab if it was closed
  6709. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6710. self.text_editor_tab.setObjectName('text_editor_tab')
  6711. # delete the absolute and relative position and messages in the infobar
  6712. self.ui.position_label.setText("")
  6713. # self.ui.rel_position_label.setText("")
  6714. # first clear previous text in text editor (if any)
  6715. self.text_editor_tab.code_editor.clear()
  6716. self.text_editor_tab.code_editor.setReadOnly(False)
  6717. self.toggle_codeeditor = True
  6718. self.text_editor_tab.code_editor.completer_enable = False
  6719. self.text_editor_tab.buttonRun.hide()
  6720. # make sure to keep a reference to the code editor
  6721. self.reference_code_editor = self.text_editor_tab.code_editor
  6722. # Switch plot_area to CNCJob tab
  6723. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6724. def on_view_source(self):
  6725. """
  6726. Called when the user wants to see the source file of the selected object
  6727. :return:
  6728. """
  6729. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6730. self.proc_container.view.set_busy(_("Loading..."))
  6731. try:
  6732. obj = self.collection.get_active()
  6733. except Exception as e:
  6734. log.debug("App.on_view_source() --> %s" % str(e))
  6735. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6736. return 'fail'
  6737. if obj is None:
  6738. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6739. return 'fail'
  6740. flt = "All Files (*.*)"
  6741. if obj.kind == 'gerber':
  6742. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6743. elif obj.kind == 'excellon':
  6744. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6745. elif obj.kind == 'cncjob':
  6746. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6747. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6748. # add the tab if it was closed
  6749. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6750. self.source_editor_tab.setObjectName('source_editor_tab')
  6751. # delete the absolute and relative position and messages in the infobar
  6752. self.ui.position_label.setText("")
  6753. # self.ui.rel_position_label.setText("")
  6754. # first clear previous text in text editor (if any)
  6755. self.source_editor_tab.code_editor.clear()
  6756. self.source_editor_tab.code_editor.setReadOnly(False)
  6757. self.source_editor_tab.code_editor.completer_enable = False
  6758. self.source_editor_tab.buttonRun.hide()
  6759. # Switch plot_area to CNCJob tab
  6760. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6761. try:
  6762. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6763. except TypeError:
  6764. pass
  6765. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6766. try:
  6767. self.source_editor_tab.buttonSave.clicked.disconnect()
  6768. except TypeError:
  6769. pass
  6770. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6771. # then append the text from GCode to the text editor
  6772. if obj.kind == 'cncjob':
  6773. try:
  6774. file = obj.export_gcode(
  6775. preamble=self.defaults["cncjob_prepend"],
  6776. postamble=self.defaults["cncjob_append"],
  6777. to_file=True)
  6778. if file == 'fail':
  6779. return 'fail'
  6780. except AttributeError:
  6781. self.inform.emit('[WARNING_NOTCL] %s' %
  6782. _("There is no selected object for which to see it's source file code."))
  6783. return 'fail'
  6784. else:
  6785. try:
  6786. file = StringIO(obj.source_file)
  6787. except (AttributeError, TypeError):
  6788. self.inform.emit('[WARNING_NOTCL] %s' %
  6789. _("There is no selected object for which to see it's source file code."))
  6790. return 'fail'
  6791. self.source_editor_tab.t_frame.hide()
  6792. try:
  6793. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6794. # for line in file:
  6795. # QtWidgets.QApplication.processEvents()
  6796. # proc_line = str(line).strip('\n')
  6797. # self.source_editor_tab.code_editor.append(proc_line)
  6798. except Exception as e:
  6799. log.debug('App.on_view_source() -->%s' % str(e))
  6800. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6801. return
  6802. self.source_editor_tab.handleTextChanged()
  6803. self.source_editor_tab.t_frame.show()
  6804. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6805. self.proc_container.view.set_idle()
  6806. # self.ui.show()
  6807. def on_toggle_code_editor(self):
  6808. self.defaults.report_usage("on_toggle_code_editor()")
  6809. if self.toggle_codeeditor is False:
  6810. self.init_code_editor(name=_("Code Editor"))
  6811. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6812. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6813. self.text_editor_tab.buttonSave.clicked.disconnect()
  6814. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6815. else:
  6816. for idx in range(self.ui.plot_tab_area.count()):
  6817. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6818. self.ui.plot_tab_area.closeTab(idx)
  6819. break
  6820. self.toggle_codeeditor = False
  6821. def on_code_editor_close(self):
  6822. self.toggle_codeeditor = False
  6823. def goto_text_line(self):
  6824. """
  6825. Will scroll a text to the specified text line.
  6826. :return: None
  6827. """
  6828. dia_box = Dialog_box(title=_("Go to Line ..."),
  6829. label=_("Line:"),
  6830. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6831. initial_text='')
  6832. try:
  6833. line = int(dia_box.location) - 1
  6834. except (ValueError, TypeError):
  6835. line = 0
  6836. if dia_box.ok:
  6837. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6838. # at the top of the window
  6839. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6840. # get the document() of the TextEditor
  6841. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6842. # create a Text Cursor based on the searched line
  6843. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6844. # set cursor of the code editor with the cursor at the searcehd line
  6845. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6846. def on_filenewscript(self, silent=False):
  6847. """
  6848. Will create a new script file and open it in the Code Editor
  6849. :param silent: if True will not display status messages
  6850. :param name: if specified will be the name of the new script
  6851. :param text: pass a source file to the newly created script to be loaded in it
  6852. :return: None
  6853. """
  6854. if silent is False:
  6855. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6856. # delete the absolute and relative position and messages in the infobar
  6857. self.ui.position_label.setText("")
  6858. # self.ui.rel_position_label.setText("")
  6859. self.new_script_object()
  6860. # script_text = script_obj.source_file
  6861. #
  6862. # self.proc_container.view.set_busy(_("Loading..."))
  6863. # script_obj.script_editor_tab.t_frame.hide()
  6864. #
  6865. # script_obj.script_editor_tab.t_frame.show()
  6866. # self.proc_container.view.set_idle()
  6867. def on_fileopenscript(self, name=None, silent=False):
  6868. """
  6869. Will open a Tcl script file into the Code Editor
  6870. :param silent: if True will not display status messages
  6871. :param name: name of a Tcl script file to open
  6872. :return: None
  6873. """
  6874. self.defaults.report_usage("on_fileopenscript")
  6875. App.log.debug("on_fileopenscript()")
  6876. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6877. "All Files (*.*)"
  6878. if name:
  6879. filenames = [name]
  6880. else:
  6881. try:
  6882. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6883. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6884. except TypeError:
  6885. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6886. if len(filenames) == 0:
  6887. if silent is False:
  6888. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6889. else:
  6890. for filename in filenames:
  6891. if filename != '':
  6892. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6893. def on_fileopenscript_example(self, name=None, silent=False):
  6894. """
  6895. Will open a Tcl script file into the Code Editor
  6896. :param silent: if True will not display status messages
  6897. :param name: name of a Tcl script file to open
  6898. :return:
  6899. """
  6900. self.defaults.report_usage("on_fileopenscript_example")
  6901. log.debug("on_fileopenscript_example()")
  6902. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6903. "All Files (*.*)"
  6904. # test if the app was frozen and choose the path for the configuration file
  6905. if getattr(sys, "frozen", False) is True:
  6906. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6907. else:
  6908. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6909. if name:
  6910. filenames = [name]
  6911. else:
  6912. try:
  6913. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6914. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6915. except TypeError:
  6916. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6917. if len(filenames) == 0:
  6918. if silent is False:
  6919. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6920. else:
  6921. for filename in filenames:
  6922. if filename != '':
  6923. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6924. def on_filerunscript(self, name=None, silent=False):
  6925. """
  6926. File menu callback for loading and running a TCL script.
  6927. :param silent: if True will not display status messages
  6928. :param name: name of a Tcl script file to be run by FlatCAM
  6929. :return: None
  6930. """
  6931. self.defaults.report_usage("on_filerunscript")
  6932. App.log.debug("on_file_runscript()")
  6933. if name:
  6934. filename = name
  6935. if self.cmd_line_headless != 1:
  6936. self.splash.showMessage('%s: %ssec\n%s' %
  6937. (_("Canvas initialization started.\n"
  6938. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6939. _("Executing ScriptObject file.")
  6940. ),
  6941. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6942. color=QtGui.QColor("gray"))
  6943. else:
  6944. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6945. "All Files (*.*)"
  6946. try:
  6947. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6948. directory=self.get_last_folder(), filter=_filter_)
  6949. except TypeError:
  6950. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6951. # The Qt methods above will return a QString which can cause problems later.
  6952. # So far json.dump() will fail to serialize it.
  6953. filename = str(filename)
  6954. if filename == "":
  6955. if silent is False:
  6956. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6957. else:
  6958. if self.cmd_line_headless != 1:
  6959. if self.ui.shell_dock.isHidden():
  6960. self.ui.shell_dock.show()
  6961. try:
  6962. with open(filename, "r") as tcl_script:
  6963. cmd_line_shellfile_content = tcl_script.read()
  6964. if self.cmd_line_headless != 1:
  6965. self.shell.exec_command(cmd_line_shellfile_content)
  6966. else:
  6967. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6968. if silent is False:
  6969. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6970. except Exception as e:
  6971. log.debug("App.on_filerunscript() -> %s" % str(e))
  6972. sys.exit(2)
  6973. def on_file_saveproject(self, silent=False):
  6974. """
  6975. Callback for menu item File->Save Project. Saves the project to
  6976. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6977. if set to None. The project is saved by calling ``self.save_project()``.
  6978. :param silent: if True will not display status messages
  6979. :return: None
  6980. """
  6981. self.defaults.report_usage("on_file_saveproject")
  6982. if self.project_filename is None:
  6983. self.on_file_saveprojectas()
  6984. else:
  6985. self.worker_task.emit({'fcn': self.save_project,
  6986. 'params': [self.project_filename, silent]})
  6987. if self.defaults["global_open_style"] is False:
  6988. self.file_opened.emit("project", self.project_filename)
  6989. self.file_saved.emit("project", self.project_filename)
  6990. self.set_ui_title(name=self.project_filename)
  6991. self.should_we_save = False
  6992. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6993. """
  6994. Callback for menu item File->Save Project As... Opens a file
  6995. chooser and saves the project to the given file via
  6996. ``self.save_project()``.
  6997. :param make_copy if to be create a copy of the project; boolean
  6998. :param use_thread: if to be run in a separate thread; boolean
  6999. :param quit_action: if to be followed by quiting the application; boolean
  7000. :return: None
  7001. """
  7002. self.defaults.report_usage("on_file_saveprojectas")
  7003. self.date = str(datetime.today()).rpartition('.')[0]
  7004. self.date = ''.join(c for c in self.date if c not in ':-')
  7005. self.date = self.date.replace(' ', '_')
  7006. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7007. try:
  7008. filename, _f = FCFileSaveDialog.get_saved_filename(
  7009. caption=_("Save Project As ..."),
  7010. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  7011. proj=_("Project")),
  7012. filter=filter_
  7013. )
  7014. except TypeError:
  7015. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  7016. filename = str(filename)
  7017. if filename == '':
  7018. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7019. return
  7020. if use_thread is True:
  7021. self.worker_task.emit({'fcn': self.save_project,
  7022. 'params': [filename, quit_action]})
  7023. else:
  7024. self.save_project(filename, quit_action)
  7025. # self.save_project(filename)
  7026. if self.defaults["global_open_style"] is False:
  7027. self.file_opened.emit("project", filename)
  7028. self.file_saved.emit("project", filename)
  7029. if not make_copy:
  7030. self.project_filename = filename
  7031. self.set_ui_title(name=self.project_filename)
  7032. self.should_we_save = False
  7033. def on_file_save_objects_pdf(self, use_thread=True):
  7034. self.date = str(datetime.today()).rpartition('.')[0]
  7035. self.date = ''.join(c for c in self.date if c not in ':-')
  7036. self.date = self.date.replace(' ', '_')
  7037. try:
  7038. obj_selection = self.collection.get_selected()
  7039. if len(obj_selection) == 1:
  7040. obj_name = str(obj_selection[0].options['name'])
  7041. else:
  7042. obj_name = _("FlatCAM objects print")
  7043. except AttributeError as err:
  7044. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7045. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7046. return
  7047. if not obj_selection:
  7048. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7049. return
  7050. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7051. try:
  7052. filename, _f = FCFileSaveDialog.get_saved_filename(
  7053. caption=_("Save Object as PDF ..."),
  7054. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7055. obj_name=obj_name,
  7056. date=self.date),
  7057. filter=filter_
  7058. )
  7059. except TypeError:
  7060. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7061. filename = str(filename)
  7062. if filename == '':
  7063. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7064. return
  7065. if use_thread is True:
  7066. self.proc_container.new(_("Printing PDF ... Please wait."))
  7067. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7068. else:
  7069. self.save_pdf(filename, obj_selection)
  7070. # self.save_project(filename)
  7071. if self.defaults["global_open_style"] is False:
  7072. self.file_opened.emit("pdf", filename)
  7073. self.file_saved.emit("pdf", filename)
  7074. def save_pdf(self, file_name, obj_selection):
  7075. p_size = self.defaults['global_workspaceT']
  7076. orientation = self.defaults['global_workspace_orientation']
  7077. color = 'black'
  7078. transparency_level = 1.0
  7079. self.pagesize = {}
  7080. self.pagesize.update(
  7081. {
  7082. 'Bounds': None,
  7083. 'A0': (841 * mm, 1189 * mm),
  7084. 'A1': (594 * mm, 841 * mm),
  7085. 'A2': (420 * mm, 594 * mm),
  7086. 'A3': (297 * mm, 420 * mm),
  7087. 'A4': (210 * mm, 297 * mm),
  7088. 'A5': (148 * mm, 210 * mm),
  7089. 'A6': (105 * mm, 148 * mm),
  7090. 'A7': (74 * mm, 105 * mm),
  7091. 'A8': (52 * mm, 74 * mm),
  7092. 'A9': (37 * mm, 52 * mm),
  7093. 'A10': (26 * mm, 37 * mm),
  7094. 'B0': (1000 * mm, 1414 * mm),
  7095. 'B1': (707 * mm, 1000 * mm),
  7096. 'B2': (500 * mm, 707 * mm),
  7097. 'B3': (353 * mm, 500 * mm),
  7098. 'B4': (250 * mm, 353 * mm),
  7099. 'B5': (176 * mm, 250 * mm),
  7100. 'B6': (125 * mm, 176 * mm),
  7101. 'B7': (88 * mm, 125 * mm),
  7102. 'B8': (62 * mm, 88 * mm),
  7103. 'B9': (44 * mm, 62 * mm),
  7104. 'B10': (31 * mm, 44 * mm),
  7105. 'C0': (917 * mm, 1297 * mm),
  7106. 'C1': (648 * mm, 917 * mm),
  7107. 'C2': (458 * mm, 648 * mm),
  7108. 'C3': (324 * mm, 458 * mm),
  7109. 'C4': (229 * mm, 324 * mm),
  7110. 'C5': (162 * mm, 229 * mm),
  7111. 'C6': (114 * mm, 162 * mm),
  7112. 'C7': (81 * mm, 114 * mm),
  7113. 'C8': (57 * mm, 81 * mm),
  7114. 'C9': (40 * mm, 57 * mm),
  7115. 'C10': (28 * mm, 40 * mm),
  7116. # American paper sizes
  7117. 'LETTER': (8.5 * inch, 11 * inch),
  7118. 'LEGAL': (8.5 * inch, 14 * inch),
  7119. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7120. # From https://en.wikipedia.org/wiki/Paper_size
  7121. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7122. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7123. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7124. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7125. 'LEDGER': (17 * inch, 11 * inch),
  7126. }
  7127. )
  7128. exported_svg = []
  7129. for obj in obj_selection:
  7130. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7131. scale_factor_x=None, scale_factor_y=None,
  7132. skew_factor_x=None, skew_factor_y=None,
  7133. mirror=None)
  7134. if obj.kind.lower() == 'gerber':
  7135. # color = self.defaults["gerber_plot_fill"][:-2]
  7136. color = obj.fill_color[:-2]
  7137. elif obj.kind.lower() == 'excellon':
  7138. color = '#C40000'
  7139. elif obj.kind.lower() == 'geometry':
  7140. color = self.defaults["global_draw_color"]
  7141. # Change the attributes of the exported SVG
  7142. # We don't need stroke-width
  7143. # We set opacity to maximum
  7144. # We set the colour to WHITE
  7145. root = ET.fromstring(svg_obj)
  7146. for child in root:
  7147. child.set('fill', str(color))
  7148. child.set('opacity', str(transparency_level))
  7149. child.set('stroke', str(color))
  7150. exported_svg.append(ET.tostring(root))
  7151. xmin = Inf
  7152. ymin = Inf
  7153. xmax = -Inf
  7154. ymax = -Inf
  7155. for obj in obj_selection:
  7156. try:
  7157. gxmin, gymin, gxmax, gymax = obj.bounds()
  7158. xmin = min([xmin, gxmin])
  7159. ymin = min([ymin, gymin])
  7160. xmax = max([xmax, gxmax])
  7161. ymax = max([ymax, gymax])
  7162. except Exception as e:
  7163. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7164. # Determine bounding area for svg export
  7165. bounds = [xmin, ymin, xmax, ymax]
  7166. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7167. # This contain the measure units
  7168. uom = obj_selection[0].units.lower()
  7169. # Define a boundary around SVG of about 1.0mm (~39mils)
  7170. if uom in "mm":
  7171. boundary = 1.0
  7172. else:
  7173. boundary = 0.0393701
  7174. # Convert everything to strings for use in the xml doc
  7175. svgwidth = str(size[0] + (2 * boundary))
  7176. svgheight = str(size[1] + (2 * boundary))
  7177. minx = str(bounds[0] - boundary)
  7178. miny = str(bounds[1] + boundary + size[1])
  7179. # Add a SVG Header and footer to the svg output from shapely
  7180. # The transform flips the Y Axis so that everything renders
  7181. # properly within svg apps such as inkscape
  7182. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7183. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7184. svg_header += 'width="' + svgwidth + uom + '" '
  7185. svg_header += 'height="' + svgheight + uom + '" '
  7186. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7187. svg_header += '>'
  7188. svg_header += '<g transform="scale(1,-1)">'
  7189. svg_footer = '</g> </svg>'
  7190. svg_elem = str(svg_header)
  7191. for svg_item in exported_svg:
  7192. svg_elem += str(svg_item)
  7193. svg_elem += str(svg_footer)
  7194. # Parse the xml through a xml parser just to add line feeds
  7195. # and to make it look more pretty for the output
  7196. doc = parse_xml_string(svg_elem)
  7197. doc_final = doc.toprettyxml()
  7198. try:
  7199. if self.defaults['units'].upper() == 'IN':
  7200. unit = inch
  7201. else:
  7202. unit = mm
  7203. doc_final = StringIO(doc_final)
  7204. drawing = svg2rlg(doc_final)
  7205. if p_size == 'Bounds':
  7206. renderPDF.drawToFile(drawing, file_name)
  7207. else:
  7208. if orientation == 'p':
  7209. page_size = portrait(self.pagesize[p_size])
  7210. else:
  7211. page_size = landscape(self.pagesize[p_size])
  7212. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7213. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7214. renderPDF.draw(drawing, my_canvas, 0, 0)
  7215. my_canvas.save()
  7216. except Exception as e:
  7217. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7218. return 'fail'
  7219. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7220. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7221. """
  7222. Exports a Geometry Object to an SVG file.
  7223. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7224. :param filename: Path to the SVG file to save to.
  7225. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7226. :return:
  7227. """
  7228. self.defaults.report_usage("export_svg()")
  7229. if filename is None:
  7230. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7231. is not None else self.defaults["global_last_folder"]
  7232. self.log.debug("export_svg()")
  7233. try:
  7234. obj = self.collection.get_by_name(str(obj_name))
  7235. except Exception:
  7236. # TODO: The return behavior has not been established... should raise exception?
  7237. return "Could not retrieve object: %s" % obj_name
  7238. with self.proc_container.new(_("Exporting SVG")) as proc:
  7239. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7240. # Determine bounding area for svg export
  7241. bounds = obj.bounds()
  7242. size = obj.size()
  7243. # Convert everything to strings for use in the xml doc
  7244. svgwidth = str(size[0])
  7245. svgheight = str(size[1])
  7246. minx = str(bounds[0])
  7247. miny = str(bounds[1] - size[1])
  7248. uom = obj.units.lower()
  7249. # Add a SVG Header and footer to the svg output from shapely
  7250. # The transform flips the Y Axis so that everything renders
  7251. # properly within svg apps such as inkscape
  7252. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7253. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7254. svg_header += 'width="' + svgwidth + uom + '" '
  7255. svg_header += 'height="' + svgheight + uom + '" '
  7256. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7257. svg_header += '<g transform="scale(1,-1)">'
  7258. svg_footer = '</g> </svg>'
  7259. svg_elem = svg_header + exported_svg + svg_footer
  7260. # Parse the xml through a xml parser just to add line feeds
  7261. # and to make it look more pretty for the output
  7262. svgcode = parse_xml_string(svg_elem)
  7263. svgcode = svgcode.toprettyxml()
  7264. try:
  7265. with open(filename, 'w') as fp:
  7266. fp.write(svgcode)
  7267. except PermissionError:
  7268. self.inform.emit('[WARNING] %s' %
  7269. _("Permission denied, saving not possible.\n"
  7270. "Most likely another app is holding the file open and not accessible."))
  7271. return 'fail'
  7272. if self.defaults["global_open_style"] is False:
  7273. self.file_opened.emit("SVG", filename)
  7274. self.file_saved.emit("SVG", filename)
  7275. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7276. def save_source_file(self, obj_name, filename, use_thread=True):
  7277. """
  7278. Exports a FlatCAM Object to an Gerber/Excellon file.
  7279. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7280. :param filename: Path to the Gerber file to save to.
  7281. :param use_thread: if to be run in a separate thread
  7282. :return:
  7283. """
  7284. self.defaults.report_usage("save source file()")
  7285. if filename is None:
  7286. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7287. is not None else self.defaults["global_last_folder"]
  7288. self.log.debug("save source file()")
  7289. obj = self.collection.get_by_name(obj_name)
  7290. file_string = StringIO(obj.source_file)
  7291. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7292. if file_string.getvalue() == '':
  7293. self.inform.emit('[ERROR_NOTCL] %s' %
  7294. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7295. return 'fail'
  7296. try:
  7297. with open(filename, 'w') as file:
  7298. file.writelines('G04*\n')
  7299. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7300. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7301. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7302. file.writelines('G04 Created on : %s*\n' % time_string)
  7303. for line in file_string:
  7304. file.writelines(line)
  7305. except PermissionError:
  7306. self.inform.emit('[WARNING] %s' %
  7307. _("Permission denied, saving not possible.\n"
  7308. "Most likely another app is holding the file open and not accessible."))
  7309. return 'fail'
  7310. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7311. """
  7312. Exports a Excellon Object to an Excellon file.
  7313. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7314. :param filename: Path to the Excellon file to save to.
  7315. :param local_use:
  7316. :param use_thread: if to be run in a separate thread
  7317. :return:
  7318. """
  7319. self.defaults.report_usage("export_excellon()")
  7320. if filename is None:
  7321. if self.defaults["global_last_save_folder"]:
  7322. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7323. else:
  7324. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7325. self.log.debug("export_excellon()")
  7326. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7327. self.defaults["excellon_exp_decimals"]
  7328. )
  7329. if local_use is None:
  7330. try:
  7331. obj = self.collection.get_by_name(str(obj_name))
  7332. except Exception:
  7333. return "Could not retrieve object: %s" % obj_name
  7334. else:
  7335. obj = local_use
  7336. if not isinstance(obj, ExcellonObject):
  7337. self.inform.emit('[ERROR_NOTCL] %s' %
  7338. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7339. return
  7340. # updated units
  7341. eunits = self.defaults["excellon_exp_units"]
  7342. ewhole = self.defaults["excellon_exp_integer"]
  7343. efract = self.defaults["excellon_exp_decimals"]
  7344. ezeros = self.defaults["excellon_exp_zeros"]
  7345. eformat = self.defaults["excellon_exp_format"]
  7346. slot_type = self.defaults["excellon_exp_slot_type"]
  7347. fc_units = self.defaults['units'].upper()
  7348. if fc_units == 'MM':
  7349. factor = 1 if eunits == 'METRIC' else 0.03937
  7350. else:
  7351. factor = 25.4 if eunits == 'METRIC' else 1
  7352. def make_excellon():
  7353. try:
  7354. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7355. header = 'M48\n'
  7356. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7357. (str(self.version), str(self.version_date))
  7358. header += ';Filename: %s' % str(obj_name) + '\n'
  7359. header += ';Created on : %s' % time_str + '\n'
  7360. if eformat == 'dec':
  7361. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7362. header += eunits + '\n'
  7363. for tool in obj.tools:
  7364. if eunits == 'METRIC':
  7365. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7366. tool=str(tool),
  7367. dec=2)
  7368. else:
  7369. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7370. tool=str(tool),
  7371. dec=4)
  7372. else:
  7373. if ezeros == 'LZ':
  7374. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7375. form='ndec', e_zeros='LZ', factor=factor,
  7376. slot_type=slot_type)
  7377. header += '%s,%s\n' % (eunits, 'LZ')
  7378. header += format_exc
  7379. for tool in obj.tools:
  7380. if eunits == 'METRIC':
  7381. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7382. tool=str(tool),
  7383. dec=2)
  7384. else:
  7385. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7386. tool=str(tool),
  7387. dec=4)
  7388. else:
  7389. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7390. form='ndec', e_zeros='TZ', factor=factor,
  7391. slot_type=slot_type)
  7392. header += '%s,%s\n' % (eunits, 'TZ')
  7393. header += format_exc
  7394. for tool in obj.tools:
  7395. if eunits == 'METRIC':
  7396. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7397. tool=str(tool),
  7398. dec=2)
  7399. else:
  7400. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7401. tool=str(tool),
  7402. dec=4)
  7403. header += '%\n'
  7404. footer = 'M30\n'
  7405. exported_excellon = header
  7406. exported_excellon += excellon_code
  7407. exported_excellon += footer
  7408. if local_use is None:
  7409. try:
  7410. with open(filename, 'w') as fp:
  7411. fp.write(exported_excellon)
  7412. except PermissionError:
  7413. self.inform.emit('[WARNING] %s' %
  7414. _("Permission denied, saving not possible.\n"
  7415. "Most likely another app is holding the file open and not accessible."))
  7416. return 'fail'
  7417. if self.defaults["global_open_style"] is False:
  7418. self.file_opened.emit("Excellon", filename)
  7419. self.file_saved.emit("Excellon", filename)
  7420. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7421. else:
  7422. return exported_excellon
  7423. except Exception as e:
  7424. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7425. return 'fail'
  7426. if use_thread is True:
  7427. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7428. def job_thread_exc(app_obj):
  7429. ret = make_excellon()
  7430. if ret == 'fail':
  7431. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7432. return
  7433. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7434. else:
  7435. eret = make_excellon()
  7436. if eret == 'fail':
  7437. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7438. return 'fail'
  7439. if local_use is not None:
  7440. return eret
  7441. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7442. """
  7443. Exports a Gerber Object to an Gerber file.
  7444. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7445. :param filename: Path to the Gerber file to save to.
  7446. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7447. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7448. :param use_thread: if to be run in a separate thread
  7449. :return:
  7450. """
  7451. self.defaults.report_usage("export_gerber()")
  7452. if filename is None:
  7453. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7454. is not None else self.defaults["global_last_folder"]
  7455. self.log.debug("export_gerber()")
  7456. if local_use is None:
  7457. try:
  7458. obj = self.collection.get_by_name(str(obj_name))
  7459. except Exception:
  7460. return "Could not retrieve object: %s" % obj_name
  7461. else:
  7462. obj = local_use
  7463. # updated units
  7464. gunits = self.defaults["gerber_exp_units"]
  7465. gwhole = self.defaults["gerber_exp_integer"]
  7466. gfract = self.defaults["gerber_exp_decimals"]
  7467. gzeros = self.defaults["gerber_exp_zeros"]
  7468. fc_units = self.defaults['units'].upper()
  7469. if fc_units == 'MM':
  7470. factor = 1 if gunits == 'MM' else 0.03937
  7471. else:
  7472. factor = 25.4 if gunits == 'MM' else 1
  7473. def make_gerber():
  7474. try:
  7475. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7476. header = 'G04*\n'
  7477. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7478. (str(self.version), str(self.version_date))
  7479. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7480. header += 'G04 Created on : %s*' % time_str + '\n'
  7481. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7482. header += "%MO{units}*%\n".format(units=gunits)
  7483. for apid in obj.apertures:
  7484. if obj.apertures[apid]['type'] == 'C':
  7485. header += "%ADD{apid}{type},{size}*%\n".format(
  7486. apid=str(apid),
  7487. type='C',
  7488. size=(factor * obj.apertures[apid]['size'])
  7489. )
  7490. elif obj.apertures[apid]['type'] == 'R':
  7491. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7492. apid=str(apid),
  7493. type='R',
  7494. width=(factor * obj.apertures[apid]['width']),
  7495. height=(factor * obj.apertures[apid]['height'])
  7496. )
  7497. elif obj.apertures[apid]['type'] == 'O':
  7498. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7499. apid=str(apid),
  7500. type='O',
  7501. width=(factor * obj.apertures[apid]['width']),
  7502. height=(factor * obj.apertures[apid]['height'])
  7503. )
  7504. header += '\n'
  7505. # obsolete units but some software may need it
  7506. if gunits == 'IN':
  7507. header += 'G70*\n'
  7508. else:
  7509. header += 'G71*\n'
  7510. # Absolute Mode
  7511. header += 'G90*\n'
  7512. header += 'G01*\n'
  7513. # positive polarity
  7514. header += '%LPD*%\n'
  7515. footer = 'M02*\n'
  7516. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7517. exported_gerber = header
  7518. exported_gerber += gerber_code
  7519. exported_gerber += footer
  7520. if local_use is None:
  7521. try:
  7522. with open(filename, 'w') as fp:
  7523. fp.write(exported_gerber)
  7524. except PermissionError:
  7525. self.inform.emit('[WARNING] %s' %
  7526. _("Permission denied, saving not possible.\n"
  7527. "Most likely another app is holding the file open and not accessible."))
  7528. return 'fail'
  7529. if self.defaults["global_open_style"] is False:
  7530. self.file_opened.emit("Gerber", filename)
  7531. self.file_saved.emit("Gerber", filename)
  7532. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7533. else:
  7534. return exported_gerber
  7535. except Exception as e:
  7536. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7537. return 'fail'
  7538. if use_thread is True:
  7539. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7540. def job_thread_grb(app_obj):
  7541. ret = make_gerber()
  7542. if ret == 'fail':
  7543. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7544. return
  7545. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7546. else:
  7547. gret = make_gerber()
  7548. if gret == 'fail':
  7549. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7550. return 'fail'
  7551. if local_use is not None:
  7552. return gret
  7553. def export_dxf(self, obj_name, filename, use_thread=True):
  7554. """
  7555. Exports a Geometry Object to an DXF file.
  7556. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7557. :param filename: Path to the DXF file to save to.
  7558. :param use_thread: if to be run in a separate thread
  7559. :return:
  7560. """
  7561. self.defaults.report_usage("export_dxf()")
  7562. if filename is None:
  7563. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7564. is not None else self.defaults["global_last_folder"]
  7565. self.log.debug("export_dxf()")
  7566. try:
  7567. obj = self.collection.get_by_name(str(obj_name))
  7568. except Exception:
  7569. # TODO: The return behavior has not been established... should raise exception?
  7570. return "Could not retrieve object: %s" % obj_name
  7571. def make_dxf():
  7572. try:
  7573. dxf_code = obj.export_dxf()
  7574. dxf_code.saveas(filename)
  7575. if self.defaults["global_open_style"] is False:
  7576. self.file_opened.emit("DXF", filename)
  7577. self.file_saved.emit("DXF", filename)
  7578. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7579. except Exception:
  7580. return 'fail'
  7581. if use_thread is True:
  7582. with self.proc_container.new(_("Exporting DXF")) as proc:
  7583. def job_thread_exc(app_obj):
  7584. ret_dxf_val = make_dxf()
  7585. if ret_dxf_val == 'fail':
  7586. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7587. return
  7588. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7589. else:
  7590. ret = make_dxf()
  7591. if ret == 'fail':
  7592. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7593. return
  7594. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7595. """
  7596. Adds a new Geometry Object to the projects and populates
  7597. it with shapes extracted from the SVG file.
  7598. :param plot: If True then the resulting object will be plotted on canvas
  7599. :param filename: Path to the SVG file.
  7600. :param geo_type: Type of FlatCAM object that will be created from SVG
  7601. :param outname: The name given to the resulting FlatCAM object
  7602. :return:
  7603. """
  7604. self.defaults.report_usage("import_svg()")
  7605. log.debug("App.import_svg()")
  7606. obj_type = ""
  7607. if geo_type is None or geo_type == "geometry":
  7608. obj_type = "geometry"
  7609. elif geo_type == "gerber":
  7610. obj_type = "gerber"
  7611. else:
  7612. self.inform.emit('[ERROR_NOTCL] %s' %
  7613. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7614. return
  7615. units = self.defaults['units'].upper()
  7616. def obj_init(geo_obj, app_obj):
  7617. geo_obj.import_svg(filename, obj_type, units=units)
  7618. geo_obj.multigeo = False
  7619. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7620. with self.proc_container.new(_("Importing SVG")) as proc:
  7621. # Object name
  7622. name = outname or filename.split('/')[-1].split('\\')[-1]
  7623. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7624. if ret == 'fail':
  7625. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7626. return 'fail'
  7627. # Register recent file
  7628. self.file_opened.emit("svg", filename)
  7629. # GUI feedback
  7630. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7631. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7632. """
  7633. Adds a new Geometry Object to the projects and populates
  7634. it with shapes extracted from the DXF file.
  7635. :param filename: Path to the DXF file.
  7636. :param geo_type: Type of FlatCAM object that will be created from DXF
  7637. :param outname: Name for the imported Geometry
  7638. :param plot: If True then the resulting object will be plotted on canvas
  7639. :return:
  7640. """
  7641. self.defaults.report_usage("import_dxf()")
  7642. obj_type = ""
  7643. if geo_type is None or geo_type == "geometry":
  7644. obj_type = "geometry"
  7645. elif geo_type == "gerber":
  7646. obj_type = geo_type
  7647. else:
  7648. self.inform.emit('[ERROR_NOTCL] %s' %
  7649. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7650. return
  7651. units = self.defaults['units'].upper()
  7652. def obj_init(geo_obj, app_obj):
  7653. geo_obj.import_dxf(filename, obj_type, units=units)
  7654. geo_obj.multigeo = False
  7655. with self.proc_container.new(_("Importing DXF")):
  7656. # Object name
  7657. name = outname or filename.split('/')[-1].split('\\')[-1]
  7658. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7659. if ret == 'fail':
  7660. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7661. return 'fail'
  7662. # Register recent file
  7663. self.file_opened.emit("dxf", filename)
  7664. # GUI feedback
  7665. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7666. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7667. """
  7668. Opens a Gerber file, parses it and creates a new object for
  7669. it in the program. Thread-safe.
  7670. :param outname: Name of the resulting object. None causes the
  7671. name to be that of the file. Str.
  7672. :param filename: Gerber file filename
  7673. :type filename: str
  7674. :param plot: boolean, to plot or not the resulting object
  7675. :param from_tcl: True if run from Tcl Shell
  7676. :return: None
  7677. """
  7678. # How the object should be initialized
  7679. def obj_init(gerber_obj, app_obj):
  7680. assert isinstance(gerber_obj, GerberObject), \
  7681. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7682. # Opening the file happens here
  7683. try:
  7684. gerber_obj.parse_file(filename)
  7685. except IOError:
  7686. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7687. return "fail"
  7688. except ParseError as err:
  7689. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7690. app_obj.log.error(str(err))
  7691. return "fail"
  7692. except Exception as e:
  7693. log.debug("App.open_gerber() --> %s" % str(e))
  7694. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7695. msg += traceback.format_exc()
  7696. app_obj.inform.emit(msg)
  7697. return "fail"
  7698. if gerber_obj.is_empty():
  7699. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7700. _("Object is not Gerber file or empty. Aborting object creation."))
  7701. return "fail"
  7702. App.log.debug("open_gerber()")
  7703. with self.proc_container.new(_("Opening Gerber")):
  7704. # Object name
  7705. name = outname or filename.split('/')[-1].split('\\')[-1]
  7706. # # ## Object creation # ##
  7707. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7708. if ret_val == 'fail':
  7709. if from_tcl:
  7710. filename = self.defaults['global_tcl_path'] + '/' + name
  7711. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7712. if ret_val == 'fail':
  7713. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7714. return 'fail'
  7715. # Register recent file
  7716. self.file_opened.emit("gerber", filename)
  7717. # GUI feedback
  7718. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7719. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7720. """
  7721. Opens an Excellon file, parses it and creates a new object for
  7722. it in the program. Thread-safe.
  7723. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7724. :param filename: Excellon file filename
  7725. :type filename: str
  7726. :param plot: boolean, to plot or not the resulting object
  7727. :param from_tcl: True if run from Tcl Shell
  7728. :return: None
  7729. """
  7730. App.log.debug("open_excellon()")
  7731. # How the object should be initialized
  7732. def obj_init(excellon_obj, app_obj):
  7733. try:
  7734. ret = excellon_obj.parse_file(filename=filename)
  7735. if ret == "fail":
  7736. log.debug("Excellon parsing failed.")
  7737. self.inform.emit('[ERROR_NOTCL] %s' %
  7738. _("This is not Excellon file."))
  7739. return "fail"
  7740. except IOError:
  7741. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7742. (_("Cannot open file"), filename))
  7743. log.debug("Could not open Excellon object.")
  7744. return "fail"
  7745. except Exception:
  7746. msg = '[ERROR_NOTCL] %s' % \
  7747. _("An internal error has occurred. See shell.\n")
  7748. msg += traceback.format_exc()
  7749. app_obj.inform.emit(msg)
  7750. return "fail"
  7751. ret = excellon_obj.create_geometry()
  7752. if ret == 'fail':
  7753. log.debug("Could not create geometry for Excellon object.")
  7754. return "fail"
  7755. for tool in excellon_obj.tools:
  7756. if excellon_obj.tools[tool]['solid_geometry']:
  7757. return
  7758. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7759. return "fail"
  7760. with self.proc_container.new(_("Opening Excellon.")):
  7761. # Object name
  7762. name = outname or filename.split('/')[-1].split('\\')[-1]
  7763. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7764. if ret_val == 'fail':
  7765. if from_tcl:
  7766. filename = self.defaults['global_tcl_path'] + '/' + name
  7767. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7768. if ret_val == 'fail':
  7769. self.inform.emit('[ERROR_NOTCL] %s' %
  7770. _('Open Excellon file failed. Probable not an Excellon file.'))
  7771. return
  7772. # Register recent file
  7773. self.file_opened.emit("excellon", filename)
  7774. # GUI feedback
  7775. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7776. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7777. """
  7778. Opens a G-gcode file, parses it and creates a new object for
  7779. it in the program. Thread-safe.
  7780. :param filename: G-code file filename
  7781. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7782. :param force_parsing:
  7783. :param plot: If True plot the object on canvas
  7784. :param from_tcl: True if run from Tcl Shell
  7785. :return: None
  7786. """
  7787. App.log.debug("open_gcode()")
  7788. # How the object should be initialized
  7789. def obj_init(job_obj, app_obj_):
  7790. """
  7791. :param job_obj: the resulting object
  7792. :type app_obj_: App
  7793. """
  7794. assert isinstance(app_obj_, App), \
  7795. "Initializer expected App, got %s" % type(app_obj_)
  7796. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7797. try:
  7798. f = open(filename)
  7799. gcode = f.read()
  7800. f.close()
  7801. except IOError:
  7802. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7803. return "fail"
  7804. job_obj.gcode = gcode
  7805. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7806. if gcode_ret == "fail":
  7807. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7808. return "fail"
  7809. job_obj.create_geometry()
  7810. with self.proc_container.new(_("Opening G-Code.")):
  7811. # Object name
  7812. name = outname or filename.split('/')[-1].split('\\')[-1]
  7813. # New object creation and file processing
  7814. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7815. if ret_val == 'fail':
  7816. if from_tcl:
  7817. filename = self.defaults['global_tcl_path'] + '/' + name
  7818. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7819. if ret_val == 'fail':
  7820. self.inform.emit('[ERROR_NOTCL] %s' %
  7821. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7822. "Try to load it from File menu.\n "
  7823. "Attempting to create a FlatCAM CNCJob Object from "
  7824. "G-Code file failed during processing"))
  7825. return "fail"
  7826. # Register recent file
  7827. self.file_opened.emit("cncjob", filename)
  7828. # GUI feedback
  7829. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7830. def open_hpgl2(self, filename, outname=None):
  7831. """
  7832. Opens a HPGL2 file, parses it and creates a new object for
  7833. it in the program. Thread-safe.
  7834. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7835. :param filename: HPGL2 file filename
  7836. :return: None
  7837. """
  7838. filename = filename
  7839. # How the object should be initialized
  7840. def obj_init(geo_obj, app_obj):
  7841. assert isinstance(geo_obj, GeometryObject), \
  7842. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7843. # Opening the file happens here
  7844. obj = HPGL2(self)
  7845. try:
  7846. HPGL2.parse_file(obj, filename)
  7847. except IOError:
  7848. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7849. return "fail"
  7850. except ParseError as err:
  7851. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7852. app_obj.log.error(str(err))
  7853. return "fail"
  7854. except Exception as e:
  7855. log.debug("App.open_hpgl2() --> %s" % str(e))
  7856. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7857. msg += traceback.format_exc()
  7858. app_obj.inform.emit(msg)
  7859. return "fail"
  7860. geo_obj.multigeo = True
  7861. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7862. geo_obj.tools = deepcopy(obj.tools)
  7863. geo_obj.source_file = deepcopy(obj.source_file)
  7864. del obj
  7865. if not geo_obj.solid_geometry:
  7866. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7867. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7868. return "fail"
  7869. App.log.debug("open_hpgl2()")
  7870. with self.proc_container.new(_("Opening HPGL2")):
  7871. # Object name
  7872. name = outname or filename.split('/')[-1].split('\\')[-1]
  7873. # # ## Object creation # ##
  7874. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7875. if ret == 'fail':
  7876. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7877. return 'fail'
  7878. # Register recent file
  7879. self.file_opened.emit("geometry", filename)
  7880. # GUI feedback
  7881. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7882. def open_script(self, filename, outname=None, silent=False):
  7883. """
  7884. Opens a Script file, parses it and creates a new object for
  7885. it in the program. Thread-safe.
  7886. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7887. :param filename: Script file filename
  7888. :param silent: If True there will be no messages printed to StatusBar
  7889. :return: None
  7890. """
  7891. def obj_init(script_obj, app_obj):
  7892. assert isinstance(script_obj, ScriptObject), \
  7893. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7894. if silent is False:
  7895. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7896. try:
  7897. script_obj.parse_file(filename)
  7898. except IOError:
  7899. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7900. return "fail"
  7901. except ParseError as err:
  7902. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7903. app_obj.log.error(str(err))
  7904. return "fail"
  7905. except Exception as e:
  7906. log.debug("App.open_script() -> %s" % str(e))
  7907. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7908. msg += traceback.format_exc()
  7909. app_obj.inform.emit(msg)
  7910. return "fail"
  7911. App.log.debug("open_script()")
  7912. with self.proc_container.new(_("Opening TCL Script...")):
  7913. # Object name
  7914. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7915. # Object creation
  7916. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7917. if ret_val == 'fail':
  7918. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7919. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7920. if ret_val == 'fail':
  7921. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7922. return 'fail'
  7923. # Register recent file
  7924. self.file_opened.emit("script", filename)
  7925. # GUI feedback
  7926. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7927. def open_config_file(self, filename, run_from_arg=None):
  7928. """
  7929. Loads a config file from the specified file.
  7930. :param filename: Name of the file from which to load.
  7931. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7932. :return: None
  7933. """
  7934. App.log.debug("Opening config file: " + filename)
  7935. if run_from_arg:
  7936. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7937. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7938. _("Opening FlatCAM Config file.")),
  7939. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7940. color=QtGui.QColor("gray"))
  7941. # # add the tab if it was closed
  7942. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7943. # # first clear previous text in text editor (if any)
  7944. # self.ui.text_editor_tab.code_editor.clear()
  7945. #
  7946. # # Switch plot_area to CNCJob tab
  7947. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7948. # close the Code editor if already open
  7949. if self.toggle_codeeditor:
  7950. self.on_toggle_code_editor()
  7951. self.on_toggle_code_editor()
  7952. try:
  7953. if filename:
  7954. f = QtCore.QFile(filename)
  7955. if f.open(QtCore.QIODevice.ReadOnly):
  7956. stream = QtCore.QTextStream(f)
  7957. code_edited = stream.readAll()
  7958. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7959. f.close()
  7960. except IOError:
  7961. App.log.error("Failed to open config file: %s" % filename)
  7962. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7963. (_("Failed to open config file"), filename))
  7964. return
  7965. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7966. """
  7967. Loads a project from the specified file.
  7968. 1) Loads and parses file
  7969. 2) Registers the file as recently opened.
  7970. 3) Calls on_file_new()
  7971. 4) Updates options
  7972. 5) Calls new_object() with the object's from_dict() as init method.
  7973. 6) Calls plot_all() if plot=True
  7974. :param filename: Name of the file from which to load.
  7975. :param run_from_arg: True if run for arguments
  7976. :param plot: If True plot all objects in the project
  7977. :param cli: Run from command line
  7978. :param from_tcl: True if run from Tcl Sehll
  7979. :return: None
  7980. """
  7981. App.log.debug("Opening project: " + filename)
  7982. # block autosaving while a project is loaded
  7983. self.block_autosave = True
  7984. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7985. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7986. if cli is None:
  7987. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7988. if run_from_arg:
  7989. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7990. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7991. _("Opening FlatCAM Project file.")),
  7992. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7993. color=QtGui.QColor("gray"))
  7994. # Open and parse an uncompressed Project file
  7995. try:
  7996. f = open(filename, 'r')
  7997. except IOError:
  7998. if from_tcl:
  7999. name = filename.split('/')[-1].split('\\')[-1]
  8000. filename = self.defaults['global_tcl_path'] + '/' + name
  8001. try:
  8002. f = open(filename, 'r')
  8003. except IOError:
  8004. log.error("Failed to open project file: %s" % filename)
  8005. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8006. return
  8007. else:
  8008. log.error("Failed to open project file: %s" % filename)
  8009. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8010. return
  8011. try:
  8012. d = json.load(f, object_hook=dict2obj)
  8013. except Exception as e:
  8014. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8015. (filename, str(e)))
  8016. f.close()
  8017. # Open and parse a compressed Project file
  8018. try:
  8019. with lzma.open(filename) as f:
  8020. file_content = f.read().decode('utf-8')
  8021. d = json.loads(file_content, object_hook=dict2obj)
  8022. except Exception as e:
  8023. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8024. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8025. return
  8026. # Clear the current project
  8027. # # NOT THREAD SAFE # ##
  8028. if run_from_arg is True:
  8029. pass
  8030. elif cli is True:
  8031. self.delete_selection_shape()
  8032. else:
  8033. self.on_file_new()
  8034. # Project options
  8035. self.options.update(d['options'])
  8036. self.project_filename = filename
  8037. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8038. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8039. if cli is None:
  8040. self.set_screen_units(self.options["units"])
  8041. # Re create objects
  8042. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8043. for obj in d['objs']:
  8044. try:
  8045. def obj_init(obj_inst, app_inst):
  8046. obj_inst.from_dict(obj)
  8047. App.log.debug("Recreating from opened project an %s object: %s" %
  8048. (obj['kind'].capitalize(), obj['options']['name']))
  8049. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8050. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8051. if cli is None:
  8052. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8053. obj['kind'].upper(),
  8054. obj['options']['name']
  8055. )
  8056. )
  8057. self.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8058. except Exception as e:
  8059. print('App.open_project() --> ' + str(e))
  8060. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8061. self.should_we_save = False
  8062. self.file_opened.emit("project", filename)
  8063. # restore autosaving after a project was loaded
  8064. self.block_autosave = False
  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_ui_title(name=self.project_filename)
  8069. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8070. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  8071. """
  8072. Re-generates all plots from all objects.
  8073. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8074. :param muted: if True don't print messages
  8075. :param use_thread: if True will use threading for plotting the objects
  8076. :return: None
  8077. """
  8078. self.log.debug("Plot_all()")
  8079. if muted is not True:
  8080. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8081. for plot_obj in self.collection.get_list():
  8082. def worker_task(obj):
  8083. with self.proc_container.new("Plotting"):
  8084. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8085. if fit_view is True:
  8086. self.object_plotted.emit(obj)
  8087. if use_thread is True:
  8088. # Send to worker
  8089. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8090. else:
  8091. worker_task(plot_obj)
  8092. def register_folder(self, filename):
  8093. """
  8094. Register the last folder used by the app to open something
  8095. :param filename: the last folder is extracted from the filename
  8096. :return: None
  8097. """
  8098. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8099. def register_save_folder(self, filename):
  8100. """
  8101. Register the last folder used by the app to save something
  8102. :param filename: the last folder is extracted from the filename
  8103. :return: None
  8104. """
  8105. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8106. # def set_progress_bar(self, percentage, text=""):
  8107. # """
  8108. # Set a progress bar to a value (percentage)
  8109. #
  8110. # :param percentage: Value set to the progressbar
  8111. # :param text: Not used
  8112. # :return: None
  8113. # """
  8114. # self.ui.progress_bar.setValue(int(percentage))
  8115. def setup_recent_items(self):
  8116. """
  8117. Setup a dictionary with the recent files accessed, organized by type
  8118. :return:
  8119. """
  8120. icons = {
  8121. "gerber": self.resource_location + "/flatcam_icon16.png",
  8122. "excellon": self.resource_location + "/drill16.png",
  8123. 'geometry': self.resource_location + "/geometry16.png",
  8124. "cncjob": self.resource_location + "/cnc16.png",
  8125. "script": self.resource_location + "/script_new24.png",
  8126. "document": self.resource_location + "/notes16_1.png",
  8127. "project": self.resource_location + "/project16.png",
  8128. "svg": self.resource_location + "/geometry16.png",
  8129. "dxf": self.resource_location + "/dxf16.png",
  8130. "pdf": self.resource_location + "/pdf32.png",
  8131. "image": self.resource_location + "/image16.png"
  8132. }
  8133. try:
  8134. image_opener = self.image_tool.import_image
  8135. except AttributeError:
  8136. image_opener = None
  8137. openers = {
  8138. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8139. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8140. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8141. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8142. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8143. "document": None,
  8144. 'project': self.open_project,
  8145. 'svg': self.import_svg,
  8146. 'dxf': self.import_dxf,
  8147. 'image': image_opener,
  8148. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8149. }
  8150. # Open recent file for files
  8151. try:
  8152. f = open(self.data_path + '/recent.json')
  8153. except IOError:
  8154. App.log.error("Failed to load recent item list.")
  8155. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8156. return
  8157. try:
  8158. self.recent = json.load(f)
  8159. except json.errors.JSONDecodeError:
  8160. App.log.error("Failed to parse recent item list.")
  8161. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8162. f.close()
  8163. return
  8164. f.close()
  8165. # Open recent file for projects
  8166. try:
  8167. fp = open(self.data_path + '/recent_projects.json')
  8168. except IOError:
  8169. App.log.error("Failed to load recent project item list.")
  8170. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8171. return
  8172. try:
  8173. self.recent_projects = json.load(fp)
  8174. except json.errors.JSONDecodeError:
  8175. App.log.error("Failed to parse recent project item list.")
  8176. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8177. fp.close()
  8178. return
  8179. fp.close()
  8180. # Closure needed to create callbacks in a loop.
  8181. # Otherwise late binding occurs.
  8182. def make_callback(func, fname):
  8183. def opener():
  8184. func(fname)
  8185. return opener
  8186. def reset_recent_files():
  8187. # Reset menu
  8188. self.ui.recent.clear()
  8189. self.recent = []
  8190. try:
  8191. ff = open(self.data_path + '/recent.json', 'w')
  8192. except IOError:
  8193. App.log.error("Failed to open recent items file for writing.")
  8194. return
  8195. json.dump(self.recent, ff)
  8196. def reset_recent_projects():
  8197. # Reset menu
  8198. self.ui.recent_projects.clear()
  8199. self.recent_projects = []
  8200. try:
  8201. frp = open(self.data_path + '/recent_projects.json', 'w')
  8202. except IOError:
  8203. App.log.error("Failed to open recent projects items file for writing.")
  8204. return
  8205. json.dump(self.recent, frp)
  8206. # Reset menu
  8207. self.ui.recent.clear()
  8208. self.ui.recent_projects.clear()
  8209. # Create menu items for projects
  8210. for recent in self.recent_projects:
  8211. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8212. if recent['kind'] == 'project':
  8213. try:
  8214. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8215. # Attach callback
  8216. o = make_callback(openers[recent["kind"]], recent['filename'])
  8217. action.triggered.connect(o)
  8218. self.ui.recent_projects.addAction(action)
  8219. except KeyError:
  8220. App.log.error("Unsupported file type: %s" % recent["kind"])
  8221. # Last action in Recent Files menu is one that Clear the content
  8222. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8223. (_("Clear Recent projects")), self)
  8224. clear_action_proj.triggered.connect(reset_recent_projects)
  8225. self.ui.recent_projects.addSeparator()
  8226. self.ui.recent_projects.addAction(clear_action_proj)
  8227. # Create menu items for files
  8228. for recent in self.recent:
  8229. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8230. if recent['kind'] != 'project':
  8231. try:
  8232. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8233. # Attach callback
  8234. o = make_callback(openers[recent["kind"]], recent['filename'])
  8235. action.triggered.connect(o)
  8236. self.ui.recent.addAction(action)
  8237. except KeyError:
  8238. App.log.error("Unsupported file type: %s" % recent["kind"])
  8239. # Last action in Recent Files menu is one that Clear the content
  8240. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8241. (_("Clear Recent files")), self)
  8242. clear_action.triggered.connect(reset_recent_files)
  8243. self.ui.recent.addSeparator()
  8244. self.ui.recent.addAction(clear_action)
  8245. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8246. # self.ui.menufilerecent.set_submenu(recent_menu)
  8247. # recent_menu.show_all()
  8248. # self.ui.recent.show()
  8249. self.log.debug("Recent items list has been populated.")
  8250. def setup_component_editor(self):
  8251. """
  8252. Default text for the Selected tab when is not taken by the Object UI.
  8253. :return:
  8254. """
  8255. # label = QtWidgets.QLabel("Choose an item from Project")
  8256. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8257. sel_title = QtWidgets.QTextEdit(
  8258. _('<b>Shortcut Key List</b>'))
  8259. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8260. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8261. f_settings = QSettings("Open Source", "FlatCAM")
  8262. if f_settings.contains("notebook_font_size"):
  8263. fsize = f_settings.value('notebook_font_size', type=int)
  8264. else:
  8265. fsize = 12
  8266. tsize = fsize + int(fsize / 2)
  8267. # selected_text = (_('''
  8268. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8269. # </p>
  8270. #
  8271. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8272. # The normal flow when working in FlatCAM is the following:</span></p>
  8273. #
  8274. # <ol>
  8275. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8276. # file into
  8277. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8278. # even dragging and dropping the files on the GUI.<br />
  8279. # <br />
  8280. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8281. # drop of the
  8282. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8283. # &nbsp;</li>
  8284. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8285. # and then
  8286. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8287. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8288. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8289. # <br />
  8290. # If the selection of the object is done on the canvas by single click instead, and the
  8291. # <strong>SELECTED TAB</strong>
  8292. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8293. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8294. # it even if it was out of focus.<br />
  8295. # <br />
  8296. # You can change the parameters in this screen and the flow direction is like this:<br />
  8297. # <br />
  8298. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8299. # <strong> Geometry Object
  8300. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8301. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8302. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8303. # </ol>
  8304. #
  8305. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8306. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8307. # <strong>F3</strong>.</span></p>
  8308. #
  8309. # ''').format(fsize=fsize, tsize=tsize))
  8310. selected_text = '''
  8311. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8312. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8313. {s1}</span></p>
  8314. <ol>
  8315. <li><span style="font-size:{fsize}px">{s2}<br />
  8316. <br />
  8317. {s3}</span><br />
  8318. &nbsp;</li>
  8319. <li><span style="font-size:{fsize}px">{s4}<br />
  8320. &nbsp;</li>
  8321. <br />
  8322. <li><span style="font-size:{fsize}px">{s5}<br />
  8323. &nbsp;</li>
  8324. <br />
  8325. <li><span style="font-size:{fsize}px">{s6}<br />
  8326. <br />
  8327. {s7}</span></li>
  8328. </ol>
  8329. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8330. '''.format(
  8331. title=_("Selected Tab - Choose an Item from Project Tab"),
  8332. subtitle=_("Details"),
  8333. s1=_("The normal flow when working in FlatCAM is the following:"),
  8334. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8335. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8336. "files on the GUI."),
  8337. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8338. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8339. "actions offered within the app."),
  8340. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8341. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8342. "SELECTED TAB will be updated with the object properties according to its kind: "
  8343. "Gerber, Excellon, Geometry or CNCJob object."),
  8344. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8345. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8346. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8347. "the SELECTED TAB and populate it even if it was out of focus."),
  8348. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8349. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8350. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8351. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8352. "(again, done in SELECTED TAB) --> Save GCode."),
  8353. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8354. "or through its own key shortcut: <b>F3</b>."),
  8355. tsize=tsize,
  8356. fsize=fsize
  8357. )
  8358. sel_title.setText(selected_text)
  8359. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8360. self.ui.selected_scroll_area.setWidget(sel_title)
  8361. def setup_obj_classes(self):
  8362. """
  8363. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8364. class.
  8365. :return: None
  8366. """
  8367. FlatCAMObj.app = self
  8368. ObjectCollection.app = self
  8369. Gerber.app = self
  8370. Excellon.app = self
  8371. Geometry.app = self
  8372. CNCjob.app = self
  8373. FCProcess.app = self
  8374. FCProcessContainer.app = self
  8375. OptionsGroupUI.app = self
  8376. def version_check(self):
  8377. """
  8378. Checks for the latest version of the program. Alerts the
  8379. user if theirs is outdated. This method is meant to be run
  8380. in a separate thread.
  8381. :return: None
  8382. """
  8383. self.log.debug("version_check()")
  8384. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8385. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8386. App.version_url,
  8387. str(self.defaults['global_serial']),
  8388. str(self.version),
  8389. str(self.os),
  8390. urllib.parse.urlencode(self.defaults["global_stats"])
  8391. )
  8392. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8393. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8394. # urllib.parse.urlencode(self.defaults["global_stats"])
  8395. else:
  8396. # no_stats dict; just so it won't break things on website
  8397. no_ststs_dict = {}
  8398. no_ststs_dict["global_ststs"] = {}
  8399. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8400. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8401. App.log.debug("Checking for updates @ %s" % full_url)
  8402. # ## Get the data
  8403. try:
  8404. f = urllib.request.urlopen(full_url)
  8405. except Exception:
  8406. # App.log.warning("Failed checking for latest version. Could not connect.")
  8407. self.log.warning("Failed checking for latest version. Could not connect.")
  8408. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8409. return
  8410. try:
  8411. data = json.load(f)
  8412. except Exception as e:
  8413. App.log.error("Could not parse information about latest version.")
  8414. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8415. App.log.debug("json.load(): %s" % str(e))
  8416. f.close()
  8417. return
  8418. f.close()
  8419. # ## Latest version?
  8420. if self.version >= data["version"]:
  8421. App.log.debug("FlatCAM is up to date!")
  8422. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8423. return
  8424. App.log.debug("Newer version available.")
  8425. self.message.emit(
  8426. _("Newer Version Available"),
  8427. '%s<br><br>><b>%s</b><br>%s' % (
  8428. _("There is a newer version of FlatCAM available for download:"),
  8429. str(data["name"]),
  8430. str(data["message"])
  8431. ),
  8432. _("info")
  8433. )
  8434. def on_plotcanvas_setup(self, container=None):
  8435. """
  8436. This is doing the setup for the plot area (canvas).
  8437. :param container: QT Widget where to install the canvas
  8438. :return: None
  8439. """
  8440. if container:
  8441. plot_container = container
  8442. else:
  8443. plot_container = self.ui.right_layout
  8444. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8445. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8446. self.is_legacy = True
  8447. self.defaults["global_graphic_engine"] = "2D"
  8448. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8449. else:
  8450. try:
  8451. self.plotcanvas = PlotCanvas(plot_container, self)
  8452. except Exception as er:
  8453. msg_txt = traceback.format_exc()
  8454. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8455. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8456. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8457. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8458. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8459. msg += msg_txt
  8460. self.inform.emit(msg)
  8461. return 'fail'
  8462. # So it can receive key presses
  8463. self.plotcanvas.native.setFocus()
  8464. if self.is_legacy is False:
  8465. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8466. # Set the mouse button for panning
  8467. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8468. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8469. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8470. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8471. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8472. # Keys over plot enabled
  8473. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8474. if self.defaults['global_cursor_type'] == 'small':
  8475. self.app_cursor = self.plotcanvas.new_cursor()
  8476. else:
  8477. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8478. if self.ui.grid_snap_btn.isChecked():
  8479. self.app_cursor.enabled = True
  8480. else:
  8481. self.app_cursor.enabled = False
  8482. if self.is_legacy is False:
  8483. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8484. else:
  8485. # will use the default Matplotlib axes
  8486. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8487. def on_zoom_fit(self, event):
  8488. """
  8489. Callback for zoom-fit request. This can be either from the corresponding
  8490. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8491. with axes limits from the geometry bounds of all objects.
  8492. :param event: Ignored.
  8493. :return: None
  8494. """
  8495. if self.is_legacy is False:
  8496. self.plotcanvas.fit_view()
  8497. else:
  8498. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8499. width = xmax - xmin
  8500. height = ymax - ymin
  8501. xmin -= 0.05 * width
  8502. xmax += 0.05 * width
  8503. ymin -= 0.05 * height
  8504. ymax += 0.05 * height
  8505. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8506. def on_zoom_in(self):
  8507. """
  8508. Callback for zoom-in request.
  8509. :return:
  8510. """
  8511. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8512. def on_zoom_out(self):
  8513. """
  8514. Callback for zoom-out request.
  8515. :return:
  8516. """
  8517. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8518. def disable_all_plots(self):
  8519. self.defaults.report_usage("disable_all_plots()")
  8520. self.disable_plots(self.collection.get_list())
  8521. self.inform.emit('[success] %s' %
  8522. _("All plots disabled."))
  8523. def disable_other_plots(self):
  8524. self.defaults.report_usage("disable_other_plots()")
  8525. self.disable_plots(self.collection.get_non_selected())
  8526. self.inform.emit('[success] %s' %
  8527. _("All non selected plots disabled."))
  8528. def enable_all_plots(self):
  8529. self.defaults.report_usage("enable_all_plots()")
  8530. self.enable_plots(self.collection.get_list())
  8531. self.inform.emit('[success] %s' %
  8532. _("All plots enabled."))
  8533. def on_enable_sel_plots(self):
  8534. log.debug("App.on_enable_sel_plot()")
  8535. object_list = self.collection.get_selected()
  8536. self.enable_plots(objects=object_list)
  8537. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8538. def on_disable_sel_plots(self):
  8539. log.debug("App.on_disable_sel_plot()")
  8540. # self.inform.emit(_("Disabling plots ..."))
  8541. object_list = self.collection.get_selected()
  8542. self.disable_plots(objects=object_list)
  8543. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8544. def enable_plots(self, objects):
  8545. """
  8546. Enable plots
  8547. :param objects: list of Objects to be enabled
  8548. :return:
  8549. """
  8550. log.debug("Enabling plots ...")
  8551. # self.inform.emit(_("Working ..."))
  8552. for obj in objects:
  8553. if obj.options['plot'] is False:
  8554. obj.options.set_change_callback(lambda x: None)
  8555. obj.options['plot'] = True
  8556. try:
  8557. # only the Gerber obj has on_plot_cb_click() method
  8558. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8559. # disable this cb while disconnected,
  8560. # in case the operation takes time the user is not allowed to change it
  8561. obj.ui.plot_cb.setDisabled(True)
  8562. except AttributeError:
  8563. pass
  8564. obj.set_form_item("plot")
  8565. try:
  8566. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8567. obj.ui.plot_cb.setDisabled(False)
  8568. except AttributeError:
  8569. pass
  8570. obj.options.set_change_callback(obj.on_options_change)
  8571. def worker_task(objs):
  8572. with self.proc_container.new(_("Enabling plots ...")):
  8573. for plot_obj in objs:
  8574. # obj.options['plot'] = True
  8575. if isinstance(plot_obj, CNCJobObject):
  8576. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8577. else:
  8578. plot_obj.plot(visible=True)
  8579. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8580. # self.plots_updated.emit()
  8581. def disable_plots(self, objects):
  8582. """
  8583. Disables plots
  8584. :param objects: list of Objects to be disabled
  8585. :return:
  8586. """
  8587. # if no objects selected then do nothing
  8588. if not self.collection.get_selected():
  8589. return
  8590. log.debug("Disabling plots ...")
  8591. # self.inform.emit(_("Working ..."))
  8592. for obj in objects:
  8593. if obj.options['plot'] is True:
  8594. obj.options.set_change_callback(lambda x: None)
  8595. obj.options['plot'] = False
  8596. try:
  8597. # only the Gerber obj has on_plot_cb_click() method
  8598. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8599. obj.ui.plot_cb.setDisabled(True)
  8600. except AttributeError:
  8601. pass
  8602. obj.set_form_item("plot")
  8603. try:
  8604. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8605. obj.ui.plot_cb.setDisabled(False)
  8606. except AttributeError:
  8607. pass
  8608. obj.options.set_change_callback(obj.on_options_change)
  8609. try:
  8610. self.delete_selection_shape()
  8611. except Exception as e:
  8612. log.debug("App.disable_plots() --> %s" % str(e))
  8613. # self.plots_updated.emit()
  8614. def worker_task(objs):
  8615. with self.proc_container.new(_("Disabling plots ...")):
  8616. for plot_obj in objs:
  8617. # obj.options['plot'] = True
  8618. if isinstance(plot_obj, CNCJobObject):
  8619. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8620. else:
  8621. plot_obj.plot(visible=False)
  8622. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8623. def toggle_plots(self, objects):
  8624. """
  8625. Toggle plots visibility
  8626. :param objects: list of Objects for which to be toggled the visibility
  8627. :return: None
  8628. """
  8629. # if no objects selected then do nothing
  8630. if not self.collection.get_selected():
  8631. return
  8632. log.debug("Toggling plots ...")
  8633. self.inform.emit(_("Working ..."))
  8634. for obj in objects:
  8635. if obj.options['plot'] is False:
  8636. obj.options['plot'] = True
  8637. else:
  8638. obj.options['plot'] = False
  8639. self.plots_updated.emit()
  8640. def clear_plots(self):
  8641. """
  8642. Clear the plots
  8643. :return: None
  8644. """
  8645. objects = self.collection.get_list()
  8646. for obj in objects:
  8647. obj.clear(obj == objects[-1])
  8648. # Clear pool to free memory
  8649. self.clear_pool()
  8650. def on_set_color_action_triggered(self):
  8651. """
  8652. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8653. :return:
  8654. """
  8655. new_color = self.defaults['gerber_plot_fill']
  8656. clicked_action = self.sender()
  8657. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8658. act_name = clicked_action.text()
  8659. sel_obj_list = self.collection.get_selected()
  8660. if not sel_obj_list:
  8661. return
  8662. # a default value, I just chose this one
  8663. alpha_level = 'BF'
  8664. for sel_obj in sel_obj_list:
  8665. if sel_obj.kind == 'excellon':
  8666. alpha_level = str(hex(
  8667. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8668. elif sel_obj.kind == 'gerber':
  8669. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8670. elif sel_obj.kind == 'geometry':
  8671. alpha_level = 'FF'
  8672. else:
  8673. log.debug(
  8674. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8675. continue
  8676. sel_obj.alpha_level = alpha_level
  8677. if act_name == _('Red'):
  8678. new_color = '#FF0000' + alpha_level
  8679. if act_name == _('Blue'):
  8680. new_color = '#0000FF' + alpha_level
  8681. if act_name == _('Yellow'):
  8682. new_color = '#FFDF00' + alpha_level
  8683. if act_name == _('Green'):
  8684. new_color = '#00FF00' + alpha_level
  8685. if act_name == _('Purple'):
  8686. new_color = '#FF00FF' + alpha_level
  8687. if act_name == _('Brown'):
  8688. new_color = '#A52A2A' + alpha_level
  8689. if act_name == _('White'):
  8690. new_color = '#FFFFFF' + alpha_level
  8691. if act_name == _('Black'):
  8692. new_color = '#000000' + alpha_level
  8693. if act_name == _('Custom'):
  8694. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8695. c_dialog = QtWidgets.QColorDialog()
  8696. plot_fill_color = c_dialog.getColor(initial=new_color)
  8697. if plot_fill_color.isValid() is False:
  8698. return
  8699. new_color = str(plot_fill_color.name()) + alpha_level
  8700. if act_name == _("Default"):
  8701. for sel_obj in sel_obj_list:
  8702. if sel_obj.kind == 'excellon':
  8703. new_color = self.defaults['excellon_plot_fill']
  8704. new_line_color = self.defaults['excellon_plot_line']
  8705. elif sel_obj.kind == 'gerber':
  8706. new_color = self.defaults['gerber_plot_fill']
  8707. new_line_color = self.defaults['gerber_plot_line']
  8708. elif sel_obj.kind == 'geometry':
  8709. new_color = self.defaults['geometry_plot_line']
  8710. new_line_color = self.defaults['geometry_plot_line']
  8711. else:
  8712. log.debug(
  8713. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8714. continue
  8715. sel_obj.fill_color = new_color
  8716. sel_obj.outline_color = new_line_color
  8717. sel_obj.shapes.redraw(
  8718. update_colors=(new_color, new_line_color)
  8719. )
  8720. return
  8721. if act_name == _("Opacity"):
  8722. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8723. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8724. if ok_button:
  8725. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8726. for sel_obj in sel_obj_list:
  8727. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8728. sel_obj.shapes.redraw(
  8729. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8730. )
  8731. return
  8732. new_line_color = color_variant(new_color[:7], 0.7)
  8733. if act_name == _("White"):
  8734. new_line_color = color_variant("#dedede", 0.7)
  8735. for sel_obj in sel_obj_list:
  8736. sel_obj.fill_color = new_color
  8737. sel_obj.outline_color = new_line_color
  8738. sel_obj.shapes.redraw(
  8739. update_colors=(new_color, new_line_color)
  8740. )
  8741. def generate_cnc_job(self, objects):
  8742. """
  8743. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8744. :param objects: Selected objects in the Project Tab
  8745. :return:
  8746. """
  8747. self.defaults.report_usage("generate_cnc_job()")
  8748. # for obj in objects:
  8749. # obj.generatecncjob()
  8750. for obj in objects:
  8751. obj.on_generatecnc_button_click()
  8752. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8753. """
  8754. Saves the current project to the specified file.
  8755. :param filename: Name of the file in which to save.
  8756. :type filename: str
  8757. :param quit_action: if the project saving will be followed by an app quit; boolean
  8758. :param silent: if True will not display status messages
  8759. :param from_tcl True is run from Tcl Shell
  8760. :return: None
  8761. """
  8762. self.log.debug("save_project()")
  8763. self.save_in_progress = True
  8764. with self.proc_container.new(_("Saving FlatCAM Project")):
  8765. # Capture the latest changes
  8766. # Current object
  8767. try:
  8768. current_object = self.collection.get_active()
  8769. if current_object:
  8770. current_object.read_form()
  8771. except Exception as e:
  8772. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8773. pass
  8774. # Serialize the whole project
  8775. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8776. "options": self.options,
  8777. "version": self.version}
  8778. if self.defaults["global_save_compressed"] is True:
  8779. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8780. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8781. # # Write
  8782. f.write(g)
  8783. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8784. else:
  8785. # Open file
  8786. try:
  8787. f = open(filename, 'w')
  8788. except IOError:
  8789. App.log.error("Failed to open file for saving: %s", filename)
  8790. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8791. return
  8792. # Write
  8793. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8794. f.close()
  8795. # verification of the saved project
  8796. # Open and parse
  8797. try:
  8798. saved_f = open(filename, 'r')
  8799. except IOError:
  8800. if silent is False:
  8801. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8802. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8803. return
  8804. try:
  8805. saved_d = json.load(saved_f, object_hook=dict2obj)
  8806. except Exception:
  8807. if silent is False:
  8808. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8809. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8810. f.close()
  8811. return
  8812. saved_f.close()
  8813. if silent is False:
  8814. if 'version' in saved_d:
  8815. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8816. else:
  8817. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8818. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8819. tb_settings = QSettings("Open Source", "FlatCAM")
  8820. lock_state = self.ui.lock_action.isChecked()
  8821. tb_settings.setValue('toolbar_lock', lock_state)
  8822. # This will write the setting to the platform specific storage.
  8823. del tb_settings
  8824. # if quit:
  8825. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8826. # t.start()
  8827. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8828. def start_delayed_quit(self, delay, filename, should_quit=None):
  8829. """
  8830. :param delay: period of checking if project file size is more than zero; in seconds
  8831. :param filename: the name of the project file to be checked periodically for size more than zero
  8832. :param should_quit: if the task finished will be followed by an app quit; boolean
  8833. :return:
  8834. """
  8835. to_quit = should_quit
  8836. self.save_timer = QtCore.QTimer()
  8837. self.save_timer.setInterval(delay)
  8838. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8839. self.save_timer.start()
  8840. def check_project_file_size(self, filename, should_quit=None):
  8841. """
  8842. :param filename: the name of the project file to be checked periodically for size more than zero
  8843. :param should_quit: will quit the app if True; boolean
  8844. :return:
  8845. """
  8846. try:
  8847. if os.stat(filename).st_size > 0:
  8848. self.save_in_progress = False
  8849. self.save_timer.stop()
  8850. if should_quit:
  8851. self.app_quit.emit()
  8852. except Exception:
  8853. traceback.print_exc()
  8854. def save_project_auto(self):
  8855. """
  8856. Called periodically to save the project.
  8857. 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
  8858. # progress.
  8859. :return:
  8860. """
  8861. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8862. self.on_file_saveproject()
  8863. def save_project_auto_update(self):
  8864. """
  8865. Update the auto save time interval value.
  8866. :return:
  8867. """
  8868. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8869. try:
  8870. if self.autosave_timer.isActive():
  8871. self.autosave_timer.stop()
  8872. except Exception:
  8873. pass
  8874. if self.defaults['global_autosave'] is True:
  8875. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8876. self.autosave_timer.start()
  8877. def on_options_app2project(self):
  8878. """
  8879. Callback for Options->Transfer Options->App=>Project. Copies options
  8880. from application defaults to project defaults.
  8881. :return: None
  8882. """
  8883. self.defaults.report_usage("on_options_app2project")
  8884. self.preferencesUiManager.defaults_read_form()
  8885. self.options.update(self.defaults)
  8886. def toggle_shell(self):
  8887. """
  8888. Toggle shell: if is visible close it, if it is closed then open it
  8889. :return: None
  8890. """
  8891. self.defaults.report_usage("toggle_shell()")
  8892. if self.ui.shell_dock.isVisible():
  8893. self.ui.shell_dock.hide()
  8894. self.plotcanvas.native.setFocus()
  8895. else:
  8896. self.ui.shell_dock.show()
  8897. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8898. # self.shell._edit.setFocus()
  8899. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8900. # HACK - simulate a mouse click - alternative
  8901. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8902. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8903. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8904. # no_km)
  8905. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8906. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8907. # no_km)
  8908. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8909. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8910. """
  8911. Shows a message on the FlatCAM Shell
  8912. :param msg: Message to display.
  8913. :param show: Opens the shell.
  8914. :param error: Shows the message as an error.
  8915. :param warning: Shows the message as an warning.
  8916. :param success: Shows the message as an success.
  8917. :param selected: Indicate that something was selected on canvas
  8918. :return: None
  8919. """
  8920. if show:
  8921. self.ui.shell_dock.show()
  8922. try:
  8923. if error:
  8924. self.shell.append_error(msg + "\n")
  8925. elif warning:
  8926. self.shell.append_warning(msg + "\n")
  8927. elif success:
  8928. self.shell.append_success(msg + "\n")
  8929. elif selected:
  8930. self.shell.append_selected(msg + "\n")
  8931. else:
  8932. self.shell.append_output(msg + "\n")
  8933. except AttributeError:
  8934. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8935. class ArgsThread(QtCore.QObject):
  8936. open_signal = pyqtSignal(list)
  8937. start = pyqtSignal()
  8938. stop = pyqtSignal()
  8939. if sys.platform == 'win32':
  8940. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8941. else:
  8942. address = ('/tmp/testipc', 'AF_UNIX')
  8943. def __init__(self):
  8944. super(ArgsThread, self).__init__()
  8945. self.listener = None
  8946. self.thread_exit = False
  8947. self.start.connect(self.run)
  8948. self.stop.connect(self.close_listener)
  8949. def my_loop(self, address):
  8950. try:
  8951. self.listener = Listener(*address)
  8952. while self.thread_exit is False:
  8953. conn = self.listener.accept()
  8954. self.serve(conn)
  8955. except socket.error:
  8956. try:
  8957. conn = Client(*address)
  8958. conn.send(sys.argv)
  8959. conn.send('close')
  8960. # close the current instance only if there are args
  8961. if len(sys.argv) > 1:
  8962. try:
  8963. self.listener.close()
  8964. except Exception:
  8965. pass
  8966. sys.exit()
  8967. except ConnectionRefusedError:
  8968. if sys.platform == 'win32':
  8969. pass
  8970. else:
  8971. os.system('rm /tmp/testipc')
  8972. self.listener = Listener(*address)
  8973. while True:
  8974. conn = self.listener.accept()
  8975. self.serve(conn)
  8976. def serve(self, conn):
  8977. while self.thread_exit is False:
  8978. msg = conn.recv()
  8979. if msg == 'close':
  8980. break
  8981. self.open_signal.emit(msg)
  8982. conn.close()
  8983. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8984. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8985. @pyqtSlot()
  8986. def run(self):
  8987. self.my_loop(self.address)
  8988. @pyqtSlot()
  8989. def close_listener(self):
  8990. self.thread_exit = True
  8991. self.listener.close()
  8992. # end of file