FlatCAMApp.py 482 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import shutil
  16. from datetime import datetime
  17. import time
  18. import ctypes
  19. import traceback
  20. from shapely.geometry import Point, MultiPolygon
  21. from io import StringIO
  22. from reportlab.graphics import renderPDF
  23. from reportlab.pdfgen import canvas
  24. from reportlab.lib.units import inch, mm
  25. from reportlab.lib.pagesizes import landscape, portrait
  26. from svglib.svglib import svg2rlg
  27. import gc
  28. from xml.dom.minidom import parseString as parse_xml_string
  29. from multiprocessing.connection import Listener, Client
  30. from multiprocessing import Pool
  31. import socket
  32. # ####################################################################################################################
  33. # ################################### Imports part of FlatCAM #############################################
  34. # ####################################################################################################################
  35. # Diverse
  36. from FlatCAMCommon import LoudDict, color_variant
  37. from FlatCAMBookmark import BookmarkManager
  38. from FlatCAMDB import ToolsDB2
  39. from vispy.gloo.util import _screenshot
  40. from vispy.io import write_png
  41. # FlatCAM Objects
  42. from defaults import FlatCAMDefaults
  43. from flatcamObjects.ObjectCollection import *
  44. from flatcamObjects.FlatCAMObj import FlatCAMObj
  45. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  46. from flatcamObjects.FlatCAMDocument import DocumentObject
  47. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  48. from flatcamObjects.FlatCAMGeometry import GeometryObject
  49. from flatcamObjects.FlatCAMGerber import GerberObject
  50. from flatcamObjects.FlatCAMScript import ScriptObject
  51. # FlatCAM Parsing files
  52. from flatcamParsers.ParseExcellon import Excellon
  53. from flatcamParsers.ParseGerber import Gerber
  54. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  55. # FlatCAM GUI
  56. from flatcamGUI.PlotCanvas import *
  57. from flatcamGUI.PlotCanvasLegacy import *
  58. from flatcamGUI.FlatCAMGUI import *
  59. from flatcamGUI.GUIElements import FCFileSaveDialog
  60. # FlatCAM Pre-processors
  61. from FlatCAMPostProc import load_preprocessors
  62. # FlatCAM Editors
  63. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  64. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  65. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  66. from flatcamEditors.FlatCAMTextEditor import TextEditor
  67. from flatcamParsers.ParseHPGL2 import HPGL2
  68. # FlatCAM Workers
  69. from FlatCAMProcess import *
  70. from FlatCAMWorkerStack import WorkerStack
  71. # FlatCAM Tools
  72. from flatcamTools import *
  73. # FlatCAM Translation
  74. import gettext
  75. import FlatCAMTranslation as fcTranslate
  76. import builtins
  77. if sys.platform == 'win32':
  78. import winreg
  79. fcTranslate.apply_language('strings')
  80. if '_' not in builtins.__dict__:
  81. _ = gettext.gettext
  82. class App(QtCore.QObject):
  83. """
  84. The main application class. The constructor starts the GUI.
  85. """
  86. # ###############################################################################################################
  87. # ########################################## App ################################################################
  88. # ###############################################################################################################
  89. # ###############################################################################################################
  90. # ######################################### LOGGING #############################################################
  91. # ###############################################################################################################
  92. log = logging.getLogger('base')
  93. log.setLevel(logging.DEBUG)
  94. # log.setLevel(logging.WARNING)
  95. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  96. handler = logging.StreamHandler()
  97. handler.setFormatter(formatter)
  98. log.addHandler(handler)
  99. # ###############################################################################################################
  100. # #################################### Get Cmd Line Options #####################################################
  101. # ###############################################################################################################
  102. cmd_line_shellfile = ''
  103. cmd_line_shellvar = ''
  104. cmd_line_headless = None
  105. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  106. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  107. "FlatCam.py --headless=1"
  108. try:
  109. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  110. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  111. "shellvar=",
  112. "headless=",
  113. "multiprocessing-fork="])
  114. except getopt.GetoptError:
  115. print(cmd_line_help)
  116. sys.exit(2)
  117. for opt, arg in cmd_line_options:
  118. if opt == '-h':
  119. print(cmd_line_help)
  120. sys.exit()
  121. elif opt == '--shellfile':
  122. cmd_line_shellfile = arg
  123. elif opt == '--shellvar':
  124. cmd_line_shellvar = arg
  125. elif opt == '--headless':
  126. try:
  127. cmd_line_headless = eval(arg)
  128. except NameError:
  129. pass
  130. # ###############################################################################################################
  131. # ################################### Version and VERSION DATE ##################################################
  132. # ###############################################################################################################
  133. version = 8.992
  134. version_date = "2020/05/01"
  135. beta = True
  136. engine = '3D'
  137. # current date now
  138. date = str(datetime.today()).rpartition('.')[0]
  139. date = ''.join(c for c in date if c not in ':-')
  140. date = date.replace(' ', '_')
  141. # ###############################################################################################################
  142. # ############################################ URLS's ###########################################################
  143. # ###############################################################################################################
  144. # URL for update checks and statistics
  145. version_url = "http://flatcam.org/version"
  146. # App URL
  147. app_url = "http://flatcam.org"
  148. # Manual URL
  149. manual_url = "http://flatcam.org/manual/index.html"
  150. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  151. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  152. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  153. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  154. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  155. # this variable will hold the project status
  156. # if True it will mean that the project was modified and not saved
  157. should_we_save = False
  158. # flag is True if saving action has been triggered
  159. save_in_progress = False
  160. # ###############################################################################################################
  161. # ####################################### APP Signals ######################################################
  162. # ###############################################################################################################
  163. # Inform the user
  164. # Handled by:
  165. # * App.info() --> Print on the status bar
  166. inform = QtCore.pyqtSignal(str)
  167. app_quit = QtCore.pyqtSignal()
  168. # General purpose background task
  169. worker_task = QtCore.pyqtSignal(dict)
  170. # File opened
  171. # Handled by:
  172. # * register_folder()
  173. # * register_recent()
  174. # Note: Setting the parameters to unicode does not seem
  175. # to have an effect. Then are received as Qstring
  176. # anyway.
  177. # File type and filename
  178. file_opened = QtCore.pyqtSignal(str, str)
  179. # File type and filename
  180. file_saved = QtCore.pyqtSignal(str, str)
  181. # Percentage of progress
  182. progress = QtCore.pyqtSignal(int)
  183. plots_updated = QtCore.pyqtSignal()
  184. # Emitted by new_object() and passes the new object as argument, plot flag.
  185. # on_object_created() adds the object to the collection, plots on appropriate flag
  186. # and emits new_object_available.
  187. object_created = QtCore.pyqtSignal(object, bool, bool)
  188. # Emitted when a object has been changed (like scaled, mirrored)
  189. object_changed = QtCore.pyqtSignal(object)
  190. # Emitted after object has been plotted.
  191. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  192. object_plotted = QtCore.pyqtSignal(object)
  193. # Emitted when a new object has been added or deleted from/to the collection
  194. object_status_changed = QtCore.pyqtSignal(object, str, str)
  195. message = QtCore.pyqtSignal(str, str, str)
  196. # Emmited when shell command is finished(one command only)
  197. shell_command_finished = QtCore.pyqtSignal(object)
  198. # Emitted when multiprocess pool has been recreated
  199. pool_recreated = QtCore.pyqtSignal(object)
  200. # Emitted when an unhandled exception happens
  201. # in the worker task.
  202. thread_exception = QtCore.pyqtSignal(object)
  203. # used to signal that there are arguments for the app
  204. args_at_startup = QtCore.pyqtSignal(list)
  205. # a reusable signal to replot a list of objects
  206. # should be disconnected after use so it can be reused
  207. replot_signal = pyqtSignal(list)
  208. # signal emitted when jumping
  209. jump_signal = pyqtSignal(tuple)
  210. # signal emitted when jumping
  211. locate_signal = pyqtSignal(tuple, str)
  212. # close app signal
  213. close_app_signal = pyqtSignal()
  214. # will perform the cleanup operation after a Graceful Exit
  215. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  216. # graphic residues behind
  217. cleanup = pyqtSignal()
  218. def __init__(self, user_defaults=True):
  219. """
  220. Starts the application.
  221. :return: app
  222. :rtype: App
  223. """
  224. App.log.info("FlatCAM Starting...")
  225. self.main_thread = QtWidgets.QApplication.instance().thread()
  226. # ############################################################################################################
  227. # ################# Setup the listening thread for another instance launching with args ######################
  228. # ############################################################################################################
  229. if sys.platform == 'win32' or sys.platform == 'linux':
  230. # make sure the thread is stored by using a self. otherwise it's garbage collected
  231. self.th = QtCore.QThread()
  232. self.th.start(priority=QtCore.QThread.LowestPriority)
  233. self.new_launch = ArgsThread()
  234. self.new_launch.open_signal[list].connect(self.on_startup_args)
  235. self.new_launch.moveToThread(self.th)
  236. self.new_launch.start.emit()
  237. # ############################################################################################################
  238. # # ######################################## OS-specific #####################################################
  239. # ############################################################################################################
  240. portable = False
  241. # Folder for user settings.
  242. if sys.platform == 'win32':
  243. from win32comext.shell import shell, shellcon
  244. if platform.architecture()[0] == '32bit':
  245. App.log.debug("Win32!")
  246. else:
  247. App.log.debug("Win64!")
  248. # #######################################################################################################
  249. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  250. # #######################################################################################################
  251. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  252. try:
  253. with open(config_file, 'r'):
  254. pass
  255. except FileNotFoundError:
  256. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  257. try:
  258. with open(config_file, 'r') as f:
  259. try:
  260. for line in f:
  261. param = str(line).replace('\n', '').rpartition('=')
  262. if param[0] == 'portable':
  263. try:
  264. portable = eval(param[2])
  265. except NameError:
  266. portable = False
  267. if param[0] == 'headless':
  268. if param[2].lower() == 'true':
  269. self.cmd_line_headless = 1
  270. else:
  271. self.cmd_line_headless = None
  272. except Exception as e:
  273. log.debug('App.__init__() -->%s' % str(e))
  274. return
  275. except FileNotFoundError as e:
  276. log.debug(str(e))
  277. pass
  278. if portable is False:
  279. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  280. else:
  281. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  282. self.os = 'windows'
  283. else: # Linux/Unix/MacOS
  284. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  285. self.os = 'unix'
  286. # ############################################################################################################
  287. # ################################# Setup folders and files ##################################################
  288. # ############################################################################################################
  289. if not os.path.exists(self.data_path):
  290. os.makedirs(self.data_path)
  291. App.log.debug('Created data folder: ' + self.data_path)
  292. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  293. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  294. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  295. if not os.path.exists(self.preprocessorpaths):
  296. os.makedirs(self.preprocessorpaths)
  297. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  298. # create geo_tools_db.FlatDB file if there is none
  299. try:
  300. f = open(self.data_path + '/geo_tools_db.FlatDB')
  301. f.close()
  302. except IOError:
  303. App.log.debug('Creating empty geo_tool_db.FlatDB')
  304. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  305. json.dump({}, f)
  306. f.close()
  307. # create current_defaults.FlatConfig file if there is none
  308. try:
  309. f = open(self.data_path + '/current_defaults.FlatConfig')
  310. f.close()
  311. except IOError:
  312. App.log.debug('Creating empty current_defaults.FlatConfig')
  313. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  314. json.dump({}, f)
  315. f.close()
  316. # Write factory_defaults.FlatConfig file to disk
  317. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  318. # create a recent files json file if there is none
  319. try:
  320. f = open(self.data_path + '/recent.json')
  321. f.close()
  322. except IOError:
  323. App.log.debug('Creating empty recent.json')
  324. f = open(self.data_path + '/recent.json', 'w')
  325. json.dump([], f)
  326. f.close()
  327. # create a recent projects json file if there is none
  328. try:
  329. fp = open(self.data_path + '/recent_projects.json')
  330. fp.close()
  331. except IOError:
  332. App.log.debug('Creating empty recent_projects.json')
  333. fp = open(self.data_path + '/recent_projects.json', 'w')
  334. json.dump([], fp)
  335. fp.close()
  336. # Application directory. CHDIR to it. Otherwise, trying to load
  337. # GUI icons will fail as their path is relative.
  338. # This will fail under cx_freeze ...
  339. self.app_home = os.path.dirname(os.path.realpath(__file__))
  340. App.log.debug("Application path is " + self.app_home)
  341. App.log.debug("Started in " + os.getcwd())
  342. # cx_freeze workaround
  343. if os.path.isfile(self.app_home):
  344. self.app_home = os.path.dirname(self.app_home)
  345. os.chdir(self.app_home)
  346. # ############################################################################################################
  347. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  348. # ############################################################################################################
  349. self.defaults = FlatCAMDefaults()
  350. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  351. if user_defaults:
  352. self.defaults.load(filename=current_defaults_path)
  353. if self.defaults['units'] == 'MM':
  354. self.decimals = int(self.defaults['decimals_metric'])
  355. else:
  356. self.decimals = int(self.defaults['decimals_inch'])
  357. if self.defaults["global_gray_icons"] is False:
  358. self.resource_location = 'assets/resources'
  359. else:
  360. self.resource_location = 'assets/resources/dark_resources'
  361. self.current_units = self.defaults['units']
  362. # ###########################################################################################################
  363. # #################################### SETUP OBJECT CLASSES #################################################
  364. # ###########################################################################################################
  365. self.setup_obj_classes()
  366. # ###########################################################################################################
  367. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  368. # ###########################################################################################################
  369. self.pool = Pool()
  370. # ###########################################################################################################
  371. # ###################################### Setting the Splash Screen ##########################################
  372. # ###########################################################################################################
  373. splash_settings = QSettings("Open Source", "FlatCAM")
  374. if splash_settings.contains("splash_screen"):
  375. show_splash = splash_settings.value("splash_screen")
  376. else:
  377. splash_settings.setValue('splash_screen', 1)
  378. # This will write the setting to the platform specific storage.
  379. del splash_settings
  380. show_splash = 1
  381. if show_splash and self.cmd_line_headless != 1:
  382. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  383. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  384. # self.splash.setMask(splash_pix.mask())
  385. # move splashscreen to the current monitor
  386. desktop = QtWidgets.QApplication.desktop()
  387. screen = desktop.screenNumber(QtGui.QCursor.pos())
  388. current_screen_center = desktop.availableGeometry(screen).center()
  389. self.splash.move(current_screen_center - self.splash.rect().center())
  390. self.splash.show()
  391. self.splash.showMessage(_("FlatCAM is initializing ..."),
  392. alignment=Qt.AlignBottom | Qt.AlignLeft,
  393. color=QtGui.QColor("gray"))
  394. else:
  395. show_splash = 0
  396. # ###########################################################################################################
  397. # ######################################### Initialize GUI ##################################################
  398. # ###########################################################################################################
  399. # FlatCAM colors used in plotting
  400. self.FC_light_green = '#BBF268BF'
  401. self.FC_dark_green = '#006E20BF'
  402. self.FC_light_blue = '#a5a5ffbf'
  403. self.FC_dark_blue = '#0000ffbf'
  404. QtCore.QObject.__init__(self)
  405. self.ui = FlatCAMGUI(self)
  406. self.on_grid_snap_triggered(state=True)
  407. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  408. if theme_settings.contains("theme"):
  409. theme = theme_settings.value('theme', type=str)
  410. else:
  411. theme = 'white'
  412. if self.defaults["global_cursor_color_enabled"]:
  413. self.cursor_color_3D = self.defaults["global_cursor_color"]
  414. else:
  415. if theme == 'white':
  416. self.cursor_color_3D = 'black'
  417. else:
  418. self.cursor_color_3D = 'gray'
  419. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  420. self.ui.final_save.connect(self.final_save)
  421. # restore the toolbar view
  422. self.restore_toolbar_view()
  423. # restore the GUI geometry
  424. self.restore_main_win_geom()
  425. # set FlatCAM units in the Status bar
  426. self.set_screen_units(self.defaults['units'])
  427. # ###########################################################################################################
  428. # ########################################### AUTOSAVE SETUP ################################################
  429. # ###########################################################################################################
  430. self.block_autosave = False
  431. self.autosave_timer = QtCore.QTimer(self)
  432. self.save_project_auto_update()
  433. self.autosave_timer.timeout.connect(self.save_project_auto)
  434. # ###########################################################################################################
  435. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  436. # ###########################################################################################################
  437. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  438. inform=self.inform)
  439. self.preferencesUiManager.defaults_write_form()
  440. # When the self.defaults dictionary changes will update the Preferences GUI forms
  441. self.defaults.set_change_callback(self.on_defaults_dict_change)
  442. # ###########################################################################################################
  443. # ##################################### FIRST RUN SECTION ###################################################
  444. # ################################ It's done only once after install #####################################
  445. # ###########################################################################################################
  446. if self.defaults["first_run"] is True:
  447. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  448. initial_lay = 'minimal'
  449. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  450. # Set the combobox in Preferences to the current layout
  451. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  452. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  453. # after the first run, this object should be False
  454. self.defaults["first_run"] = False
  455. self.preferencesUiManager.save_defaults(silent=True)
  456. # ###########################################################################################################
  457. # ############################################ Data #########################################################
  458. # ###########################################################################################################
  459. self.recent = []
  460. self.recent_projects = []
  461. self.clipboard = QtWidgets.QApplication.clipboard()
  462. self.project_filename = None
  463. self.toggle_units_ignore = False
  464. # ###########################################################################################################
  465. # #################################### LOAD PREPROCESSORS ###################################################
  466. # ###########################################################################################################
  467. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  468. # the preprocessor file
  469. self.preprocessors = load_preprocessors(self)
  470. # make sure that always the 'default' preprocessor is the first item in the dictionary
  471. if 'default' in self.preprocessors.keys():
  472. new_ppp_dict = {}
  473. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  474. default_pp = self.preprocessors.pop('default')
  475. new_ppp_dict['default'] = default_pp
  476. # then add the rest of the keys
  477. for name, val_class in self.preprocessors.items():
  478. new_ppp_dict[name] = val_class
  479. # and now put back the ordered dict with 'default' key first
  480. self.preprocessors = new_ppp_dict
  481. for name in list(self.preprocessors.keys()):
  482. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  483. if name.partition('_')[0] == 'Paste':
  484. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  485. continue
  486. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  487. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  488. if name == 'hpgl':
  489. continue
  490. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  491. # ###########################################################################################################
  492. # ########################################## LOAD LANGUAGES ################################################
  493. # ###########################################################################################################
  494. self.languages = fcTranslate.load_languages()
  495. for name in sorted(self.languages.values()):
  496. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  497. # ###########################################################################################################
  498. # ####################################### APPLY APP LANGUAGE ################################################
  499. # ###########################################################################################################
  500. ret_val = fcTranslate.apply_language('strings')
  501. if ret_val == "no language":
  502. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  503. log.debug("Could not find the Language files. The App strings are missing.")
  504. else:
  505. # make the current language the current selection on the language combobox
  506. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  507. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  508. # ###########################################################################################################
  509. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  510. # ###########################################################################################################
  511. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  512. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  513. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  514. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  515. self.defaults.propagate_defaults()
  516. # ###########################################################################################################
  517. # ######################################## UPDATE THE OPTIONS ###############################################
  518. # ###########################################################################################################
  519. self.options = LoudDict()
  520. # -----------------------------------------------------------------------------------------------------------
  521. # Update the self.options from the self.defaults
  522. # The self.defaults holds the application defaults while the self.options holds the object defaults
  523. # -----------------------------------------------------------------------------------------------------------
  524. # Copy app defaults to project options
  525. for def_key, def_val in self.defaults.items():
  526. self.options[def_key] = deepcopy(def_val)
  527. self.preferencesUiManager.show_preferences_gui()
  528. # ### End of Data ####
  529. # ###########################################################################################################
  530. # #################################### SETUP OBJECT COLLECTION ##############################################
  531. # ###########################################################################################################
  532. self.collection = ObjectCollection(self)
  533. self.ui.project_tab_layout.addWidget(self.collection.view)
  534. # ### Adjust tabs width ## ##
  535. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  536. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  537. self.collection.view.setMinimumWidth(290)
  538. self.log.debug("Finished creating Object Collection.")
  539. # ###########################################################################################################
  540. # ######################################## SETUP Plot Area ##################################################
  541. # ###########################################################################################################
  542. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  543. if self.defaults["global_graphic_engine"] == '3D':
  544. self.is_legacy = False
  545. else:
  546. self.is_legacy = True
  547. # Event signals disconnect id holders
  548. self.mp = None
  549. self.mm = None
  550. self.mr = None
  551. self.mdc = None
  552. self.mp_zc = None
  553. self.kp = None
  554. # Matplotlib axis
  555. self.axes = None
  556. if show_splash:
  557. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  558. "Canvas initialization started."),
  559. alignment=Qt.AlignBottom | Qt.AlignLeft,
  560. color=QtGui.QColor("gray"))
  561. start_plot_time = time.time() # debug
  562. self.plotcanvas = None
  563. self.app_cursor = None
  564. self.hover_shapes = None
  565. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  566. # setup the PlotCanvas
  567. self.on_plotcanvas_setup()
  568. end_plot_time = time.time()
  569. self.used_time = end_plot_time - start_plot_time
  570. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  571. if show_splash:
  572. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  573. "Canvas initialization started.\n"
  574. "Canvas initialization finished in"), '%.2f' % self.used_time),
  575. alignment=Qt.AlignBottom | Qt.AlignLeft,
  576. color=QtGui.QColor("gray"))
  577. self.ui.splitter.setStretchFactor(1, 2)
  578. # ###########################################################################################################
  579. # ############################################### SYS TRAY ##################################################
  580. # ###########################################################################################################
  581. if self.defaults["global_systray_icon"]:
  582. self.parent_w = QtWidgets.QWidget()
  583. if self.cmd_line_headless == 1:
  584. self.trayIcon = FlatCAMSystemTray(app=self,
  585. icon=QtGui.QIcon(self.resource_location +
  586. '/flatcam_icon32_green.png'),
  587. headless=True,
  588. parent=self.parent_w)
  589. else:
  590. self.trayIcon = FlatCAMSystemTray(app=self,
  591. icon=QtGui.QIcon(self.resource_location +
  592. '/flatcam_icon32_green.png'),
  593. parent=self.parent_w)
  594. # ###########################################################################################################
  595. # ############################################### Worker SETUP ##############################################
  596. # ###########################################################################################################
  597. if self.defaults["global_worker_number"]:
  598. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  599. else:
  600. self.workers = WorkerStack(workers_number=2)
  601. self.worker_task.connect(self.workers.add_task)
  602. self.log.debug("Finished creating Workers crew.")
  603. # ###########################################################################################################
  604. # ############################################# Activity Monitor ###########################################
  605. # ###########################################################################################################
  606. self.activity_view = FlatCAMActivityView(app=self)
  607. self.ui.infobar.addWidget(self.activity_view)
  608. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  609. # ###########################################################################################################
  610. # ############################################# Signal handling #############################################
  611. # ###########################################################################################################
  612. # ########################################## Custom signals ################################################
  613. # signal for displaying messages in status bar
  614. self.inform.connect(self.info)
  615. # signal to be called when the app is quiting
  616. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  617. self.message.connect(self.message_dialog)
  618. # self.progress.connect(self.set_progress_bar)
  619. # signals that are emitted when object state changes
  620. self.object_created.connect(self.on_object_created)
  621. self.object_changed.connect(self.on_object_changed)
  622. self.object_plotted.connect(self.on_object_plotted)
  623. self.plots_updated.connect(self.on_plots_updated)
  624. # signals emitted when file state change
  625. self.file_opened.connect(self.register_recent)
  626. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  627. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  628. # ########################################## Standard signals ###############################################
  629. # ### Menu
  630. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  631. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  632. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  633. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  634. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  635. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  636. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  637. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  638. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  639. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  640. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  641. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  642. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  643. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  644. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  645. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  646. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  647. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  648. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  649. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  650. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  651. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  652. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  653. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  654. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  655. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  656. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  657. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  658. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  659. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  660. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  661. self.ui.menufile_exit.triggered.connect(self.final_save)
  662. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  663. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  664. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  665. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  666. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  667. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  668. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  669. self.ui.menueditdelete.triggered.connect(self.on_delete)
  670. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  671. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  672. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  673. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  674. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  675. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  676. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  677. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  678. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  679. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  680. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  681. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  682. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  683. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  684. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  685. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  686. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  687. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  688. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  689. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  690. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  691. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  692. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  693. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  694. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  695. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  696. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  697. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  698. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  699. self.ui.menuview_replot.triggered.connect(self.plot_all)
  700. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  701. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  702. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  703. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  704. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  705. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  706. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  707. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  708. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  709. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  710. self.ui.menuhelp_about.triggered.connect(self.on_about)
  711. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  712. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  713. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  714. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  715. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  716. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  717. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  718. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  719. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  720. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  721. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  722. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  723. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  724. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  725. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  726. # ToolBar signals
  727. self.connect_toolbar_signals()
  728. # Notebook and Plot Tab Area signals
  729. # make the right click on the notebook tab and plot tab area tab raise a menu
  730. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  731. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  732. self.on_tab_setup_context_menu()
  733. # activate initial state
  734. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  735. # Context Menu
  736. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  737. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  738. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  739. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  740. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  741. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  742. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  743. self.ui.clearplot.triggered.connect(self.clear_plots)
  744. self.ui.replot.triggered.connect(self.plot_all)
  745. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  746. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  747. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  748. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  749. self.ui.popmenu_move.triggered.connect(self.obj_move)
  750. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  751. # Project Context Menu -> Color Setting
  752. for act in self.ui.menuprojectcolor.actions():
  753. act.triggered.connect(self.on_set_color_action_triggered)
  754. # ###########################################################################################################
  755. # #################################### GUI PREFERENCES SIGNALS ##############################################
  756. # ###########################################################################################################
  757. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  758. lambda: self.on_toggle_units(no_pref=False))
  759. # ##################################### Workspace Setting Signals ###########################################
  760. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  761. self.on_workspace_modified)
  762. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  763. self.on_workspace_modified
  764. )
  765. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  766. # ###########################################################################################################
  767. # ######################################## GUI SETTINGS SIGNALS #############################################
  768. # ###########################################################################################################
  769. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  770. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  771. # ######################################## Tools related signals ############################################
  772. # Film Tool
  773. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  774. self.on_film_color_entry)
  775. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  776. self.on_film_color_button)
  777. # QRCode Tool
  778. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  779. self.on_qrcode_fill_color_entry)
  780. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  781. self.on_qrcode_fill_color_button)
  782. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  783. self.on_qrcode_back_color_entry)
  784. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  785. self.on_qrcode_back_color_button)
  786. # portability changed signal
  787. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  788. # Object list
  789. self.collection.view.activated.connect(self.on_row_activated)
  790. self.collection.item_selected.connect(self.on_row_selected)
  791. self.object_status_changed.connect(self.on_collection_updated)
  792. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  793. # Export Excellon parameters.
  794. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  795. self.on_update_exc_export
  796. )
  797. # call it once to make sure it is updated at startup
  798. self.on_update_exc_export(state=self.defaults["excellon_update"])
  799. # when there are arguments at application startup this get launched
  800. self.args_at_startup[list].connect(self.on_startup_args)
  801. # ###########################################################################################################
  802. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  803. # ###########################################################################################################
  804. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  805. lambda: self.restore_extensions(ext_type='excellon'))
  806. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  807. lambda: self.restore_extensions(ext_type='gcode'))
  808. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  809. lambda: self.restore_extensions(ext_type='gerber'))
  810. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  811. lambda: self.delete_all_extensions(ext_type='excellon'))
  812. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  813. lambda: self.delete_all_extensions(ext_type='gcode'))
  814. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  815. lambda: self.delete_all_extensions(ext_type='gerber'))
  816. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  817. lambda: self.add_extension(ext_type='excellon'))
  818. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  819. lambda: self.add_extension(ext_type='gcode'))
  820. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  821. lambda: self.add_extension(ext_type='gerber'))
  822. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  823. lambda: self.del_extension(ext_type='excellon'))
  824. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  825. lambda: self.del_extension(ext_type='gcode'))
  826. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  827. lambda: self.del_extension(ext_type='gerber'))
  828. # connect the 'Apply' buttons from the Preferences/File Associations
  829. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  830. lambda: self.on_register_files(obj_type='excellon'))
  831. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  832. lambda: self.on_register_files(obj_type='gcode'))
  833. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  834. lambda: self.on_register_files(obj_type='gerber'))
  835. # ###########################################################################################################
  836. # ########################################### KEYWORDS SIGNALS ##############################################
  837. # ###########################################################################################################
  838. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  839. lambda: self.restore_extensions(ext_type='keyword'))
  840. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  841. lambda: self.delete_all_extensions(ext_type='keyword'))
  842. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  843. lambda: self.add_extension(ext_type='keyword'))
  844. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  845. lambda: self.del_extension(ext_type='keyword'))
  846. # connect the abort_all_tasks related slots to the related signals
  847. self.proc_container.idle_flag.connect(self.app_is_idle)
  848. # signal emitted when a tab is closed in the Plot Area
  849. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  850. self.ui.grid_snap_btn.triggered.connect(self.on_grid_snap_triggered)
  851. self.ui.snap_infobar_label.clicked.connect(self.on_grid_icon_snap_clicked)
  852. # signal to close the application
  853. self.close_app_signal.connect(self.kill_app)
  854. # ################################# FINISHED CONNECTING SIGNALS #############################################
  855. # ###########################################################################################################
  856. # ###########################################################################################################
  857. # ###########################################################################################################
  858. self.log.debug("Finished connecting Signals.")
  859. # ###########################################################################################################
  860. # ########################################## Other setups ###################################################
  861. # ###########################################################################################################
  862. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  863. # depending on from where those tools are called different actions can be done
  864. self.call_source = 'app'
  865. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  866. self.tool_tab_locked = False
  867. # decide if to show or hide the Notebook side of the screen at startup
  868. if self.defaults["global_project_at_startup"] is True:
  869. self.ui.splitter.setSizes([1, 1])
  870. else:
  871. self.ui.splitter.setSizes([0, 1])
  872. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  873. self.setup_component_editor()
  874. # ###########################################################################################################
  875. # ####################################### Auto-complete KEYWORDS ############################################
  876. # ###########################################################################################################
  877. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  878. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  879. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  880. 'export_exc',
  881. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  882. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  883. 'interiors', 'isolate', 'join_excellon',
  884. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  885. 'mirror', 'ncc',
  886. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  887. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  888. 'options', 'origin',
  889. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  890. 'save', 'save_project',
  891. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  892. 'skew', 'subtract_poly', 'subtract_rectangle',
  893. 'version', 'write_gcode'
  894. ]
  895. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  896. 'Paste_1',
  897. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  898. 'Toolchange_manual', 'True', 'Users',
  899. 'all', 'auto', 'axis',
  900. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  901. 'contour', 'default',
  902. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  903. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  904. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  905. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  906. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  907. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  908. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  909. 'spacing_columns',
  910. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  911. 'toolchange_xy', 'toolchangez', 'travelz',
  912. 'tooldia', 'use_threads', 'value',
  913. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  914. ]
  915. self.tcl_keywords = [
  916. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  917. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  918. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  919. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  920. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  921. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  922. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  923. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  924. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  925. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  926. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  927. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  928. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  929. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  930. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  931. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  932. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  933. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  934. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  935. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  936. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  937. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  938. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  939. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  940. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  941. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  942. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  943. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  944. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  945. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  946. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  947. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  948. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  949. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  950. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  951. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  952. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  953. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  954. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  955. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  956. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  957. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  958. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  959. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  960. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  961. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  962. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  963. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  964. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  965. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  966. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  967. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  968. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  969. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  970. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  971. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  972. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  973. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  974. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  975. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  976. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  977. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  978. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  979. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  980. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  981. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  982. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  983. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  984. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  985. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  986. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  987. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  988. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  989. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  990. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  991. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  992. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  993. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  994. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  995. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  996. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  997. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  998. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  999. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1000. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1001. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1002. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1003. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1004. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1005. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1006. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1007. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1008. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1009. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1010. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1011. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1012. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1013. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1014. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1015. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1016. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1017. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1018. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1019. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1020. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1021. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1022. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1023. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1024. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1025. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1026. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1027. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1028. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1029. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1030. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1031. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1032. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1033. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1034. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1035. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1036. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1037. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1038. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1039. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1040. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1041. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1042. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1043. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1044. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1045. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1046. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1047. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1048. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1049. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1050. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1051. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1052. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1053. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1054. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1055. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1056. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1057. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1058. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1059. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1060. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1061. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1062. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1063. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1064. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1065. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1066. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1067. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1068. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1069. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1070. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1071. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1072. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1073. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1074. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1075. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1076. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1077. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1078. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1079. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1080. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1081. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1082. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1083. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1084. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1085. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1086. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1087. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1088. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1089. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1090. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1091. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1092. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1093. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1094. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1095. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1096. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1097. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1098. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1099. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1100. ]
  1101. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1102. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1103. # ###########################################################################################################
  1104. # ############################################## Shell SETUP ################################################
  1105. # ###########################################################################################################
  1106. self.shell = FCShell(app=self, version=self.version)
  1107. self.ui.shell_dock.setWidget(self.shell)
  1108. self.log.debug("TCL Shell has been initialized.")
  1109. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1110. if self.defaults["global_shell_at_startup"]:
  1111. self.ui.shell_dock.show()
  1112. else:
  1113. self.ui.shell_dock.hide()
  1114. # ###########################################################################################################
  1115. # ########################################## Tools and Plugins ##############################################
  1116. # ###########################################################################################################
  1117. self.dblsidedtool = None
  1118. self.distance_tool = None
  1119. self.distance_min_tool = None
  1120. self.panelize_tool = None
  1121. self.film_tool = None
  1122. self.paste_tool = None
  1123. self.calculator_tool = None
  1124. self.rules_tool = None
  1125. self.sub_tool = None
  1126. self.move_tool = None
  1127. self.cutout_tool = None
  1128. self.ncclear_tool = None
  1129. self.optimal_tool = None
  1130. self.paint_tool = None
  1131. self.transform_tool = None
  1132. self.properties_tool = None
  1133. self.pdf_tool = None
  1134. self.image_tool = None
  1135. self.pcb_wizard_tool = None
  1136. self.cal_exc_tool = None
  1137. self.qrcode_tool = None
  1138. self.copper_thieving_tool = None
  1139. self.fiducial_tool = None
  1140. self.edrills_tool = None
  1141. self.align_objects_tool = None
  1142. self.punch_tool = None
  1143. self.invert_tool = None
  1144. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1145. try:
  1146. self.install_tools()
  1147. except AttributeError as e:
  1148. log.debug("App.__init__() install tools() --> %s" % str(e))
  1149. # ###########################################################################################################
  1150. # ############################################ SETUP RECENT ITEMS ###########################################
  1151. # ###########################################################################################################
  1152. self.setup_recent_items()
  1153. # ###########################################################################################################
  1154. # ######################################### BookMarks Manager ###############################################
  1155. # ###########################################################################################################
  1156. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1157. self.install_bookmarks()
  1158. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1159. # ###########################################################################################################
  1160. # ########################################### Tools Database ################################################
  1161. # ###########################################################################################################
  1162. self.tools_db_tab = None
  1163. # ### System Font Parsing ###
  1164. # self.f_parse = ParseFont(self)
  1165. # self.parse_system_fonts()
  1166. # ###########################################################################################################
  1167. # ######################################### Check for updates ###############################################
  1168. # ###########################################################################################################
  1169. # Separate thread (Not worker)
  1170. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1171. if (self.beta is False or self.beta is None) and \
  1172. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1173. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1174. # self.thr2 = QtCore.QThread()
  1175. self.worker_task.emit({'fcn': self.version_check,
  1176. 'params': []})
  1177. # self.thr2.start(QtCore.QThread.LowPriority)
  1178. # ###########################################################################################################
  1179. # ##################################### Register files with FlatCAM; #######################################
  1180. # ################################### It works only for Windows for now ####################################
  1181. # ###########################################################################################################
  1182. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1183. self.on_register_files()
  1184. # ###########################################################################################################
  1185. # ######################################## Variables for global usage #######################################
  1186. # ###########################################################################################################
  1187. # hold the App units
  1188. self.units = 'MM'
  1189. # coordinates for relative position display
  1190. self.rel_point1 = (0, 0)
  1191. self.rel_point2 = (0, 0)
  1192. # variable to store coordinates
  1193. self.pos = (0, 0)
  1194. self.pos_canvas = (0, 0)
  1195. self.pos_jump = (0, 0)
  1196. # variable to store mouse coordinates
  1197. self.mouse = [0, 0]
  1198. # variable to store the delta positions on cavnas
  1199. self.dx = 0
  1200. self.dy = 0
  1201. # decide if we have a double click or single click
  1202. self.doubleclick = False
  1203. # store here the is_dragging value
  1204. self.event_is_dragging = False
  1205. # variable to store if a command is active (then the var is not None) and which one it is
  1206. self.command_active = None
  1207. # variable to store the status of moving selection action
  1208. # None value means that it's not an selection action
  1209. # True value = a selection from left to right
  1210. # False value = a selection from right to left
  1211. self.selection_type = None
  1212. # List to store the objects that are currently loaded in FlatCAM
  1213. # This list is updated on each object creation or object delete
  1214. self.all_objects_list = []
  1215. self.objects_under_the_click_list = []
  1216. # List to store the objects that are selected
  1217. self.sel_objects_list = []
  1218. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1219. self.key_modifiers = None
  1220. # Variable to hold the status of the axis
  1221. self.toggle_axis = True
  1222. # Variable to hold the status of the grid lines
  1223. self.toggle_grid_lines = True
  1224. # Variable to store the status of the fullscreen event
  1225. self.toggle_fscreen = False
  1226. # Variable to store the status of the code editor
  1227. self.toggle_codeeditor = False
  1228. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1229. self.click_noproject = False
  1230. self.cursor = None
  1231. # Variable to store the GCODE that was edited
  1232. self.gcode_edited = ""
  1233. self.text_editor_tab = None
  1234. # reference for the self.ui.code_editor
  1235. self.reference_code_editor = None
  1236. self.script_code = ''
  1237. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1238. self.tools_db_changed_flag = False
  1239. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1240. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1241. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1242. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1243. 'tsm']
  1244. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1245. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1246. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1247. 'sbp', 'tap', 'xpi']
  1248. self.svg_list = ['svg']
  1249. self.dxf_list = ['dxf']
  1250. self.pdf_list = ['pdf']
  1251. self.prj_list = ['flatprj']
  1252. self.conf_list = ['flatconfig']
  1253. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1254. # flag for polygons not cleared
  1255. self.poly_not_cleared = False
  1256. # VisPy visuals
  1257. self.isHovering = False
  1258. self.notHovering = True
  1259. # Window geometry
  1260. self.x_pos = None
  1261. self.y_pos = None
  1262. self.width = None
  1263. self.height = None
  1264. # when True, the app has to return from any thread
  1265. self.abort_flag = False
  1266. # set the value used in the Windows Title
  1267. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1268. # this holds a widget that is installed in the Plot Area when View Source option is used
  1269. self.source_editor_tab = None
  1270. self.pagesize = {}
  1271. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1272. # VisPy visuals
  1273. if self.is_legacy is False:
  1274. try:
  1275. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1276. except AttributeError:
  1277. self.tool_shapes = None
  1278. else:
  1279. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1280. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1281. # used in the delayed shutdown self.start_delayed_quit() method
  1282. self.save_timer = None
  1283. # ###########################################################################################################
  1284. # ################################## ADDING FlatCAM EDITORS section #########################################
  1285. # ###########################################################################################################
  1286. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1287. # at the first launch of the App , the editors will not be functional.
  1288. try:
  1289. self.geo_editor = FlatCAMGeoEditor(self)
  1290. except AttributeError:
  1291. pass
  1292. try:
  1293. self.exc_editor = FlatCAMExcEditor(self)
  1294. except AttributeError:
  1295. pass
  1296. try:
  1297. self.grb_editor = FlatCAMGrbEditor(self)
  1298. except AttributeError:
  1299. pass
  1300. self.log.debug("Finished adding FlatCAM Editor's.")
  1301. self.set_ui_title(name=_("New Project - Not saved"))
  1302. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1303. current_platform = platform.architecture()[0]
  1304. if current_platform != '64bit':
  1305. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1306. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1307. # ###########################################################################################################
  1308. # ##################################### Finished the CONSTRUCTOR ############################################
  1309. # ###########################################################################################################
  1310. App.log.debug("END of constructor. Releasing control.")
  1311. # ###########################################################################################################
  1312. # ########################################## SHOW GUI #######################################################
  1313. # ###########################################################################################################
  1314. # if the app is not started as headless, show it
  1315. if self.cmd_line_headless != 1:
  1316. if show_splash:
  1317. # finish the splash
  1318. self.splash.finish(self.ui)
  1319. mgui_settings = QSettings("Open Source", "FlatCAM")
  1320. if mgui_settings.contains("maximized_gui"):
  1321. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1322. if maximized_ui is True:
  1323. self.ui.showMaximized()
  1324. else:
  1325. self.ui.show()
  1326. else:
  1327. self.ui.show()
  1328. if self.defaults["global_systray_icon"]:
  1329. self.trayIcon.show()
  1330. else:
  1331. log.warning("******************* RUNNING HEADLESS *******************")
  1332. # ###########################################################################################################
  1333. # ######################################## START-UP ARGUMENTS ###############################################
  1334. # ###########################################################################################################
  1335. # test if the program was started with a script as parameter
  1336. if self.cmd_line_shellvar:
  1337. try:
  1338. cnt = 0
  1339. command_tcl = 0
  1340. for i in self.cmd_line_shellvar.split(','):
  1341. if i is not None:
  1342. # noinspection PyBroadException
  1343. try:
  1344. command_tcl = eval(i)
  1345. except Exception:
  1346. command_tcl = i
  1347. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1348. cnt += 1
  1349. # if there are Windows paths then replace the path separator with a Unix like one
  1350. if sys.platform == 'win32':
  1351. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1352. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1353. except Exception as ext:
  1354. print("ERROR: ", ext)
  1355. sys.exit(2)
  1356. if self.cmd_line_shellfile:
  1357. if self.cmd_line_headless != 1:
  1358. if self.ui.shell_dock.isHidden():
  1359. self.ui.shell_dock.show()
  1360. try:
  1361. with open(self.cmd_line_shellfile, "r") as myfile:
  1362. # if show_splash:
  1363. # self.splash.showMessage('%s: %ssec\n%s' % (
  1364. # _("Canvas initialization started.\n"
  1365. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1366. # _("Executing Tcl Script ...")),
  1367. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1368. # color=QtGui.QColor("gray"))
  1369. cmd_line_shellfile_text = myfile.read()
  1370. if self.cmd_line_headless != 1:
  1371. self.shell.exec_command(cmd_line_shellfile_text)
  1372. else:
  1373. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1374. except Exception as ext:
  1375. print("ERROR: ", ext)
  1376. sys.exit(2)
  1377. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1378. # the path/file_name must be enclosed in quotes if it contain spaces
  1379. if App.args:
  1380. self.args_at_startup.emit(App.args)
  1381. if self.defaults.old_defaults_found is True:
  1382. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1383. "Please reboot the application to update."))
  1384. self.defaults.old_defaults_found = False
  1385. # ######################################### INIT FINISHED #######################################################
  1386. # #################################################################################################################
  1387. # #################################################################################################################
  1388. # #################################################################################################################
  1389. # #################################################################################################################
  1390. # #################################################################################################################
  1391. @staticmethod
  1392. def copy_and_overwrite(from_path, to_path):
  1393. """
  1394. From here:
  1395. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1396. :param from_path: source path
  1397. :param to_path: destination path
  1398. :return: None
  1399. """
  1400. if os.path.exists(to_path):
  1401. shutil.rmtree(to_path)
  1402. try:
  1403. shutil.copytree(from_path, to_path)
  1404. except FileNotFoundError:
  1405. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1406. shutil.copytree(from_new_path, to_path)
  1407. def on_startup_args(self, args, silent=False):
  1408. """
  1409. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1410. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1411. :param args: a list containing the application args at startup
  1412. :return: None
  1413. """
  1414. if args is not None:
  1415. args_to_process = args
  1416. else:
  1417. args_to_process = App.args
  1418. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1419. for argument in args_to_process:
  1420. if '.FlatPrj'.lower() in argument.lower():
  1421. try:
  1422. project_name = str(argument)
  1423. if project_name == "":
  1424. if silent is False:
  1425. self.inform.emit(_("Cancelled."))
  1426. else:
  1427. # self.open_project(project_name)
  1428. run_from_arg = True
  1429. # self.worker_task.emit({'fcn': self.open_project,
  1430. # 'params': [project_name, run_from_arg]})
  1431. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1432. except Exception as e:
  1433. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1434. elif '.FlatConfig'.lower() in argument.lower():
  1435. try:
  1436. file_name = str(argument)
  1437. if file_name == "":
  1438. if silent is False:
  1439. self.inform.emit(_("Open Config file failed."))
  1440. else:
  1441. run_from_arg = True
  1442. # self.worker_task.emit({'fcn': self.open_config_file,
  1443. # 'params': [file_name, run_from_arg]})
  1444. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1445. except Exception as e:
  1446. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1447. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1448. try:
  1449. file_name = str(argument)
  1450. if file_name == "":
  1451. if silent is False:
  1452. self.inform.emit(_("Open Script file failed."))
  1453. else:
  1454. if silent is False:
  1455. self.on_fileopenscript(name=file_name)
  1456. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1457. self.on_filerunscript(name=file_name)
  1458. except Exception as e:
  1459. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1460. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1461. log.debug("App.on_startup_args() --> Quit event.")
  1462. sys.exit()
  1463. elif 'save'.lower() in argument.lower():
  1464. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1465. self.preferencesUiManager.save_defaults()
  1466. else:
  1467. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1468. proc_arg = argument.lower()
  1469. for ext in exc_list:
  1470. proc_ext = ext.replace(' ', '')
  1471. proc_ext = '.%s' % proc_ext
  1472. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1473. file_name = str(argument)
  1474. if file_name == "":
  1475. if silent is False:
  1476. self.inform.emit(_("Open Excellon file failed."))
  1477. else:
  1478. self.on_fileopenexcellon(name=file_name, signal=None)
  1479. return
  1480. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1481. for ext in gco_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 GCode file failed."))
  1489. else:
  1490. self.on_fileopengcode(name=file_name, signal=None)
  1491. return
  1492. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1493. for ext in grb_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 Gerber file failed."))
  1501. else:
  1502. self.on_fileopengerber(name=file_name, signal=None)
  1503. return
  1504. # if it reached here without already returning then the app was registered with a file that it does not
  1505. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1506. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1507. # for arg in args_to_process:
  1508. # if 'FlatCAM.exe' in arg:
  1509. # continue
  1510. # else:
  1511. # sys.exit(2)
  1512. def set_ui_title(self, name):
  1513. """
  1514. Sets the title of the main window.
  1515. :param name: String that store the project path and project name
  1516. :return: None
  1517. """
  1518. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1519. (self.version,
  1520. ('BETA' if self.beta else ''),
  1521. platform.architecture()[0],
  1522. self.engine,
  1523. name)
  1524. )
  1525. def on_app_restart(self):
  1526. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1527. # be left in the SySTray
  1528. try:
  1529. self.trayIcon.hide()
  1530. except Exception:
  1531. pass
  1532. fcTranslate.restart_program(app=self)
  1533. def clear_pool(self):
  1534. """
  1535. Clear the multiprocessing pool and calls garbage collector.
  1536. :return: None
  1537. """
  1538. self.pool.close()
  1539. self.pool = Pool()
  1540. self.pool_recreated.emit(self.pool)
  1541. gc.collect()
  1542. def install_tools(self):
  1543. """
  1544. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1545. Instantiation of the Tools classes.
  1546. The order that the tools are installed is important as they can depend on each other install position.
  1547. :return: None
  1548. """
  1549. self.distance_tool = Distance(self)
  1550. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1551. before=self.ui.menueditorigin,
  1552. separator=False)
  1553. self.distance_min_tool = DistanceMin(self)
  1554. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1555. pos=self.ui.menuedit,
  1556. before=self.ui.menueditorigin,
  1557. separator=True)
  1558. self.dblsidedtool = DblSidedTool(self)
  1559. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1560. self.cal_exc_tool = ToolCalibration(self)
  1561. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1562. before=self.dblsidedtool.menuAction,
  1563. separator=False)
  1564. self.align_objects_tool = AlignObjects(self)
  1565. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1566. self.edrills_tool = ToolExtractDrills(self)
  1567. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1568. self.panelize_tool = Panelize(self)
  1569. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1570. self.film_tool = Film(self)
  1571. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1572. self.paste_tool = SolderPaste(self)
  1573. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1574. self.calculator_tool = ToolCalculator(self)
  1575. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1576. self.sub_tool = ToolSub(self)
  1577. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1578. pos=self.ui.menutool, separator=True)
  1579. self.rules_tool = RulesCheck(self)
  1580. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1581. pos=self.ui.menutool, separator=False)
  1582. self.optimal_tool = ToolOptimal(self)
  1583. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1584. pos=self.ui.menutool, separator=True)
  1585. self.move_tool = ToolMove(self)
  1586. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1587. before=self.ui.menueditorigin, separator=True)
  1588. self.cutout_tool = CutOut(self)
  1589. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1590. before=self.sub_tool.menuAction)
  1591. self.ncclear_tool = NonCopperClear(self)
  1592. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1593. before=self.sub_tool.menuAction, separator=True)
  1594. self.paint_tool = ToolPaint(self)
  1595. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1596. before=self.sub_tool.menuAction, separator=True)
  1597. self.copper_thieving_tool = ToolCopperThieving(self)
  1598. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1599. pos=self.ui.menutool)
  1600. self.fiducial_tool = ToolFiducials(self)
  1601. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1602. pos=self.ui.menutool)
  1603. self.qrcode_tool = QRCode(self)
  1604. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1605. pos=self.ui.menutool)
  1606. self.punch_tool = ToolPunchGerber(self)
  1607. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1608. self.invert_tool = ToolInvertGerber(self)
  1609. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1610. self.transform_tool = ToolTransform(self)
  1611. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1612. pos=self.ui.menuoptions, separator=True)
  1613. self.properties_tool = Properties(self)
  1614. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1615. pos=self.ui.menuoptions)
  1616. self.pdf_tool = ToolPDF(self)
  1617. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1618. pos=self.ui.menufileimport,
  1619. separator=True)
  1620. self.image_tool = ToolImage(self)
  1621. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1622. pos=self.ui.menufileimport,
  1623. separator=True)
  1624. self.pcb_wizard_tool = PcbWizard(self)
  1625. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1626. pos=self.ui.menufileimport)
  1627. self.log.debug("Tools are installed.")
  1628. def remove_tools(self):
  1629. """
  1630. Will remove all the actions in the Tool menu.
  1631. :return: None
  1632. """
  1633. for act in self.ui.menutool.actions():
  1634. self.ui.menutool.removeAction(act)
  1635. def init_tools(self):
  1636. """
  1637. Initialize the Tool tab in the notebook side of the central widget.
  1638. Remove the actions in the Tools menu.
  1639. Instantiate again the FlatCAM tools (plugins).
  1640. All this is required when changing the layout: standard, compact etc.
  1641. :return: None
  1642. """
  1643. log.debug("init_tools()")
  1644. # delete the data currently in the Tools Tab and the Tab itself
  1645. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1646. if widget is not None:
  1647. widget.deleteLater()
  1648. self.ui.notebook.removeTab(2)
  1649. # rebuild the Tools Tab
  1650. self.ui.tool_tab = QtWidgets.QWidget()
  1651. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1652. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1653. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1654. self.ui.tool_scroll_area = VerticalScrollArea()
  1655. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1656. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1657. # first remove all of them
  1658. self.remove_tools()
  1659. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1660. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1661. '&Command Line\tS')
  1662. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1663. # third install all of them
  1664. try:
  1665. self.install_tools()
  1666. except AttributeError:
  1667. pass
  1668. self.log.debug("Tools are initialized.")
  1669. # def parse_system_fonts(self):
  1670. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1671. # 'params': []})
  1672. def connect_toolbar_signals(self):
  1673. """
  1674. Reconnect the signals to the actions in the toolbar.
  1675. This has to be done each time after the FlatCAM tools are removed/installed.
  1676. :return: None
  1677. """
  1678. # Toolbar
  1679. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1680. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1681. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1682. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1683. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1684. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1685. self.ui.replot_btn.triggered.connect(self.plot_all)
  1686. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1687. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1688. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1689. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1690. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1691. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1692. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1693. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1694. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1695. self.ui.delete_btn.triggered.connect(self.on_delete)
  1696. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1697. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1698. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1699. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1700. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1701. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1702. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1703. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1704. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1705. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1706. # Tools Toolbar Signals
  1707. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1708. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1709. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1710. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1711. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1712. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1713. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1714. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1715. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1716. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1717. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1718. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1719. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1720. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1721. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1722. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1723. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1724. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1725. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1726. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1727. def object2editor(self):
  1728. """
  1729. Send the current Geometry or Excellon object (if any) into the it's editor.
  1730. :return: None
  1731. """
  1732. self.defaults.report_usage("object2editor()")
  1733. # disable the objects menu as it may interfere with the Editors
  1734. self.ui.menuobjects.setDisabled(True)
  1735. edited_object = self.collection.get_active()
  1736. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1737. isinstance(edited_object, ExcellonObject):
  1738. pass
  1739. else:
  1740. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1741. return
  1742. if isinstance(edited_object, GeometryObject):
  1743. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1744. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1745. # we set the notebook to hidden
  1746. # self.ui.splitter.setSizes([0, 1])
  1747. if edited_object.multigeo is True:
  1748. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1749. if len(sel_rows) > 1:
  1750. self.inform.emit('[WARNING_NOTCL] %s' %
  1751. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1752. "is not possible.\n"
  1753. "Edit only one geometry at a time."))
  1754. # determine the tool dia of the selected tool
  1755. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1756. # now find the key in the edited_object.tools that has this tooldia
  1757. multi_tool = 1
  1758. for tool in edited_object.tools:
  1759. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1760. multi_tool = tool
  1761. break
  1762. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1763. else:
  1764. self.geo_editor.edit_fcgeometry(edited_object)
  1765. # set call source to the Editor we go into
  1766. self.call_source = 'geo_editor'
  1767. elif isinstance(edited_object, ExcellonObject):
  1768. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1769. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1770. if self.ui.splitter.sizes()[0] == 0:
  1771. self.ui.splitter.setSizes([1, 1])
  1772. self.exc_editor.edit_fcexcellon(edited_object)
  1773. # set call source to the Editor we go into
  1774. self.call_source = 'exc_editor'
  1775. elif isinstance(edited_object, GerberObject):
  1776. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1777. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1778. if self.ui.splitter.sizes()[0] == 0:
  1779. self.ui.splitter.setSizes([1, 1])
  1780. self.grb_editor.edit_fcgerber(edited_object)
  1781. # set call source to the Editor we go into
  1782. self.call_source = 'grb_editor'
  1783. # reset the following variables so the UI is built again after edit
  1784. edited_object.ui_build = False
  1785. edited_object.build_aperture_storage = False
  1786. # make sure that we can't select another object while in Editor Mode:
  1787. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1788. self.ui.project_frame.setDisabled(True)
  1789. # delete any selection shape that might be active as they are not relevant in Editor
  1790. self.delete_selection_shape()
  1791. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1792. self.ui.plot_tab_area.protectTab(0)
  1793. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1794. self.should_we_save = True
  1795. def editor2object(self, cleanup=None):
  1796. """
  1797. Transfers the Geometry or Excellon from it's editor to the current object.
  1798. :return: None
  1799. """
  1800. self.defaults.report_usage("editor2object()")
  1801. # re-enable the objects menu that was disabled on entry in Editor mode
  1802. self.ui.menuobjects.setDisabled(False)
  1803. # do not update a geometry or excellon object unless it comes out of an editor
  1804. if self.call_source != 'app':
  1805. edited_obj = self.collection.get_active()
  1806. if cleanup is None:
  1807. msgbox = QtWidgets.QMessageBox()
  1808. msgbox.setText(_("Do you want to save the edited object?"))
  1809. msgbox.setWindowTitle(_("Close Editor"))
  1810. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1811. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1812. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1813. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1814. msgbox.setDefaultButton(bt_yes)
  1815. msgbox.exec_()
  1816. response = msgbox.clickedButton()
  1817. if response == bt_yes:
  1818. # clean the Tools Tab
  1819. self.ui.tool_scroll_area.takeWidget()
  1820. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1821. self.ui.notebook.setTabText(2, "Tool")
  1822. if isinstance(edited_obj, GeometryObject):
  1823. obj_type = "Geometry"
  1824. if cleanup is None:
  1825. self.geo_editor.update_fcgeometry(edited_obj)
  1826. # self.geo_editor.update_options(edited_obj)
  1827. self.geo_editor.deactivate()
  1828. # restore GUI to the Selected TAB
  1829. # Remove anything else in the GUI
  1830. self.ui.tool_scroll_area.takeWidget()
  1831. # update the geo object options so it is including the bounding box values
  1832. try:
  1833. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1834. edited_obj.options['xmin'] = xmin
  1835. edited_obj.options['ymin'] = ymin
  1836. edited_obj.options['xmax'] = xmax
  1837. edited_obj.options['ymax'] = ymax
  1838. except AttributeError as e:
  1839. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1840. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1841. edited_obj.build_ui()
  1842. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1843. elif isinstance(edited_obj, GerberObject):
  1844. obj_type = "Gerber"
  1845. if cleanup is None:
  1846. self.grb_editor.update_fcgerber()
  1847. self.grb_editor.update_options(edited_obj)
  1848. self.grb_editor.deactivate_grb_editor()
  1849. # delete the old object (the source object) if it was an empty one
  1850. try:
  1851. if len(edited_obj.solid_geometry) == 0:
  1852. old_name = edited_obj.options['name']
  1853. self.collection.set_active(old_name)
  1854. self.collection.delete_active()
  1855. except TypeError:
  1856. # if the solid_geometry is a single Polygon the len() will not work
  1857. # in any case, falling here means that we have something in the solid_geometry, even if only
  1858. # a single Polygon, therefore we pass this
  1859. pass
  1860. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1861. # restore GUI to the Selected TAB
  1862. # Remove anything else in the GUI
  1863. self.ui.selected_scroll_area.takeWidget()
  1864. elif isinstance(edited_obj, ExcellonObject):
  1865. obj_type = "Excellon"
  1866. if cleanup is None:
  1867. self.exc_editor.update_fcexcellon(edited_obj)
  1868. # self.exc_editor.update_options(edited_obj)
  1869. self.exc_editor.deactivate()
  1870. # restore GUI to the Selected TAB
  1871. # Remove anything else in the GUI
  1872. self.ui.tool_scroll_area.takeWidget()
  1873. # delete the old object (the source object) if it was an empty one
  1874. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1875. old_name = edited_obj.options['name']
  1876. self.collection.delete_by_name(name=old_name)
  1877. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1878. else:
  1879. self.inform.emit('[WARNING_NOTCL] %s' %
  1880. _("Select a Gerber, Geometry or Excellon Object to update."))
  1881. return
  1882. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1883. elif response == bt_no:
  1884. # clean the Tools Tab
  1885. self.ui.tool_scroll_area.takeWidget()
  1886. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1887. self.ui.notebook.setTabText(2, "Tool")
  1888. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1889. if isinstance(edited_obj, GeometryObject):
  1890. self.geo_editor.deactivate()
  1891. edited_obj.build_ui()
  1892. elif isinstance(edited_obj, GerberObject):
  1893. self.grb_editor.deactivate_grb_editor()
  1894. edited_obj.build_ui()
  1895. elif isinstance(edited_obj, ExcellonObject):
  1896. self.exc_editor.deactivate()
  1897. edited_obj.build_ui()
  1898. else:
  1899. self.inform.emit('[WARNING_NOTCL] %s' %
  1900. _("Select a Gerber, Geometry or Excellon Object to update."))
  1901. return
  1902. elif response == bt_cancel:
  1903. return
  1904. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1905. # edited_obj.build_ui()
  1906. # Switch notebook to Selected page
  1907. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1908. else:
  1909. if isinstance(edited_obj, GeometryObject):
  1910. self.geo_editor.deactivate()
  1911. elif isinstance(edited_obj, GerberObject):
  1912. self.grb_editor.deactivate_grb_editor()
  1913. elif isinstance(edited_obj, ExcellonObject):
  1914. self.exc_editor.deactivate()
  1915. else:
  1916. self.inform.emit('[WARNING_NOTCL] %s' %
  1917. _("Select a Gerber, Geometry or Excellon Object to update."))
  1918. return
  1919. # if notebook is hidden we show it
  1920. if self.ui.splitter.sizes()[0] == 0:
  1921. self.ui.splitter.setSizes([1, 1])
  1922. # restore the call_source to app
  1923. self.call_source = 'app'
  1924. edited_obj.plot()
  1925. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1926. self.ui.plot_tab_area.protectTab(0)
  1927. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1928. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1929. self.ui.project_frame.setDisabled(False)
  1930. def get_last_folder(self):
  1931. """
  1932. Get the folder path from where the last file was opened.
  1933. :return: String, last opened folder path
  1934. """
  1935. return self.defaults["global_last_folder"]
  1936. def get_last_save_folder(self):
  1937. """
  1938. Get the folder path from where the last file was saved.
  1939. :return: String, last saved folder path
  1940. """
  1941. loc = self.defaults["global_last_save_folder"]
  1942. if loc is None:
  1943. loc = self.defaults["global_last_folder"]
  1944. if loc is None:
  1945. loc = os.path.dirname(__file__)
  1946. return loc
  1947. def info(self, msg):
  1948. """
  1949. Informs the user. Normally on the status bar, optionally
  1950. also on the shell.
  1951. :param msg: Text to write.
  1952. :return: None
  1953. """
  1954. # Type of message in brackets at the beginning of the message.
  1955. match = re.search(r"\[(.*)\](.*)", msg)
  1956. if match:
  1957. level = match.group(1)
  1958. msg_ = match.group(2)
  1959. self.ui.fcinfo.set_status(str(msg_), level=level)
  1960. if level.lower() == "error":
  1961. self.shell_message(msg, error=True, show=True)
  1962. elif level.lower() == "warning":
  1963. self.shell_message(msg, warning=True, show=True)
  1964. elif level.lower() == "error_notcl":
  1965. self.shell_message(msg, error=True, show=False)
  1966. elif level.lower() == "warning_notcl":
  1967. self.shell_message(msg, warning=True, show=False)
  1968. elif level.lower() == "success":
  1969. self.shell_message(msg, success=True, show=False)
  1970. elif level.lower() == "selected":
  1971. self.shell_message(msg, selected=True, show=False)
  1972. else:
  1973. self.shell_message(msg, show=False)
  1974. else:
  1975. self.ui.fcinfo.set_status(str(msg), level="info")
  1976. # make sure that if the message is to clear the infobar with a space
  1977. # is not printed over and over on the shell
  1978. if msg != '':
  1979. self.shell_message(msg)
  1980. def restore_toolbar_view(self):
  1981. """
  1982. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1983. was saved in the defaults dictionary.
  1984. :return: None
  1985. """
  1986. tb = self.defaults["global_toolbar_view"]
  1987. if tb & 1:
  1988. self.ui.toolbarfile.setVisible(True)
  1989. else:
  1990. self.ui.toolbarfile.setVisible(False)
  1991. if tb & 2:
  1992. self.ui.toolbargeo.setVisible(True)
  1993. else:
  1994. self.ui.toolbargeo.setVisible(False)
  1995. if tb & 4:
  1996. self.ui.toolbarview.setVisible(True)
  1997. else:
  1998. self.ui.toolbarview.setVisible(False)
  1999. if tb & 8:
  2000. self.ui.toolbartools.setVisible(True)
  2001. else:
  2002. self.ui.toolbartools.setVisible(False)
  2003. if tb & 16:
  2004. self.ui.exc_edit_toolbar.setVisible(True)
  2005. else:
  2006. self.ui.exc_edit_toolbar.setVisible(False)
  2007. if tb & 32:
  2008. self.ui.geo_edit_toolbar.setVisible(True)
  2009. else:
  2010. self.ui.geo_edit_toolbar.setVisible(False)
  2011. if tb & 64:
  2012. self.ui.grb_edit_toolbar.setVisible(True)
  2013. else:
  2014. self.ui.grb_edit_toolbar.setVisible(False)
  2015. if tb & 128:
  2016. self.ui.snap_toolbar.setVisible(True)
  2017. else:
  2018. self.ui.snap_toolbar.setVisible(False)
  2019. if tb & 256:
  2020. self.ui.toolbarshell.setVisible(True)
  2021. else:
  2022. self.ui.toolbarshell.setVisible(False)
  2023. def on_import_preferences(self):
  2024. """
  2025. Loads the application default settings from a saved file into
  2026. ``self.defaults`` dictionary.
  2027. :return: None
  2028. """
  2029. self.defaults.report_usage("on_import_preferences")
  2030. App.log.debug("App.on_import_preferences()")
  2031. # Show file chooser
  2032. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2033. try:
  2034. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2035. directory=self.data_path,
  2036. filter=filter_)
  2037. except TypeError:
  2038. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2039. filter=filter_)
  2040. filename = str(filename)
  2041. if filename == "":
  2042. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2043. return
  2044. # Load in the defaults from the chosen file
  2045. self.defaults.load(filename=filename)
  2046. self.preferencesUiManager.on_preferences_edited()
  2047. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2048. def on_export_preferences(self):
  2049. """
  2050. Save the defaults dictionary to a file.
  2051. :return: None
  2052. """
  2053. self.defaults.report_usage("on_export_preferences")
  2054. App.log.debug("on_export_preferences()")
  2055. defaults_file_content = None
  2056. # Show file chooser
  2057. date = str(datetime.today()).rpartition('.')[0]
  2058. date = ''.join(c for c in date if c not in ':-')
  2059. date = date.replace(' ', '_')
  2060. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2061. try:
  2062. filename, _f = FCFileSaveDialog.get_saved_filename(
  2063. caption=_("Export FlatCAM Preferences"),
  2064. directory=self.data_path + '/preferences_' + date,
  2065. filter=filter__
  2066. )
  2067. except TypeError:
  2068. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2069. filename = str(filename)
  2070. if filename == "":
  2071. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2072. return
  2073. # Update options
  2074. self.preferencesUiManager.defaults_read_form()
  2075. self.defaults.propagate_defaults()
  2076. # Save update options
  2077. try:
  2078. self.defaults.write(filename=filename)
  2079. except Exception:
  2080. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2081. return
  2082. if self.defaults["global_open_style"] is False:
  2083. self.file_opened.emit("preferences", filename)
  2084. self.file_saved.emit("preferences", filename)
  2085. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2086. def save_to_file(self, content_to_save, txt_content):
  2087. """
  2088. Save something to a file.
  2089. :return: None
  2090. """
  2091. self.defaults.report_usage("save_to_file")
  2092. App.log.debug("save_to_file()")
  2093. self.date = str(datetime.today()).rpartition('.')[0]
  2094. self.date = ''.join(c for c in self.date if c not in ':-')
  2095. self.date = self.date.replace(' ', '_')
  2096. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2097. path_to_save = self.defaults["global_last_save_folder"] if\
  2098. self.defaults["global_last_save_folder"] is not None else self.data_path
  2099. try:
  2100. filename, _f = FCFileSaveDialog.get_saved_filename(
  2101. caption=_("Save to file"),
  2102. directory=path_to_save + '/file_' + self.date,
  2103. filter=filter__
  2104. )
  2105. except TypeError:
  2106. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2107. filename = str(filename)
  2108. if filename == "":
  2109. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2110. return
  2111. else:
  2112. try:
  2113. with open(filename, 'w') as f:
  2114. ___ = f.read()
  2115. except PermissionError:
  2116. self.inform.emit('[WARNING] %s' %
  2117. _("Permission denied, saving not possible.\n"
  2118. "Most likely another app is holding the file open and not accessible."))
  2119. return
  2120. except IOError:
  2121. App.log.debug('Creating a new file ...')
  2122. f = open(filename, 'w')
  2123. f.close()
  2124. except Exception:
  2125. e = sys.exc_info()[0]
  2126. App.log.error("Could not load the file.")
  2127. App.log.error(str(e))
  2128. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2129. return
  2130. # Save content
  2131. if filename.rpartition('.')[2].lower() == 'html':
  2132. file_content = content_to_save
  2133. else:
  2134. file_content = txt_content
  2135. try:
  2136. with open(filename, "w") as f:
  2137. f.write(file_content)
  2138. except Exception:
  2139. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2140. return
  2141. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2142. def save_geometry(self, x, y, width, height, notebook_width):
  2143. """
  2144. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2145. launch of the application.
  2146. :param x: X position of the main window
  2147. :param y: Y position of the main window
  2148. :param width: width of the main window
  2149. :param height: height of the main window
  2150. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2151. :return: None
  2152. """
  2153. self.defaults["global_def_win_x"] = x
  2154. self.defaults["global_def_win_y"] = y
  2155. self.defaults["global_def_win_w"] = width
  2156. self.defaults["global_def_win_h"] = height
  2157. self.defaults["global_def_notebook_width"] = notebook_width
  2158. self.preferencesUiManager.save_defaults()
  2159. def restore_main_win_geom(self):
  2160. try:
  2161. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2162. self.defaults["global_def_win_y"],
  2163. self.defaults["global_def_win_w"],
  2164. self.defaults["global_def_win_h"])
  2165. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2166. except KeyError as e:
  2167. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2168. def message_dialog(self, title, message, kind="info"):
  2169. """
  2170. Builds and show a custom QMessageBox to be used in FlatCAM.
  2171. :param title: title of the QMessageBox
  2172. :param message: message to be displayed
  2173. :param kind: type of QMessageBox; will display a specific icon.
  2174. :return:
  2175. """
  2176. icon = {"info": QtWidgets.QMessageBox.Information,
  2177. "warning": QtWidgets.QMessageBox.Warning,
  2178. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2179. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2180. dlg.setText(message)
  2181. dlg.exec_()
  2182. def register_recent(self, kind, filename):
  2183. """
  2184. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2185. dictionary.
  2186. :param kind: type of file that was opened
  2187. :param filename: the path and file name for the file that was opened
  2188. :return:
  2189. """
  2190. self.log.debug("register_recent()")
  2191. self.log.debug(" %s" % kind)
  2192. self.log.debug(" %s" % filename)
  2193. record = {'kind': str(kind), 'filename': str(filename)}
  2194. if record in self.recent:
  2195. return
  2196. if record in self.recent_projects:
  2197. return
  2198. if record['kind'] == 'project':
  2199. self.recent_projects.insert(0, record)
  2200. else:
  2201. self.recent.insert(0, record)
  2202. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2203. self.recent.pop()
  2204. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2205. self.recent_projects.pop()
  2206. try:
  2207. f = open(self.data_path + '/recent.json', 'w')
  2208. except IOError:
  2209. App.log.error("Failed to open recent items file for writing.")
  2210. self.inform.emit('[ERROR_NOTCL] %s' %
  2211. _('Failed to open recent files file for writing.'))
  2212. return
  2213. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2214. f.close()
  2215. try:
  2216. fp = open(self.data_path + '/recent_projects.json', 'w')
  2217. except IOError:
  2218. App.log.error("Failed to open recent items file for writing.")
  2219. self.inform.emit('[ERROR_NOTCL] %s' %
  2220. _('Failed to open recent projects file for writing.'))
  2221. return
  2222. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2223. fp.close()
  2224. # Re-build the recent items menu
  2225. self.setup_recent_items()
  2226. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2227. """
  2228. Creates a new specialized FlatCAMObj and attaches it to the application,
  2229. this is, updates the GUI accordingly, any other records and plots it.
  2230. This method is thread-safe.
  2231. Notes:
  2232. * If the name is in use, the self.collection will modify it
  2233. when appending it to the collection. There is no need to handle
  2234. name conflicts here.
  2235. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2236. :type kind: str
  2237. :param name: Name for the object.
  2238. :type name: str
  2239. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2240. The function is called with 2 parameters: the new object and the App instance.
  2241. :type initialize: function
  2242. :param active:
  2243. :param fit:
  2244. :param plot: If to plot the resulting object
  2245. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2246. self.collection
  2247. :return: None
  2248. :rtype: None
  2249. """
  2250. App.log.debug("new_object()")
  2251. obj_plot = plot
  2252. obj_autoselected = autoselected
  2253. t0 = time.time() # Debug
  2254. # ## Create object
  2255. classdict = {
  2256. "gerber": GerberObject,
  2257. "excellon": ExcellonObject,
  2258. "cncjob": CNCJobObject,
  2259. "geometry": GeometryObject,
  2260. "script": ScriptObject,
  2261. "document": DocumentObject
  2262. }
  2263. App.log.debug("Calling object constructor...")
  2264. # Object creation/instantiation
  2265. obj = classdict[kind](name)
  2266. obj.units = self.options["units"]
  2267. # IMPORTANT
  2268. # The key names in defaults and options dictionary's are not random:
  2269. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2270. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2271. # copied to self.options. After that, below, depending on the type of
  2272. # object that is created, it will strip the name of the object and the underline (if the original key was
  2273. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2274. # "toolchange"
  2275. for option in self.options:
  2276. if option.find(kind + "_") == 0:
  2277. oname = option[len(kind) + 1:]
  2278. obj.options[oname] = self.options[option]
  2279. obj.isHovering = False
  2280. obj.notHovering = True
  2281. # Initialize as per user request
  2282. # User must take care to implement initialize
  2283. # in a thread-safe way as is is likely that we
  2284. # have been invoked in a separate thread.
  2285. t1 = time.time()
  2286. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2287. try:
  2288. return_value = initialize(obj, self)
  2289. except Exception as e:
  2290. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2291. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2292. msg += traceback.format_exc()
  2293. self.inform.emit(msg)
  2294. return "fail"
  2295. t2 = time.time()
  2296. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2297. if return_value == 'fail':
  2298. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2299. return "fail"
  2300. # Check units and convert if necessary
  2301. # This condition CAN be true because initialize() can change obj.units
  2302. if self.options["units"].upper() != obj.units.upper():
  2303. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2304. obj.convert_units(self.options["units"])
  2305. t3 = time.time()
  2306. self.log.debug("%f seconds converting units." % (t3 - t2))
  2307. # Create the bounding box for the object and then add the results to the obj.options
  2308. # But not for Scripts or for Documents
  2309. if kind != 'document' and kind != 'script':
  2310. try:
  2311. xmin, ymin, xmax, ymax = obj.bounds()
  2312. obj.options['xmin'] = xmin
  2313. obj.options['ymin'] = ymin
  2314. obj.options['xmax'] = xmax
  2315. obj.options['ymax'] = ymax
  2316. except Exception as e:
  2317. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2318. return "fail"
  2319. try:
  2320. if kind == 'excellon':
  2321. obj.fill_color = self.defaults["excellon_plot_fill"]
  2322. obj.outline_color = self.defaults["excellon_plot_line"]
  2323. if kind == 'gerber':
  2324. obj.fill_color = self.defaults["gerber_plot_fill"]
  2325. obj.outline_color = self.defaults["gerber_plot_line"]
  2326. except Exception as e:
  2327. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2328. # update the KeyWords list with the name of the file
  2329. self.myKeywords.append(obj.options['name'])
  2330. log.debug("Moving new object back to main thread.")
  2331. # Move the object to the main thread and let the app know that it is available.
  2332. obj.moveToThread(self.main_thread)
  2333. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2334. return obj
  2335. def new_excellon_object(self):
  2336. """
  2337. Creates a new, blank Excellon object.
  2338. :return: None
  2339. """
  2340. self.defaults.report_usage("new_excellon_object()")
  2341. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2342. def new_geometry_object(self):
  2343. """
  2344. Creates a new, blank and single-tool Geometry object.
  2345. :return: None
  2346. """
  2347. self.defaults.report_usage("new_geometry_object()")
  2348. def initialize(obj, app):
  2349. obj.multitool = False
  2350. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2351. def new_gerber_object(self):
  2352. """
  2353. Creates a new, blank Gerber object.
  2354. :return: None
  2355. """
  2356. self.defaults.report_usage("new_gerber_object()")
  2357. def initialize(grb_obj, app):
  2358. grb_obj.multitool = False
  2359. grb_obj.source_file = []
  2360. grb_obj.multigeo = False
  2361. grb_obj.follow = False
  2362. grb_obj.apertures = {}
  2363. grb_obj.solid_geometry = []
  2364. try:
  2365. grb_obj.options['xmin'] = 0
  2366. grb_obj.options['ymin'] = 0
  2367. grb_obj.options['xmax'] = 0
  2368. grb_obj.options['ymax'] = 0
  2369. except KeyError:
  2370. pass
  2371. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2372. def new_script_object(self, name=None, text=None):
  2373. """
  2374. Creates a new, blank TCL Script object.
  2375. :param name: a name for the new object
  2376. :param text: pass a source file to the newly created script to be loaded in it
  2377. :return: None
  2378. """
  2379. self.defaults.report_usage("new_script_object()")
  2380. if text is not None:
  2381. new_source_file = text
  2382. else:
  2383. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2384. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2385. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2386. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2387. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2388. # "ListSys, MillDrills,\n" \
  2389. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2390. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2391. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2392. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2393. # "# SubtractRectangle, Version, WriteGCode\n"
  2394. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2395. '# %s:\n' % _('TCL Tutorial is here') + \
  2396. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2397. '# %s:\n' % _("FlatCAM commands list")
  2398. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2399. "(displayed in Tcl Shell).")
  2400. def initialize(obj, app):
  2401. obj.source_file = deepcopy(new_source_file)
  2402. if name is None:
  2403. outname = 'new_script'
  2404. else:
  2405. outname = name
  2406. self.new_object('script', outname, initialize, plot=False)
  2407. def new_document_object(self):
  2408. """
  2409. Creates a new, blank Document object.
  2410. :return: None
  2411. """
  2412. self.defaults.report_usage("new_document_object()")
  2413. def initialize(obj, app):
  2414. obj.source_file = ""
  2415. self.new_object('document', 'new_document', initialize, plot=False)
  2416. def on_object_created(self, obj, plot, auto_select):
  2417. """
  2418. Event callback for object creation.
  2419. It will add the new object to the collection. After that it will plot the object in a threaded way
  2420. :param obj: The newly created FlatCAM object.
  2421. :param plot: if the newly create object t obe plotted
  2422. :param auto_select: if the newly created object to be autoselected after creation
  2423. :return: None
  2424. """
  2425. t0 = time.time() # DEBUG
  2426. self.log.debug("on_object_created()")
  2427. # The Collection might change the name if there is a collision
  2428. self.collection.append(obj)
  2429. # after adding the object to the collection always update the list of objects that are in the collection
  2430. self.all_objects_list = self.collection.get_list()
  2431. # self.inform.emit('[selected] %s created & selected: %s' %
  2432. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2433. if obj.kind == 'gerber':
  2434. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2435. kind=obj.kind.capitalize(),
  2436. color='green',
  2437. name=str(obj.options['name']), tx=_("created/selected"))
  2438. )
  2439. elif obj.kind == 'excellon':
  2440. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2441. kind=obj.kind.capitalize(),
  2442. color='brown',
  2443. name=str(obj.options['name']), tx=_("created/selected"))
  2444. )
  2445. elif obj.kind == 'cncjob':
  2446. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2447. kind=obj.kind.capitalize(),
  2448. color='blue',
  2449. name=str(obj.options['name']), tx=_("created/selected"))
  2450. )
  2451. elif obj.kind == 'geometry':
  2452. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2453. kind=obj.kind.capitalize(),
  2454. color='red',
  2455. name=str(obj.options['name']), tx=_("created/selected"))
  2456. )
  2457. elif obj.kind == 'script':
  2458. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2459. kind=obj.kind.capitalize(),
  2460. color='orange',
  2461. name=str(obj.options['name']), tx=_("created/selected"))
  2462. )
  2463. elif obj.kind == 'document':
  2464. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2465. kind=obj.kind.capitalize(),
  2466. color='darkCyan',
  2467. name=str(obj.options['name']), tx=_("created/selected"))
  2468. )
  2469. # update the SHELL auto-completer model with the name of the new object
  2470. self.shell._edit.set_model_data(self.myKeywords)
  2471. if auto_select:
  2472. # select the just opened object but deselect the previous ones
  2473. self.collection.set_all_inactive()
  2474. self.collection.set_active(obj.options["name"])
  2475. else:
  2476. self.collection.set_all_inactive()
  2477. # here it is done the object plotting
  2478. def worker_task(t_obj):
  2479. with self.proc_container.new(_("Plotting")):
  2480. if isinstance(t_obj, CNCJobObject):
  2481. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2482. else:
  2483. t_obj.plot()
  2484. t1 = time.time() # DEBUG
  2485. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2486. self.object_plotted.emit(t_obj)
  2487. # Send to worker
  2488. # self.worker.add_task(worker_task, [self])
  2489. if plot is True:
  2490. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2491. def on_object_changed(self, obj):
  2492. """
  2493. Called whenever the geometry of the object was changed in some way.
  2494. This require the update of it's bounding values so it can be the selected on canvas.
  2495. Update the bounding box data from obj.options
  2496. :param obj: the object that was changed
  2497. :return: None
  2498. """
  2499. xmin, ymin, xmax, ymax = obj.bounds()
  2500. obj.options['xmin'] = xmin
  2501. obj.options['ymin'] = ymin
  2502. obj.options['xmax'] = xmax
  2503. obj.options['ymax'] = ymax
  2504. log.debug("Object changed, updating the bounding box data on self.options")
  2505. # delete the old selection shape
  2506. self.delete_selection_shape()
  2507. self.should_we_save = True
  2508. def on_object_plotted(self):
  2509. """
  2510. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2511. :return: None
  2512. """
  2513. self.on_zoom_fit(None)
  2514. def on_about(self):
  2515. """
  2516. Displays the "about" dialog found in the Menu --> Help.
  2517. :return: None
  2518. """
  2519. self.defaults.report_usage("on_about")
  2520. version = self.version
  2521. version_date = self.version_date
  2522. beta = self.beta
  2523. class AboutDialog(QtWidgets.QDialog):
  2524. def __init__(self, app, parent=None):
  2525. QtWidgets.QDialog.__init__(self, parent)
  2526. self.app = app
  2527. # Icon and title
  2528. self.setWindowIcon(parent.app_icon)
  2529. self.setWindowTitle(_("About FlatCAM"))
  2530. self.resize(600, 200)
  2531. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2532. # self.setStyleSheet(
  2533. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2534. # "background-attachment: fixed"
  2535. # )
  2536. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2537. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2538. # palette = QtGui.QPalette()
  2539. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2540. # self.setPalette(palette)
  2541. logo = QtWidgets.QLabel()
  2542. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2543. title = QtWidgets.QLabel(
  2544. "<font size=8><B>FlatCAM</B></font><BR>"
  2545. "{title}<BR>"
  2546. "<BR>"
  2547. "<BR>"
  2548. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2549. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2550. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2551. "<B>{issue}</B></a><BR>".format(
  2552. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2553. devel=_("Development"),
  2554. down=_("DOWNLOAD"),
  2555. issue=_("Issue tracker"))
  2556. )
  2557. title.setOpenExternalLinks(True)
  2558. closebtn = QtWidgets.QPushButton(_("Close"))
  2559. tab_widget = QtWidgets.QTabWidget()
  2560. description_label = QtWidgets.QLabel(
  2561. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2562. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2563. version=version,
  2564. beta=('BETA' if beta else ''),
  2565. date=version_date,
  2566. arch=platform.architecture()[0])
  2567. )
  2568. description_label.setOpenExternalLinks(True)
  2569. lic_lbl_header = QtWidgets.QLabel(
  2570. '%s:<br>%s<br>' % (
  2571. _('Licensed under the MIT license'),
  2572. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2573. "http://www.opensource.org/licenses/mit-license.php</a>"
  2574. )
  2575. )
  2576. lic_lbl_header.setOpenExternalLinks(True)
  2577. lic_lbl_body = QtWidgets.QLabel(
  2578. _(
  2579. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2580. 'of this software and associated documentation files (the "Software"), to deal\n'
  2581. 'in the Software without restriction, including without limitation the rights\n'
  2582. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2583. 'copies of the Software, and to permit persons to whom the Software is\n'
  2584. 'furnished to do so, subject to the following conditions:\n\n'
  2585. 'The above copyright notice and this permission notice shall be included in\n'
  2586. 'all copies or substantial portions of the Software.\n\n'
  2587. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2588. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2589. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2590. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2591. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2592. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2593. 'THE SOFTWARE.'
  2594. )
  2595. )
  2596. attributions_label = QtWidgets.QLabel(
  2597. _(
  2598. 'Some of the icons used are from the following sources:<br>'
  2599. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2600. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2601. 'title="Flaticon">www.flaticon.com</a></div>'
  2602. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2603. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2604. )
  2605. )
  2606. attributions_label.setOpenExternalLinks(True)
  2607. # layouts
  2608. layout1 = QtWidgets.QVBoxLayout()
  2609. layout1_1 = QtWidgets.QHBoxLayout()
  2610. layout1_2 = QtWidgets.QHBoxLayout()
  2611. layout2 = QtWidgets.QHBoxLayout()
  2612. layout3 = QtWidgets.QHBoxLayout()
  2613. self.setLayout(layout1)
  2614. layout1.addLayout(layout1_1)
  2615. layout1.addLayout(layout1_2)
  2616. layout1.addLayout(layout2)
  2617. layout1.addLayout(layout3)
  2618. layout1_1.addStretch()
  2619. layout1_1.addWidget(description_label)
  2620. layout1_2.addWidget(tab_widget)
  2621. self.splash_tab = QtWidgets.QWidget()
  2622. self.splash_tab.setObjectName("splash_about")
  2623. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2624. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2625. tab_widget.addTab(self.splash_tab, _("Splash"))
  2626. self.programmmers_tab = QtWidgets.QWidget()
  2627. self.programmmers_tab.setObjectName("programmers_about")
  2628. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2629. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2630. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2631. self.translators_tab = QtWidgets.QWidget()
  2632. self.translators_tab.setObjectName("translators_about")
  2633. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2634. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2635. tab_widget.addTab(self.translators_tab, _("Translators"))
  2636. self.license_tab = QtWidgets.QWidget()
  2637. self.license_tab.setObjectName("license_about")
  2638. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2639. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2640. tab_widget.addTab(self.license_tab, _("License"))
  2641. self.attributions_tab = QtWidgets.QWidget()
  2642. self.attributions_tab.setObjectName("attributions_about")
  2643. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2644. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2645. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2646. self.splash_tab_layout.addWidget(logo, stretch=0)
  2647. self.splash_tab_layout.addWidget(title, stretch=1)
  2648. pal = QtGui.QPalette()
  2649. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2650. self.prog_grid_lay = QtWidgets.QGridLayout()
  2651. self.prog_grid_lay.setHorizontalSpacing(20)
  2652. self.prog_grid_lay.setColumnStretch(0, 0)
  2653. self.prog_grid_lay.setColumnStretch(2, 1)
  2654. prog_widget = QtWidgets.QWidget()
  2655. prog_widget.setLayout(self.prog_grid_lay)
  2656. prog_scroll = QtWidgets.QScrollArea()
  2657. prog_scroll.setWidget(prog_widget)
  2658. prog_scroll.setWidgetResizable(True)
  2659. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2660. prog_scroll.setPalette(pal)
  2661. self.programmmers_tab_layout.addWidget(prog_scroll)
  2662. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2663. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2664. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2665. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2666. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2704. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2705. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2706. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2707. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2708. self.translator_grid_lay = QtWidgets.QGridLayout()
  2709. self.translator_grid_lay.setColumnStretch(0, 0)
  2710. self.translator_grid_lay.setColumnStretch(1, 0)
  2711. self.translator_grid_lay.setColumnStretch(2, 1)
  2712. self.translator_grid_lay.setColumnStretch(3, 0)
  2713. # trans_widget = QtWidgets.QWidget()
  2714. # trans_widget.setLayout(self.translator_grid_lay)
  2715. # self.translators_tab_layout.addWidget(trans_widget)
  2716. # self.translators_tab_layout.addStretch()
  2717. trans_widget = QtWidgets.QWidget()
  2718. trans_widget.setLayout(self.translator_grid_lay)
  2719. trans_scroll = QtWidgets.QScrollArea()
  2720. trans_scroll.setWidget(trans_widget)
  2721. trans_scroll.setWidgetResizable(True)
  2722. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2723. trans_scroll.setPalette(pal)
  2724. self.translators_tab_layout.addWidget(trans_scroll)
  2725. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2726. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2727. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2728. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2729. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 3, 2)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  2750. self.translator_grid_lay.setColumnStretch(0, 0)
  2751. self.translators_tab_layout.addStretch()
  2752. self.license_tab_layout.addWidget(lic_lbl_header)
  2753. self.license_tab_layout.addWidget(lic_lbl_body)
  2754. self.license_tab_layout.addStretch()
  2755. self.attributions_tab_layout.addWidget(attributions_label)
  2756. self.attributions_tab_layout.addStretch()
  2757. layout3.addStretch()
  2758. layout3.addWidget(closebtn)
  2759. closebtn.clicked.connect(self.accept)
  2760. AboutDialog(app=self, parent=self.ui).exec_()
  2761. def install_bookmarks(self, book_dict=None):
  2762. """
  2763. Install the bookmarks actions in the Help menu -> Bookmarks
  2764. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2765. :return: None
  2766. """
  2767. if book_dict is None:
  2768. self.defaults["global_bookmarks"].update(
  2769. {
  2770. '1': ['FlatCAM', "http://flatcam.org"],
  2771. '2': ['Backup Site', ""]
  2772. }
  2773. )
  2774. else:
  2775. self.defaults["global_bookmarks"].clear()
  2776. self.defaults["global_bookmarks"].update(book_dict)
  2777. # first try to disconnect if somehow they get connected from elsewhere
  2778. for act in self.ui.menuhelp_bookmarks.actions():
  2779. try:
  2780. act.triggered.disconnect()
  2781. except TypeError:
  2782. pass
  2783. # clear all actions except the last one who is the Bookmark manager
  2784. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2785. pass
  2786. else:
  2787. self.ui.menuhelp_bookmarks.removeAction(act)
  2788. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2789. if self.defaults["global_bookmarks"]:
  2790. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2791. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2792. # the JSON is first making the keys as strings (therefore I have to use strings too
  2793. # or do the conversion :(
  2794. # )
  2795. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2796. # the '10' entry jsut after '1' therefore ordering as strings
  2797. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2798. key=lambda x: int(x[0]))
  2799. for entry, bookmark in sorted_bookmarks:
  2800. title = bookmark[0]
  2801. weblink = bookmark[1]
  2802. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2803. act.setText(title)
  2804. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2805. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2806. if title == 'Backup Site' and weblink == "":
  2807. act.triggered.connect(self.on_backup_site)
  2808. else:
  2809. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2810. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2811. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2812. def on_bookmarks_manager(self):
  2813. """
  2814. Adds the bookmark manager in a Tab in Plot Area
  2815. :return:
  2816. """
  2817. for idx in range(self.ui.plot_tab_area.count()):
  2818. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2819. # there can be only one instance of Bookmark Manager at one time
  2820. return
  2821. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2822. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2823. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2824. # add the tab if it was closed
  2825. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2826. # delete the absolute and relative position and messages in the infobar
  2827. self.ui.position_label.setText("")
  2828. self.ui.rel_position_label.setText("")
  2829. # Switch plot_area to preferences page
  2830. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2831. def on_backup_site(self):
  2832. msgbox = QtWidgets.QMessageBox()
  2833. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2834. "1. FlatCAM.org website is down\n"
  2835. "2. Someone forked FlatCAM project and wants to point\n"
  2836. "to his own website\n\n"
  2837. "If you can't get any informations about FlatCAM beta\n"
  2838. "use the YouTube channel link from the Help menu."))
  2839. msgbox.setWindowTitle(_("Alternative website"))
  2840. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2841. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2842. msgbox.setDefaultButton(bt_yes)
  2843. msgbox.exec_()
  2844. # response = msgbox.clickedButton()
  2845. def on_file_savedefaults(self):
  2846. """
  2847. Callback for menu item File->Save Defaults. Saves application default options
  2848. ``self.defaults`` to current_defaults.FlatConfig.
  2849. :return: None
  2850. """
  2851. self.preferencesUiManager.save_defaults()
  2852. def final_save(self):
  2853. """
  2854. Callback for doing a preferences save to file whenever the application is about to quit.
  2855. If the project has changes, it will ask the user to save the project.
  2856. :return: None
  2857. """
  2858. if self.save_in_progress:
  2859. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2860. return
  2861. if self.should_we_save and self.collection.get_list():
  2862. msgbox = QtWidgets.QMessageBox()
  2863. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2864. "\n"
  2865. "Do you want to Save the project?"))
  2866. msgbox.setWindowTitle(_("Save changes"))
  2867. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2868. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2869. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2870. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2871. msgbox.setDefaultButton(bt_yes)
  2872. msgbox.exec_()
  2873. response = msgbox.clickedButton()
  2874. if response == bt_yes:
  2875. try:
  2876. self.trayIcon.hide()
  2877. except Exception:
  2878. pass
  2879. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2880. elif response == bt_no:
  2881. try:
  2882. self.trayIcon.hide()
  2883. except Exception:
  2884. pass
  2885. self.quit_application()
  2886. elif response == bt_cancel:
  2887. return
  2888. else:
  2889. try:
  2890. self.trayIcon.hide()
  2891. except Exception:
  2892. pass
  2893. self.quit_application()
  2894. def quit_application(self):
  2895. """
  2896. Called (as a pyslot or not) when the application is quit.
  2897. :return: None
  2898. """
  2899. self.preferencesUiManager.save_defaults(silent=True)
  2900. log.debug("App.quit_application() --> App Defaults saved.")
  2901. if self.cmd_line_headless != 1:
  2902. # save app state to file
  2903. stgs = QSettings("Open Source", "FlatCAM")
  2904. stgs.setValue('saved_gui_state', self.ui.saveState())
  2905. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2906. stgs.setValue(
  2907. 'language',
  2908. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2909. )
  2910. stgs.setValue(
  2911. 'notebook_font_size',
  2912. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2913. )
  2914. stgs.setValue(
  2915. 'axis_font_size',
  2916. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2917. )
  2918. stgs.setValue(
  2919. 'textbox_font_size',
  2920. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2921. )
  2922. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2923. stgs.setValue(
  2924. 'machinist',
  2925. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2926. )
  2927. # This will write the setting to the platform specific storage.
  2928. del stgs
  2929. log.debug("App.quit_application() --> App UI state saved.")
  2930. # try to quit the Socket opened by ArgsThread class
  2931. try:
  2932. self.new_launch.thread_exit = True
  2933. self.new_launch.listener.close()
  2934. except Exception as err:
  2935. log.debug("App.quit_application() --> %s" % str(err))
  2936. # try to quit the QThread that run ArgsThread class
  2937. try:
  2938. self.th.terminate()
  2939. except Exception as e:
  2940. log.debug("App.quit_application() --> %s" % str(e))
  2941. # terminate workers
  2942. self.workers.__del__()
  2943. # quit app by signalling for self.kill_app() method
  2944. # self.close_app_signal.emit()
  2945. QtWidgets.qApp.quit()
  2946. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2947. # we use the following command
  2948. # sys.exit(0)
  2949. os._exit(0) # fix to work with Python 3.8
  2950. @staticmethod
  2951. def kill_app():
  2952. # QtCore.QCoreApplication.quit()
  2953. QtWidgets.qApp.quit()
  2954. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2955. # we use the following command
  2956. sys.exit(0)
  2957. def on_portable_checked(self, state):
  2958. """
  2959. Callback called when the checkbox in Preferences GUI is checked.
  2960. It will set the application as portable by creating the preferences and recent files in the
  2961. 'config' folder found in the FlatCAM installation folder.
  2962. :param state: boolean, the state of the checkbox when clicked/checked
  2963. :return:
  2964. """
  2965. line_no = 0
  2966. data = None
  2967. if sys.platform != 'win32':
  2968. # this won't work in Linux or MacOS
  2969. return
  2970. # test if the app was frozen and choose the path for the configuration file
  2971. if getattr(sys, "frozen", False) is True:
  2972. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2973. else:
  2974. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2975. config_file = current_data_path + '\\configuration.txt'
  2976. try:
  2977. with open(config_file, 'r') as f:
  2978. try:
  2979. data = f.readlines()
  2980. except Exception as e:
  2981. log.debug('App.__init__() -->%s' % str(e))
  2982. return
  2983. except FileNotFoundError:
  2984. pass
  2985. for line in data:
  2986. line = line.strip('\n')
  2987. param = str(line).rpartition('=')
  2988. if param[0] == 'portable':
  2989. break
  2990. line_no += 1
  2991. if state:
  2992. data[line_no] = 'portable=True\n'
  2993. # create the new defauults files
  2994. # create current_defaults.FlatConfig file if there is none
  2995. try:
  2996. f = open(current_data_path + '/current_defaults.FlatConfig')
  2997. f.close()
  2998. except IOError:
  2999. App.log.debug('Creating empty current_defaults.FlatConfig')
  3000. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3001. json.dump({}, f)
  3002. f.close()
  3003. # create factory_defaults.FlatConfig file if there is none
  3004. try:
  3005. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3006. f.close()
  3007. except IOError:
  3008. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3009. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3010. json.dump({}, f)
  3011. f.close()
  3012. try:
  3013. f = open(current_data_path + '/recent.json')
  3014. f.close()
  3015. except IOError:
  3016. App.log.debug('Creating empty recent.json')
  3017. f = open(current_data_path + '/recent.json', 'w')
  3018. json.dump([], f)
  3019. f.close()
  3020. try:
  3021. fp = open(current_data_path + '/recent_projects.json')
  3022. fp.close()
  3023. except IOError:
  3024. App.log.debug('Creating empty recent_projects.json')
  3025. fp = open(current_data_path + '/recent_projects.json', 'w')
  3026. json.dump([], fp)
  3027. fp.close()
  3028. # save the current defaults to the new defaults file
  3029. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3030. else:
  3031. data[line_no] = 'portable=False\n'
  3032. with open(config_file, 'w') as f:
  3033. f.writelines(data)
  3034. def on_register_files(self, obj_type=None):
  3035. """
  3036. Called whenever there is a need to register file extensions with FlatCAM.
  3037. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3038. :param obj_type: the type of object to be register for.
  3039. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3040. :return: None
  3041. """
  3042. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3043. new_reg_path = 'Software\\Classes\\'
  3044. # find if the current user is admin
  3045. try:
  3046. is_admin = os.getuid() == 0
  3047. except AttributeError:
  3048. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3049. if is_admin is True:
  3050. root_path = winreg.HKEY_LOCAL_MACHINE
  3051. else:
  3052. root_path = winreg.HKEY_CURRENT_USER
  3053. # create the keys
  3054. def set_reg(name, root_path, new_reg_path, value):
  3055. try:
  3056. winreg.CreateKey(root_path, new_reg_path)
  3057. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3058. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3059. return True
  3060. except WindowsError:
  3061. return False
  3062. # delete key in registry
  3063. def delete_reg(root_path, reg_path, key_to_del):
  3064. key_to_del_path = reg_path + key_to_del
  3065. try:
  3066. winreg.DeleteKey(root_path, key_to_del_path)
  3067. return True
  3068. except WindowsError:
  3069. return False
  3070. if obj_type is None or obj_type == 'excellon':
  3071. exc_list = \
  3072. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3073. exc_list = [x for x in exc_list if x != '']
  3074. # register all keys in the Preferences window
  3075. for ext in exc_list:
  3076. new_k = new_reg_path + '.%s' % ext
  3077. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3078. # and unregister those that are no longer in the Preferences windows but are in the file
  3079. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3080. if ext not in exc_list:
  3081. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3082. # now write the updated extensions to the self.defaults
  3083. # new_ext = ''
  3084. # for ext in exc_list:
  3085. # new_ext = new_ext + ext + ', '
  3086. # self.defaults["fa_excellon"] = new_ext
  3087. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3088. if obj_type is None or obj_type == 'gcode':
  3089. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3090. gco_list = [x for x in gco_list if x != '']
  3091. # register all keys in the Preferences window
  3092. for ext in gco_list:
  3093. new_k = new_reg_path + '.%s' % ext
  3094. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3095. # and unregister those that are no longer in the Preferences windows but are in the file
  3096. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3097. if ext not in gco_list:
  3098. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3099. # now write the updated extensions to the self.defaults
  3100. # new_ext = ''
  3101. # for ext in gco_list:
  3102. # new_ext = new_ext + ext + ', '
  3103. # self.defaults["fa_gcode"] = new_ext
  3104. self.inform.emit('[success] %s' %
  3105. _("Selected GCode file extensions registered with FlatCAM."))
  3106. if obj_type is None or obj_type == 'gerber':
  3107. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3108. grb_list = [x for x in grb_list if x != '']
  3109. # register all keys in the Preferences window
  3110. for ext in grb_list:
  3111. new_k = new_reg_path + '.%s' % ext
  3112. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3113. # and unregister those that are no longer in the Preferences windows but are in the file
  3114. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3115. if ext not in grb_list:
  3116. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3117. # now write the updated extensions to the self.defaults
  3118. # new_ext = ''
  3119. # for ext in grb_list:
  3120. # new_ext = new_ext + ext + ', '
  3121. # self.defaults["fa_gerber"] = new_ext
  3122. self.inform.emit('[success] %s' %
  3123. _("Selected Gerber file extensions registered with FlatCAM."))
  3124. def add_extension(self, ext_type):
  3125. """
  3126. Add a file extension to the list for a specific object
  3127. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3128. :return:
  3129. """
  3130. if ext_type == 'excellon':
  3131. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3132. if new_ext == '':
  3133. return
  3134. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3135. if new_ext in old_val:
  3136. return
  3137. old_val.append(new_ext)
  3138. old_val.sort()
  3139. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3140. if ext_type == 'gcode':
  3141. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3142. if new_ext == '':
  3143. return
  3144. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3145. if new_ext in old_val:
  3146. return
  3147. old_val.append(new_ext)
  3148. old_val.sort()
  3149. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3150. if ext_type == 'gerber':
  3151. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3152. if new_ext == '':
  3153. return
  3154. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3155. if new_ext in old_val:
  3156. return
  3157. old_val.append(new_ext)
  3158. old_val.sort()
  3159. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3160. if ext_type == 'keyword':
  3161. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3162. if new_kw == '':
  3163. return
  3164. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3165. if new_kw in old_val:
  3166. return
  3167. old_val.append(new_kw)
  3168. old_val.sort()
  3169. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3170. # update the self.myKeywords so the model is updated
  3171. self.autocomplete_kw_list = \
  3172. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3173. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3174. self.shell._edit.set_model_data(self.myKeywords)
  3175. def del_extension(self, ext_type):
  3176. """
  3177. Remove a file extension from the list for a specific object
  3178. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3179. :return:
  3180. """
  3181. if ext_type == 'excellon':
  3182. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3183. if new_ext == '':
  3184. return
  3185. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3186. if new_ext not in old_val:
  3187. return
  3188. old_val.remove(new_ext)
  3189. old_val.sort()
  3190. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3191. if ext_type == 'gcode':
  3192. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3193. if new_ext == '':
  3194. return
  3195. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3196. if new_ext not in old_val:
  3197. return
  3198. old_val.remove(new_ext)
  3199. old_val.sort()
  3200. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3201. if ext_type == 'gerber':
  3202. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3203. if new_ext == '':
  3204. return
  3205. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3206. if new_ext not in old_val:
  3207. return
  3208. old_val.remove(new_ext)
  3209. old_val.sort()
  3210. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3211. if ext_type == 'keyword':
  3212. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3213. if new_kw == '':
  3214. return
  3215. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3216. if new_kw not in old_val:
  3217. return
  3218. old_val.remove(new_kw)
  3219. old_val.sort()
  3220. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3221. # update the self.myKeywords so the model is updated
  3222. self.autocomplete_kw_list = \
  3223. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3224. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3225. self.shell._edit.set_model_data(self.myKeywords)
  3226. def restore_extensions(self, ext_type):
  3227. """
  3228. Restore all file extensions associations with FlatCAM, for a specific object
  3229. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3230. :return:
  3231. """
  3232. if ext_type == 'excellon':
  3233. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3234. # for the ability to open Excellon files with .txt extension
  3235. new_exc_list = deepcopy(self.exc_list)
  3236. try:
  3237. new_exc_list.remove('txt')
  3238. except ValueError:
  3239. pass
  3240. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3241. if ext_type == 'gcode':
  3242. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3243. if ext_type == 'gerber':
  3244. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3245. if ext_type == 'keyword':
  3246. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3247. # update the self.myKeywords so the model is updated
  3248. self.autocomplete_kw_list = self.default_keywords
  3249. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3250. self.shell._edit.set_model_data(self.myKeywords)
  3251. def delete_all_extensions(self, ext_type):
  3252. """
  3253. Delete all file extensions associations with FlatCAM, for a specific object
  3254. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3255. :return:
  3256. """
  3257. if ext_type == 'excellon':
  3258. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3259. if ext_type == 'gcode':
  3260. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3261. if ext_type == 'gerber':
  3262. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3263. if ext_type == 'keyword':
  3264. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3265. # update the self.myKeywords so the model is updated
  3266. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3267. self.shell._edit.set_model_data(self.myKeywords)
  3268. def on_edit_join(self, name=None):
  3269. """
  3270. Callback for Edit->Join. Joins the selected geometry objects into
  3271. a new one.
  3272. :return: None
  3273. """
  3274. self.defaults.report_usage("on_edit_join()")
  3275. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3276. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3277. geo_type_set = set()
  3278. objs = self.collection.get_selected()
  3279. if len(objs) < 2:
  3280. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3281. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3282. return 'fail'
  3283. for obj in objs:
  3284. geo_type_set.add(obj.multigeo)
  3285. # if len(geo_type_list) == 1 means that all list elements are the same
  3286. if len(geo_type_set) != 1:
  3287. self.inform.emit('[ERROR] %s' %
  3288. _("Failed join. The Geometry objects are of different types.\n"
  3289. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3290. "convert from one to another and retry joining \n"
  3291. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3292. "the result may not be what was expected. \n"
  3293. "Check the generated GCODE."))
  3294. return
  3295. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3296. if True in geo_type_set:
  3297. def initialize(geo_obj, app):
  3298. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  3299. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3300. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3301. for v in geo_obj.tools.values():
  3302. v['data']['name'] = obj_name_multi
  3303. self.new_object("geometry", obj_name_multi, initialize)
  3304. else:
  3305. def initialize(geo_obj, app):
  3306. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  3307. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3308. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3309. for v in geo_obj.tools.values():
  3310. v['data']['name'] = obj_name_single
  3311. self.new_object("geometry", obj_name_single, initialize)
  3312. self.should_we_save = True
  3313. def on_edit_join_exc(self):
  3314. """
  3315. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3316. a new Excellon.
  3317. :return: None
  3318. """
  3319. self.defaults.report_usage("on_edit_join_exc()")
  3320. objs = self.collection.get_selected()
  3321. for obj in objs:
  3322. if not isinstance(obj, ExcellonObject):
  3323. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3324. return
  3325. if len(objs) < 2:
  3326. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3327. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3328. return 'fail'
  3329. def initialize(exc_obj, app):
  3330. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj)
  3331. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3332. self.new_object("excellon", 'Combo_Excellon', initialize)
  3333. self.should_we_save = True
  3334. def on_edit_join_grb(self):
  3335. """
  3336. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3337. a new Gerber object.
  3338. :return: None
  3339. """
  3340. self.defaults.report_usage("on_edit_join_grb()")
  3341. objs = self.collection.get_selected()
  3342. for obj in objs:
  3343. if not isinstance(obj, GerberObject):
  3344. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3345. return
  3346. if len(objs) < 2:
  3347. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3348. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3349. return 'fail'
  3350. def initialize(grb_obj, app):
  3351. GerberObject.merge(self, grb_list=objs, grb_final=grb_obj)
  3352. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3353. self.new_object("gerber", 'Combo_Gerber', initialize)
  3354. self.should_we_save = True
  3355. def on_convert_singlegeo_to_multigeo(self):
  3356. """
  3357. Called for converting a Geometry object from single-geo to multi-geo.
  3358. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3359. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3360. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3361. the solid-geometry of that tool.
  3362. :return: None
  3363. """
  3364. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3365. obj = self.collection.get_active()
  3366. if obj is None:
  3367. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3368. return
  3369. if not isinstance(obj, GeometryObject):
  3370. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3371. return
  3372. obj.multigeo = True
  3373. for tooluid, dict_value in obj.tools.items():
  3374. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3375. if not isinstance(obj.solid_geometry, list):
  3376. obj.solid_geometry = [obj.solid_geometry]
  3377. obj.solid_geometry[:] = []
  3378. obj.plot()
  3379. self.should_we_save = True
  3380. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3381. def on_convert_multigeo_to_singlegeo(self):
  3382. """
  3383. Called for converting a Geometry object from multi-geo to single-geo.
  3384. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3385. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3386. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3387. the solid-geometry of that tool.
  3388. :return: None
  3389. """
  3390. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3391. obj = self.collection.get_active()
  3392. if obj is None:
  3393. self.inform.emit('[ERROR_NOTCL] %s' %
  3394. _("Failed. Select a Geometry Object and try again."))
  3395. return
  3396. if not isinstance(obj, GeometryObject):
  3397. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3398. (_("Expected a GeometryObject, got"), type(obj)))
  3399. return
  3400. obj.multigeo = False
  3401. total_solid_geometry = []
  3402. for tooluid, dict_value in obj.tools.items():
  3403. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3404. # clear the original geometry
  3405. dict_value['solid_geometry'][:] = []
  3406. obj.solid_geometry = deepcopy(total_solid_geometry)
  3407. obj.plot()
  3408. self.should_we_save = True
  3409. self.inform.emit('[success] %s' %
  3410. _("A Geometry object was converted to SingleGeo type."))
  3411. def on_defaults_dict_change(self, field):
  3412. """
  3413. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3414. Edit -> Preferences tab window.
  3415. :param field: the key of the self.defaults dictionary that was changed.
  3416. :return: None
  3417. """
  3418. self.preferencesUiManager.defaults_write_form_field(field=field)
  3419. if field == "units":
  3420. self.set_screen_units(self.defaults['units'])
  3421. def set_screen_units(self, units):
  3422. """
  3423. Set the FlatCAM units on the status bar.
  3424. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3425. :return: None
  3426. """
  3427. self.ui.units_label.setText("[" + units.lower() + "]")
  3428. def on_toggle_units_click(self):
  3429. try:
  3430. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3431. except (TypeError, AttributeError):
  3432. pass
  3433. if self.defaults["units"] == 'MM':
  3434. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3435. else:
  3436. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3437. self.on_toggle_units(no_pref=True)
  3438. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3439. lambda: self.on_toggle_units(no_pref=False))
  3440. def on_toggle_units(self, no_pref=False):
  3441. """
  3442. Callback for the Units radio-button change in the Preferences tab.
  3443. Changes the application's default units adn for the project too.
  3444. If changing the project's units, the change propagates to all of
  3445. the objects in the project.
  3446. :return: None
  3447. """
  3448. self.defaults.report_usage("on_toggle_units")
  3449. if self.toggle_units_ignore:
  3450. return
  3451. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3452. # If option is the same, then ignore
  3453. if new_units == self.defaults["units"].upper():
  3454. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3455. return
  3456. # Options to scale
  3457. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  3458. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3459. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3460. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3461. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3462. "excellon_feedrate_probe",
  3463. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3464. "excellon_editor_slot_lin_pitch",
  3465. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3466. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3467. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3468. "geometry_z_pdepth",
  3469. "geometry_feedrate_probe", "geometry_startz",
  3470. 'cncjob_tooldia',
  3471. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3472. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3473. "tools_nccnewdia",
  3474. "tools_2sided_drilldia", "tools_film_boundary",
  3475. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3476. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3477. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3478. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3479. "tools_transform_offset_y",
  3480. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3481. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3482. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3483. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3484. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3485. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3486. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  3487. "tools_fiducials_line_thickness",
  3488. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3489. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3490. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3491. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3492. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3493. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3494. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3495. def scale_defaults(sfactor):
  3496. for dim in dimensions:
  3497. if dim == 'excellon_toolchangexy':
  3498. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3499. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3500. coords_xy[0] *= sfactor
  3501. coords_xy[1] *= sfactor
  3502. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3503. self.decimals, coords_xy[1])
  3504. elif dim == 'geometry_toolchangexy':
  3505. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3506. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3507. coords_xy[0] *= sfactor
  3508. coords_xy[1] *= sfactor
  3509. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3510. self.decimals, coords_xy[1])
  3511. elif dim == 'excellon_endxy':
  3512. coordinates = self.defaults["excellon_endxy"].split(",")
  3513. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3514. end_coords_xy[0] *= sfactor
  3515. end_coords_xy[1] *= sfactor
  3516. self.defaults['excellon_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3517. self.decimals, end_coords_xy[1])
  3518. elif dim == 'geometry_endxy':
  3519. coordinates = self.defaults["geometry_endxy"].split(",")
  3520. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3521. end_coords_xy[0] *= sfactor
  3522. end_coords_xy[1] *= sfactor
  3523. self.defaults['geometry_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3524. self.decimals, end_coords_xy[1])
  3525. elif dim == 'geometry_cnctooldia':
  3526. if type(self.defaults["geometry_cnctooldia"]) == float:
  3527. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  3528. else:
  3529. try:
  3530. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3531. tools_diameters = [eval(a) for a in tools_string if a != '']
  3532. except Exception as e:
  3533. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3534. continue
  3535. self.defaults['geometry_cnctooldia'] = ''
  3536. for t in range(len(tools_diameters)):
  3537. tools_diameters[t] *= sfactor
  3538. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  3539. elif dim == 'tools_ncctools':
  3540. if type(self.defaults["tools_ncctools"]) == float:
  3541. ncctools = [self.defaults["tools_ncctools"]]
  3542. else:
  3543. try:
  3544. tools_string = self.defaults["tools_ncctools"].split(",")
  3545. ncctools = [eval(a) for a in tools_string if a != '']
  3546. except Exception as e:
  3547. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3548. continue
  3549. self.defaults['tools_ncctools'] = ''
  3550. for t in range(len(ncctools)):
  3551. ncctools[t] *= sfactor
  3552. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  3553. elif dim == 'tools_solderpaste_tools':
  3554. if type(self.defaults["tools_solderpaste_tools"]) == float:
  3555. sptools = [self.defaults["tools_solderpaste_tools"]]
  3556. else:
  3557. try:
  3558. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3559. sptools = [eval(a) for a in tools_string if a != '']
  3560. except Exception as e:
  3561. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3562. continue
  3563. self.defaults['tools_solderpaste_tools'] = ""
  3564. for t in range(len(sptools)):
  3565. sptools[t] *= sfactor
  3566. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  3567. elif dim == 'tools_solderpaste_xy_toolchange':
  3568. try:
  3569. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3570. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3571. sp_coords[0] *= sfactor
  3572. sp_coords[1] *= sfactor
  3573. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  3574. self.decimals, sp_coords[1])
  3575. except Exception as e:
  3576. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3577. continue
  3578. elif dim == 'global_gridx' or dim == 'global_gridy':
  3579. if new_units == 'IN':
  3580. try:
  3581. val = float(self.defaults[dim]) * sfactor
  3582. except Exception as e:
  3583. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3584. continue
  3585. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3586. else:
  3587. try:
  3588. val = float(self.defaults[dim]) * sfactor
  3589. except Exception as e:
  3590. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3591. continue
  3592. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3593. else:
  3594. if self.defaults[dim]:
  3595. try:
  3596. val = float(self.defaults[dim]) * sfactor
  3597. except Exception as e:
  3598. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3599. continue
  3600. self.defaults[dim] = val
  3601. # The scaling factor depending on choice of units.
  3602. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3603. # Changing project units. Warn user.
  3604. msgbox = QtWidgets.QMessageBox()
  3605. msgbox.setWindowTitle(_("Toggle Units"))
  3606. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3607. msgbox.setText(_("Changing the units of the project\n"
  3608. "will scale all objects.\n\n"
  3609. "Do you want to continue?"))
  3610. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3611. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3612. msgbox.setDefaultButton(bt_ok)
  3613. msgbox.exec_()
  3614. response = msgbox.clickedButton()
  3615. if response == bt_ok:
  3616. if no_pref is False:
  3617. self.preferencesUiManager.defaults_read_form()
  3618. scale_defaults(factor)
  3619. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3620. self.defaults["units"] = new_units
  3621. # update the defaults from form, some may assume that the conversion is enough and it's not
  3622. self.on_options_app2project()
  3623. # update the objects
  3624. for obj in self.collection.get_list():
  3625. obj.convert_units(new_units)
  3626. # make that the properties stored in the object are also updated
  3627. self.object_changed.emit(obj)
  3628. # rebuild the object UI
  3629. obj.build_ui()
  3630. # change this only if the workspace is active
  3631. if self.defaults['global_workspace'] is True:
  3632. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3633. # adjust the grid values on the main toolbar
  3634. val_x = float(self.defaults['global_gridx']) * factor
  3635. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3636. current = self.collection.get_active()
  3637. if current is not None:
  3638. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3639. if not isinstance(current, GeometryObject):
  3640. current.to_form()
  3641. # replot all objects
  3642. self.plot_all()
  3643. # set the status labels to reflect the current FlatCAM units
  3644. self.set_screen_units(new_units)
  3645. # signal to the app that we changed the object properties and it shoud save the project
  3646. self.should_we_save = True
  3647. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3648. else:
  3649. # Undo toggling
  3650. self.toggle_units_ignore = True
  3651. if self.defaults['units'].upper() == 'MM':
  3652. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3653. else:
  3654. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3655. self.toggle_units_ignore = False
  3656. # store the grid values so they are not changed in the next step
  3657. val_x = float(self.defaults['global_gridx'])
  3658. val_y = float(self.defaults['global_gridy'])
  3659. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3660. self.preferencesUiManager.defaults_read_form()
  3661. # the self.preferencesUiManager.defaults_read_form() will update all defaults values 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.splitter_left.setVisible(False)
  3695. self.toggle_fscreen = True
  3696. elif self.toggle_fscreen is True or disable is True:
  3697. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3698. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3699. self.ui.showNormal()
  3700. self.restore_toolbar_view()
  3701. self.ui.splitter_left.setVisible(True)
  3702. self.toggle_fscreen = False
  3703. def on_toggle_plotarea(self):
  3704. self.defaults.report_usage("on_toggle_plotarea()")
  3705. try:
  3706. name = self.ui.plot_tab_area.widget(0).objectName()
  3707. except AttributeError:
  3708. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3709. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3710. self.ui.plot_tab_area.protectTab(0)
  3711. return
  3712. if name != 'plotarea':
  3713. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3714. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3715. self.ui.plot_tab_area.protectTab(0)
  3716. else:
  3717. self.ui.plot_tab_area.closeTab(0)
  3718. def on_toggle_notebook(self):
  3719. if self.ui.splitter.sizes()[0] == 0:
  3720. self.ui.splitter.setSizes([1, 1])
  3721. self.ui.menu_toggle_nb.setChecked(True)
  3722. else:
  3723. self.ui.splitter.setSizes([0, 1])
  3724. self.ui.menu_toggle_nb.setChecked(False)
  3725. def on_toggle_axis(self):
  3726. self.defaults.report_usage("on_toggle_axis()")
  3727. if self.toggle_axis is False:
  3728. if self.is_legacy is False:
  3729. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3730. parent=self.plotcanvas.view.scene)
  3731. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3732. parent=self.plotcanvas.view.scene)
  3733. else:
  3734. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3735. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3736. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3737. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3738. self.plotcanvas.canvas.draw()
  3739. self.toggle_axis = True
  3740. else:
  3741. if self.is_legacy is False:
  3742. self.plotcanvas.v_line.parent = None
  3743. self.plotcanvas.h_line.parent = None
  3744. else:
  3745. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3746. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3747. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3748. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3749. self.plotcanvas.canvas.draw()
  3750. self.toggle_axis = False
  3751. def on_toggle_grid(self):
  3752. self.defaults.report_usage("on_toggle_grid()")
  3753. self.ui.grid_snap_btn.trigger()
  3754. self.on_grid_snap_triggered(state=True)
  3755. def on_toggle_grid_lines(self):
  3756. self.defaults.report_usage("on_toggle_grd_lines()")
  3757. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3758. if tt_settings.contains("theme"):
  3759. theme = tt_settings.value('theme', type=str)
  3760. else:
  3761. theme = 'white'
  3762. if self.toggle_grid_lines is False:
  3763. if self.is_legacy is False:
  3764. if theme == 'white':
  3765. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3766. else:
  3767. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3768. else:
  3769. self.plotcanvas.axes.grid(True)
  3770. try:
  3771. self.plotcanvas.canvas.draw()
  3772. except IndexError:
  3773. pass
  3774. pass
  3775. self.toggle_grid_lines = True
  3776. else:
  3777. if self.is_legacy is False:
  3778. if theme == 'white':
  3779. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3780. else:
  3781. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3782. else:
  3783. self.plotcanvas.axes.grid(False)
  3784. try:
  3785. self.plotcanvas.canvas.draw()
  3786. except IndexError:
  3787. pass
  3788. self.toggle_grid_lines = False
  3789. if self.is_legacy is False:
  3790. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3791. # - perhaps is a bug in VisPy implementation
  3792. if self.grid_status() is True:
  3793. self.app_cursor.enabled = False
  3794. self.app_cursor.enabled = True
  3795. else:
  3796. self.app_cursor.enabled = True
  3797. self.app_cursor.enabled = False
  3798. def on_update_exc_export(self, state):
  3799. """
  3800. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3801. if the update_excellon_cb checkbox is checked
  3802. :param state: state of the checkbox whose signals is tied to his slot
  3803. :return:
  3804. """
  3805. if state:
  3806. # first try to disconnect
  3807. try:
  3808. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3809. disconnect(self.on_excellon_format_changed)
  3810. except TypeError:
  3811. pass
  3812. try:
  3813. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3814. disconnect(self.on_excellon_format_changed)
  3815. except TypeError:
  3816. pass
  3817. try:
  3818. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3819. disconnect(self.on_excellon_format_changed)
  3820. except TypeError:
  3821. pass
  3822. try:
  3823. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3824. disconnect(self.on_excellon_format_changed)
  3825. except TypeError:
  3826. pass
  3827. try:
  3828. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3829. disconnect(self.on_excellon_zeros_changed)
  3830. except TypeError:
  3831. pass
  3832. try:
  3833. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3834. disconnect(self.on_excellon_zeros_changed)
  3835. except TypeError:
  3836. pass
  3837. # the connect them
  3838. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3839. self.on_excellon_format_changed)
  3840. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3841. self.on_excellon_format_changed)
  3842. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3843. self.on_excellon_format_changed)
  3844. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3845. self.on_excellon_format_changed)
  3846. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3847. self.on_excellon_zeros_changed)
  3848. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3849. self.on_excellon_units_changed)
  3850. else:
  3851. # disconnect the signals
  3852. try:
  3853. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3854. disconnect(self.on_excellon_format_changed)
  3855. except TypeError:
  3856. pass
  3857. try:
  3858. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3859. disconnect(self.on_excellon_format_changed)
  3860. except TypeError:
  3861. pass
  3862. try:
  3863. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3864. disconnect(self.on_excellon_format_changed)
  3865. except TypeError:
  3866. pass
  3867. try:
  3868. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3869. disconnect(self.on_excellon_format_changed)
  3870. except TypeError:
  3871. pass
  3872. try:
  3873. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3874. disconnect(self.on_excellon_zeros_changed)
  3875. except TypeError:
  3876. pass
  3877. try:
  3878. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3879. disconnect(self.on_excellon_zeros_changed)
  3880. except TypeError:
  3881. pass
  3882. def on_excellon_format_changed(self):
  3883. """
  3884. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3885. :return: None
  3886. """
  3887. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3888. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3889. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3890. )
  3891. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3892. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3893. )
  3894. else:
  3895. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3896. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3897. )
  3898. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3899. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3900. )
  3901. def on_excellon_zeros_changed(self):
  3902. """
  3903. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3904. :return: None
  3905. """
  3906. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3907. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3908. )
  3909. def on_excellon_units_changed(self):
  3910. """
  3911. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3912. :return: None
  3913. """
  3914. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3915. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3916. )
  3917. self.on_excellon_format_changed()
  3918. def on_film_color_entry(self):
  3919. self.defaults['tools_film_color'] = \
  3920. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3921. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3922. "background-color:%s;"
  3923. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3924. )
  3925. def on_film_color_button(self):
  3926. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3927. c_dialog = QtWidgets.QColorDialog()
  3928. film_color = c_dialog.getColor(initial=current_color)
  3929. if film_color.isValid() is False:
  3930. return
  3931. # if new color is different then mark that the Preferences are changed
  3932. if film_color != current_color:
  3933. self.preferencesUiManager.on_preferences_edited()
  3934. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3935. "background-color:%s;"
  3936. "border-color: dimgray" % str(film_color.name())
  3937. )
  3938. new_val_sel = str(film_color.name())
  3939. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3940. self.defaults['tools_film_color'] = new_val_sel
  3941. def on_qrcode_fill_color_entry(self):
  3942. self.defaults['tools_qrcode_fill_color'] = \
  3943. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3944. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3945. "background-color:%s;"
  3946. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3947. )
  3948. def on_qrcode_fill_color_button(self):
  3949. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3950. c_dialog = QtWidgets.QColorDialog()
  3951. fill_color = c_dialog.getColor(initial=current_color)
  3952. if fill_color.isValid() is False:
  3953. return
  3954. # if new color is different then mark that the Preferences are changed
  3955. if fill_color != current_color:
  3956. self.preferencesUiManager.on_preferences_edited()
  3957. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3958. "background-color:%s;"
  3959. "border-color: dimgray" % str(fill_color.name())
  3960. )
  3961. new_val_sel = str(fill_color.name())
  3962. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3963. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3964. def on_qrcode_back_color_entry(self):
  3965. self.defaults['tools_qrcode_back_color'] = \
  3966. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3967. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3968. "background-color:%s;"
  3969. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3970. )
  3971. def on_qrcode_back_color_button(self):
  3972. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3973. c_dialog = QtWidgets.QColorDialog()
  3974. back_color = c_dialog.getColor(initial=current_color)
  3975. if back_color.isValid() is False:
  3976. return
  3977. # if new color is different then mark that the Preferences are changed
  3978. if back_color != current_color:
  3979. self.preferencesUiManager.on_preferences_edited()
  3980. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3981. "background-color:%s;"
  3982. "border-color: dimgray" % str(back_color.name())
  3983. )
  3984. new_val_sel = str(back_color.name())
  3985. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3986. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3987. def on_tab_rmb_click(self, checked):
  3988. self.ui.notebook.set_detachable(val=checked)
  3989. self.defaults["global_tabs_detachable"] = checked
  3990. self.ui.plot_tab_area.set_detachable(val=checked)
  3991. self.defaults["global_tabs_detachable"] = checked
  3992. def on_tab_setup_context_menu(self):
  3993. initial_checked = self.defaults["global_tabs_detachable"]
  3994. action_name = str(_("Detachable Tabs"))
  3995. action = QtWidgets.QAction(self)
  3996. action.setCheckable(True)
  3997. action.setText(action_name)
  3998. action.setChecked(initial_checked)
  3999. self.ui.notebook.tabBar.addAction(action)
  4000. self.ui.plot_tab_area.tabBar.addAction(action)
  4001. try:
  4002. action.triggered.disconnect()
  4003. except TypeError:
  4004. pass
  4005. action.triggered.connect(self.on_tab_rmb_click)
  4006. def on_deselect_all(self):
  4007. self.collection.set_all_inactive()
  4008. self.delete_selection_shape()
  4009. def on_workspace_modified(self):
  4010. # self.save_defaults(silent=True)
  4011. if self.is_legacy is True:
  4012. self.plotcanvas.delete_workspace()
  4013. self.preferencesUiManager.defaults_read_form()
  4014. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4015. def on_workspace(self):
  4016. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4017. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4018. else:
  4019. self.plotcanvas.delete_workspace()
  4020. self.preferencesUiManager.defaults_read_form()
  4021. # self.save_defaults(silent=True)
  4022. def on_workspace_toggle(self):
  4023. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4024. try:
  4025. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4026. except TypeError:
  4027. pass
  4028. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4029. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4030. self.on_workspace()
  4031. def on_cursor_type(self, val):
  4032. """
  4033. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4034. :return: None
  4035. """
  4036. self.app_cursor.enabled = False
  4037. if val == 'small':
  4038. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4039. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4040. self.app_cursor = self.plotcanvas.new_cursor()
  4041. else:
  4042. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4043. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4044. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4045. if self.ui.grid_snap_btn.isChecked():
  4046. self.app_cursor.enabled = True
  4047. else:
  4048. self.app_cursor.enabled = False
  4049. def on_tool_add_keypress(self):
  4050. # ## Current application units in Upper Case
  4051. self.units = self.defaults['units'].upper()
  4052. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4053. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4054. if notebook_widget_name == 'selected_tab':
  4055. if self.collection.get_active().kind == 'geometry':
  4056. # Tool add works for Geometry only if Advanced is True in Preferences
  4057. if self.defaults["global_app_level"] == 'a':
  4058. tool_add_popup = FCInputDialog(title="New Tool ...",
  4059. text='Enter a Tool Diameter:',
  4060. min=0.0000, max=99.9999, decimals=4)
  4061. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4062. val, ok = tool_add_popup.get_value()
  4063. if ok:
  4064. if float(val) == 0:
  4065. self.inform.emit('[WARNING_NOTCL] %s' %
  4066. _("Please enter a tool diameter with non-zero value, in Float format."))
  4067. return
  4068. self.collection.get_active().on_tool_add(dia=float(val))
  4069. else:
  4070. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4071. else:
  4072. msgbox = QtWidgets.QMessageBox()
  4073. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4074. "Go to Preferences -> General - Show Advanced Options."))
  4075. msgbox.setWindowTitle("Tool adding ...")
  4076. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4077. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4078. msgbox.setDefaultButton(bt_ok)
  4079. msgbox.exec_()
  4080. # work only if the notebook tab on focus is the Tools_Tab
  4081. if notebook_widget_name == 'tool_tab':
  4082. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4083. # and only if the tool is NCC Tool
  4084. if tool_widget == self.ncclear_tool.toolName:
  4085. self.ncclear_tool.on_add_tool_by_key()
  4086. # and only if the tool is Paint Area Tool
  4087. elif tool_widget == self.paint_tool.toolName:
  4088. self.paint_tool.on_add_tool_by_key()
  4089. # and only if the tool is Solder Paste Dispensing Tool
  4090. elif tool_widget == self.paste_tool.toolName:
  4091. self.paste_tool.on_add_tool_by_key()
  4092. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4093. # See description bellow.
  4094. def on_delete_keypress(self):
  4095. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4096. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4097. if notebook_widget_name == 'selected_tab':
  4098. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4099. self.collection.get_active().on_tool_delete()
  4100. # work only if the notebook tab on focus is the Tools_Tab
  4101. elif notebook_widget_name == 'tool_tab':
  4102. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4103. # and only if the tool is NCC Tool
  4104. if tool_widget == self.ncclear_tool.toolName:
  4105. self.ncclear_tool.on_tool_delete()
  4106. # and only if the tool is Paint Tool
  4107. elif tool_widget == self.paint_tool.toolName:
  4108. self.paint_tool.on_tool_delete()
  4109. # and only if the tool is Solder Paste Dispensing Tool
  4110. elif tool_widget == self.paste_tool.toolName:
  4111. self.paste_tool.on_tool_delete()
  4112. else:
  4113. self.on_delete()
  4114. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4115. # some screens you have to be careful where you hover with your mouse.
  4116. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4117. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4118. # Complicated, I know :)
  4119. def on_delete(self, force_deletion=False):
  4120. """
  4121. Delete the currently selected FlatCAMObjs.
  4122. :param force_deletion: used by Tcl command
  4123. :return: None
  4124. """
  4125. self.defaults.report_usage("on_delete()")
  4126. response = None
  4127. bt_ok = None
  4128. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4129. # a geometry object before we update it.
  4130. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4131. and self.grb_editor.editor_active is False:
  4132. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4133. msgbox = QtWidgets.QMessageBox()
  4134. msgbox.setWindowTitle(_("Delete objects"))
  4135. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4136. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4137. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4138. "the selected objects?"))
  4139. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4140. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4141. msgbox.setDefaultButton(bt_ok)
  4142. msgbox.exec_()
  4143. response = msgbox.clickedButton()
  4144. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4145. response = bt_ok
  4146. if response == bt_ok:
  4147. if self.collection.get_active():
  4148. self.log.debug("App.on_delete()")
  4149. for obj_active in self.collection.get_selected():
  4150. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4151. if isinstance(obj_active, GerberObject):
  4152. for el in obj_active.mark_shapes:
  4153. obj_active.mark_shapes[el].clear(update=True)
  4154. obj_active.mark_shapes[el].enabled = False
  4155. # obj_active.mark_shapes[el] = None
  4156. del el
  4157. elif isinstance(obj_active, CNCJobObject):
  4158. try:
  4159. obj_active.text_col.enabled = False
  4160. del obj_active.text_col
  4161. obj_active.annotation.clear(update=True)
  4162. del obj_active.annotation
  4163. except AttributeError as e:
  4164. log.debug(
  4165. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4166. )
  4167. while self.collection.get_selected():
  4168. self.delete_first_selected()
  4169. self.inform.emit('%s...' % _("Object(s) deleted"))
  4170. # make sure that the selection shape is deleted, too
  4171. self.delete_selection_shape()
  4172. else:
  4173. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4174. else:
  4175. self.inform.emit(_("Save the work in Editor and try again ..."))
  4176. def delete_first_selected(self):
  4177. # Keep this for later
  4178. try:
  4179. sel_obj = self.collection.get_active()
  4180. name = sel_obj.options["name"]
  4181. isPlotted = sel_obj.options["plot"]
  4182. except AttributeError:
  4183. self.log.debug("Nothing selected for deletion")
  4184. return
  4185. if self.is_legacy is True:
  4186. # Remove plot only if the object was plotted otherwise delaxes will fail
  4187. if isPlotted:
  4188. try:
  4189. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4190. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4191. except Exception as e:
  4192. log.debug("App.delete_first_selected() --> %s" % str(e))
  4193. self.plotcanvas.auto_adjust_axes()
  4194. # Remove from dictionary
  4195. self.collection.delete_active()
  4196. # Clear form
  4197. self.setup_component_editor()
  4198. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4199. def on_set_origin(self):
  4200. """
  4201. Set the origin to the left mouse click position
  4202. :return: None
  4203. """
  4204. # display the message for the user
  4205. # and ask him to click on the desired position
  4206. self.defaults.report_usage("on_set_origin()")
  4207. def origin_replot():
  4208. def worker_task():
  4209. with self.proc_container.new('%s...' % _("Plotting")):
  4210. for obj in self.collection.get_list():
  4211. obj.plot()
  4212. self.plotcanvas.fit_view()
  4213. if self.is_legacy:
  4214. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4215. else:
  4216. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4217. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4218. self.inform.emit(_('Click to set the origin ...'))
  4219. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4220. # first disconnect it as it may have been used by something else
  4221. try:
  4222. self.replot_signal.disconnect()
  4223. except TypeError:
  4224. pass
  4225. self.replot_signal[list].connect(origin_replot)
  4226. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4227. """
  4228. :param event:
  4229. :param location:
  4230. :param noplot:
  4231. :param use_thread:
  4232. :return:
  4233. """
  4234. noplot_sig = noplot
  4235. def worker_task():
  4236. with self.proc_container.new(_("Setting Origin...")):
  4237. obj_list = self.collection.get_list()
  4238. for obj in obj_list:
  4239. obj.offset((x, y))
  4240. self.object_changed.emit(obj)
  4241. # Update the object bounding box options
  4242. a, b, c, d = obj.bounds()
  4243. obj.options['xmin'] = a
  4244. obj.options['ymin'] = b
  4245. obj.options['xmax'] = c
  4246. obj.options['ymax'] = d
  4247. self.inform.emit('[success] %s...' % _('Origin set'))
  4248. for obj in obj_list:
  4249. out_name = obj.options["name"]
  4250. if obj.kind == 'gerber':
  4251. obj.source_file = self.export_gerber(
  4252. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4253. elif obj.kind == 'excellon':
  4254. obj.source_file = self.export_excellon(
  4255. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4256. if noplot_sig is False:
  4257. self.replot_signal.emit([])
  4258. if location is not None:
  4259. if len(location) != 2:
  4260. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4261. return 'fail'
  4262. x, y = location
  4263. if use_thread is True:
  4264. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4265. else:
  4266. worker_task()
  4267. self.should_we_save = True
  4268. return
  4269. if event.button == 1:
  4270. if self.is_legacy is False:
  4271. event_pos = event.pos
  4272. else:
  4273. event_pos = (event.xdata, event.ydata)
  4274. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4275. if self.grid_status():
  4276. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4277. else:
  4278. pos = pos_canvas
  4279. x = 0 - pos[0]
  4280. y = 0 - pos[1]
  4281. if use_thread is True:
  4282. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4283. else:
  4284. worker_task()
  4285. self.should_we_save = True
  4286. def on_move2origin(self, use_thread=True):
  4287. """
  4288. Move selected objects to origin.
  4289. :param use_thread: Control if to use threaded operation. Boolean.
  4290. :return:
  4291. """
  4292. def worker_task():
  4293. with self.proc_container.new(_("Moving to Origin...")):
  4294. obj_list = self.collection.get_selected()
  4295. if not obj_list:
  4296. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4297. return
  4298. xminlist = []
  4299. yminlist = []
  4300. # first get a bounding box to fit all
  4301. for obj in obj_list:
  4302. xmin, ymin, xmax, ymax = obj.bounds()
  4303. xminlist.append(xmin)
  4304. yminlist.append(ymin)
  4305. # get the minimum x,y for all objects selected
  4306. x = min(xminlist)
  4307. y = min(yminlist)
  4308. for obj in obj_list:
  4309. obj.offset((-x, -y))
  4310. self.object_changed.emit(obj)
  4311. # Update the object bounding box options
  4312. a, b, c, d = obj.bounds()
  4313. obj.options['xmin'] = a
  4314. obj.options['ymin'] = b
  4315. obj.options['xmax'] = c
  4316. obj.options['ymax'] = d
  4317. for obj in obj_list:
  4318. obj.plot()
  4319. for obj in obj_list:
  4320. out_name = obj.options["name"]
  4321. if obj.kind == 'gerber':
  4322. obj.source_file = self.export_gerber(
  4323. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4324. elif obj.kind == 'excellon':
  4325. obj.source_file = self.export_excellon(
  4326. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4327. self.inform.emit('[success] %s...' % _('Origin set'))
  4328. if use_thread is True:
  4329. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4330. else:
  4331. worker_task()
  4332. self.should_we_save = True
  4333. def on_jump_to(self, custom_location=None, fit_center=True):
  4334. """
  4335. Jump to a location by setting the mouse cursor location.
  4336. :param custom_location: Jump to a specified point. (x, y) tuple.
  4337. :param fit_center: If to fit view. Boolean.
  4338. :return:
  4339. """
  4340. self.defaults.report_usage("on_jump_to()")
  4341. if not custom_location:
  4342. dia_box_location = None
  4343. try:
  4344. dia_box_location = eval(self.clipboard.text())
  4345. except Exception:
  4346. pass
  4347. if type(dia_box_location) == tuple:
  4348. dia_box_location = str(dia_box_location)
  4349. else:
  4350. dia_box_location = None
  4351. # dia_box = Dialog_box(title=_("Jump to ..."),
  4352. # label=_("Enter the coordinates in format X,Y:"),
  4353. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4354. # initial_text=dia_box_location)
  4355. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4356. label=_("Enter the coordinates in format X,Y:"),
  4357. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4358. initial_text=dia_box_location,
  4359. reference=self.defaults['global_jump_ref'])
  4360. if dia_box.ok is True:
  4361. try:
  4362. location = eval(dia_box.location)
  4363. if not isinstance(location, tuple):
  4364. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4365. return
  4366. if dia_box.reference == 'rel':
  4367. rel_x = self.mouse[0] + location[0]
  4368. rel_y = self.mouse[1] + location[1]
  4369. location = (rel_x, rel_y)
  4370. self.defaults['global_jump_ref'] = dia_box.reference
  4371. except Exception:
  4372. return
  4373. else:
  4374. return
  4375. else:
  4376. location = custom_location
  4377. self.jump_signal.emit(location)
  4378. if fit_center:
  4379. self.plotcanvas.fit_center(loc=location)
  4380. cursor = QtGui.QCursor()
  4381. if self.is_legacy is False:
  4382. # I don't know where those differences come from but they are constant for the current
  4383. # execution of the application and they are multiples of a value around 0.0263mm.
  4384. # In a random way sometimes they are more sometimes they are less
  4385. # if units == 'MM':
  4386. # cal_factor = 0.0263
  4387. # else:
  4388. # cal_factor = 0.0263 / 25.4
  4389. cal_location = (location[0], location[1])
  4390. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4391. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4392. j_pos = (
  4393. int(canvas_origin.x() + round(jump_loc[0])),
  4394. int(canvas_origin.y() + round(jump_loc[1]))
  4395. )
  4396. cursor.setPos(j_pos[0], j_pos[1])
  4397. else:
  4398. # find the canvas origin which is in the top left corner
  4399. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4400. # determine the coordinates for the lowest left point of the canvas
  4401. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4402. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4403. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4404. # canvas) and the point (width, height) is in the top-right location
  4405. loc = self.plotcanvas.axes.transData.transform_point(location)
  4406. j_pos = (
  4407. int(x0 + loc[0]),
  4408. int(y0 - loc[1])
  4409. )
  4410. cursor.setPos(j_pos[0], j_pos[1])
  4411. self.plotcanvas.mouse = [location[0], location[1]]
  4412. if self.defaults["global_cursor_color_enabled"] is True:
  4413. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4414. else:
  4415. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4416. if self.grid_status():
  4417. # Update cursor
  4418. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4419. symbol='++', edge_color=self.cursor_color_3D,
  4420. edge_width=self.defaults["global_cursor_width"],
  4421. size=self.defaults["global_cursor_size"])
  4422. # Set the position label
  4423. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4424. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4425. # Set the relative position label
  4426. dx = location[0] - float(self.rel_point1[0])
  4427. dy = location[1] - float(self.rel_point1[1])
  4428. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4429. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4430. self.inform.emit('[success] %s' % _("Done."))
  4431. return location
  4432. def on_locate(self, obj, fit_center=True):
  4433. """
  4434. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4435. :param obj: The object on which to locate certain points
  4436. :param fit_center: If to fit view. Boolean.
  4437. :return: A point location. (x, y) tuple.
  4438. """
  4439. self.defaults.report_usage("on_locate()")
  4440. if obj is None:
  4441. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4442. return 'fail'
  4443. class DialogBoxChoice(QtWidgets.QDialog):
  4444. def __init__(self, title=None, icon=None, choice='bl'):
  4445. """
  4446. :param title: string with the window title
  4447. """
  4448. super(DialogBoxChoice, self).__init__()
  4449. self.ok = False
  4450. self.setWindowIcon(icon)
  4451. self.setWindowTitle(str(title))
  4452. self.form = QtWidgets.QFormLayout(self)
  4453. self.ref_radio = RadioSet([
  4454. {"label": _("Bottom-Left"), "value": "bl"},
  4455. {"label": _("Top-Left"), "value": "tl"},
  4456. {"label": _("Bottom-Right"), "value": "br"},
  4457. {"label": _("Top-Right"), "value": "tr"},
  4458. {"label": _("Center"), "value": "c"}
  4459. ], orientation='vertical', stretch=False)
  4460. self.ref_radio.set_value(choice)
  4461. self.form.addRow(self.ref_radio)
  4462. self.button_box = QtWidgets.QDialogButtonBox(
  4463. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4464. Qt.Horizontal, parent=self)
  4465. self.form.addRow(self.button_box)
  4466. self.button_box.accepted.connect(self.accept)
  4467. self.button_box.rejected.connect(self.reject)
  4468. if self.exec_() == QtWidgets.QDialog.Accepted:
  4469. self.ok = True
  4470. self.location_point = self.ref_radio.get_value()
  4471. else:
  4472. self.ok = False
  4473. self.location_point = None
  4474. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4475. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4476. choice=self.defaults['global_locate_pt'])
  4477. if dia_box.ok is True:
  4478. try:
  4479. location_point = dia_box.location_point
  4480. self.defaults['global_locate_pt'] = dia_box.location_point
  4481. except Exception:
  4482. return
  4483. else:
  4484. return
  4485. loc_b = obj.bounds()
  4486. if location_point == 'bl':
  4487. location = (loc_b[0], loc_b[1])
  4488. elif location_point == 'tl':
  4489. location = (loc_b[0], loc_b[3])
  4490. elif location_point == 'br':
  4491. location = (loc_b[2], loc_b[1])
  4492. elif location_point == 'tr':
  4493. location = (loc_b[2], loc_b[3])
  4494. else:
  4495. # center
  4496. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4497. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4498. location = (cx, cy)
  4499. self.locate_signal.emit(location, location_point)
  4500. if fit_center:
  4501. self.plotcanvas.fit_center(loc=location)
  4502. cursor = QtGui.QCursor()
  4503. if self.is_legacy is False:
  4504. # I don't know where those differences come from but they are constant for the current
  4505. # execution of the application and they are multiples of a value around 0.0263mm.
  4506. # In a random way sometimes they are more sometimes they are less
  4507. # if units == 'MM':
  4508. # cal_factor = 0.0263
  4509. # else:
  4510. # cal_factor = 0.0263 / 25.4
  4511. cal_location = (location[0], location[1])
  4512. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4513. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4514. j_pos = (
  4515. int(canvas_origin.x() + round(jump_loc[0])),
  4516. int(canvas_origin.y() + round(jump_loc[1]))
  4517. )
  4518. cursor.setPos(j_pos[0], j_pos[1])
  4519. else:
  4520. # find the canvas origin which is in the top left corner
  4521. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4522. # determine the coordinates for the lowest left point of the canvas
  4523. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4524. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4525. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4526. # canvas) and the point (width, height) is in the top-right location
  4527. loc = self.plotcanvas.axes.transData.transform_point(location)
  4528. j_pos = (
  4529. int(x0 + loc[0]),
  4530. int(y0 - loc[1])
  4531. )
  4532. cursor.setPos(j_pos[0], j_pos[1])
  4533. self.plotcanvas.mouse = [location[0], location[1]]
  4534. if self.defaults["global_cursor_color_enabled"] is True:
  4535. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4536. else:
  4537. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4538. if self.grid_status():
  4539. # Update cursor
  4540. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4541. symbol='++', edge_color=self.cursor_color_3D,
  4542. edge_width=self.defaults["global_cursor_width"],
  4543. size=self.defaults["global_cursor_size"])
  4544. # Set the position label
  4545. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4546. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4547. # Set the relative position label
  4548. self.dx = location[0] - float(self.rel_point1[0])
  4549. self.dy = location[1] - float(self.rel_point1[1])
  4550. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4551. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4552. self.inform.emit('[success] %s' % _("Done."))
  4553. return location
  4554. def on_copy_command(self):
  4555. """
  4556. Will copy a selection of objects, creating new objects.
  4557. :return:
  4558. """
  4559. self.defaults.report_usage("on_copy_command()")
  4560. def initialize(obj_init, app):
  4561. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4562. try:
  4563. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4564. except AttributeError:
  4565. pass
  4566. try:
  4567. obj_init.apertures = deepcopy(obj.apertures)
  4568. except AttributeError:
  4569. pass
  4570. try:
  4571. if obj.tools:
  4572. obj_init.tools = deepcopy(obj.tools)
  4573. except Exception as err:
  4574. log.debug("App.on_copy_command() --> %s" % str(err))
  4575. try:
  4576. obj_init.source_file = deepcopy(obj.source_file)
  4577. except (AttributeError, TypeError):
  4578. pass
  4579. def initialize_excellon(obj_init, app):
  4580. obj_init.source_file = deepcopy(obj.source_file)
  4581. obj_init.tools = deepcopy(obj.tools)
  4582. # drills are offset, so they need to be deep copied
  4583. obj_init.drills = deepcopy(obj.drills)
  4584. # slots are offset, so they need to be deep copied
  4585. obj_init.slots = deepcopy(obj.slots)
  4586. obj_init.create_geometry()
  4587. def initialize_script(obj_init, app_obj):
  4588. obj_init.source_file = deepcopy(obj.source_file)
  4589. def initialize_document(obj_init, app_obj):
  4590. obj_init.source_file = deepcopy(obj.source_file)
  4591. for obj in self.collection.get_selected():
  4592. obj_name = obj.options["name"]
  4593. try:
  4594. if isinstance(obj, ExcellonObject):
  4595. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4596. elif isinstance(obj, GerberObject):
  4597. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4598. elif isinstance(obj, GeometryObject):
  4599. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4600. elif isinstance(obj, ScriptObject):
  4601. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4602. elif isinstance(obj, DocumentObject):
  4603. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4604. except Exception as e:
  4605. return "Operation failed: %s" % str(e)
  4606. def on_copy_object2(self, custom_name):
  4607. def initialize_geometry(obj_init, app):
  4608. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4609. try:
  4610. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4611. except AttributeError:
  4612. pass
  4613. try:
  4614. obj_init.apertures = deepcopy(obj.apertures)
  4615. except AttributeError:
  4616. pass
  4617. try:
  4618. if obj.tools:
  4619. obj_init.tools = deepcopy(obj.tools)
  4620. except Exception as ee:
  4621. log.debug("on_copy_object2() --> %s" % str(ee))
  4622. def initialize_gerber(obj_init, app):
  4623. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4624. obj_init.apertures = deepcopy(obj.apertures)
  4625. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4626. def initialize_excellon(obj_init, app):
  4627. obj_init.tools = deepcopy(obj.tools)
  4628. # drills are offset, so they need to be deep copied
  4629. obj_init.drills = deepcopy(obj.drills)
  4630. # slots are offset, so they need to be deep copied
  4631. obj_init.slots = deepcopy(obj.slots)
  4632. obj_init.create_geometry()
  4633. for obj in self.collection.get_selected():
  4634. obj_name = obj.options["name"]
  4635. try:
  4636. if isinstance(obj, ExcellonObject):
  4637. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4638. elif isinstance(obj, GerberObject):
  4639. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4640. elif isinstance(obj, GeometryObject):
  4641. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4642. except Exception as er:
  4643. return "Operation failed: %s" % str(er)
  4644. def on_rename_object(self, text):
  4645. """
  4646. Will rename an object.
  4647. :param text: New name for the object.
  4648. :return:
  4649. """
  4650. self.defaults.report_usage("on_rename_object()")
  4651. named_obj = self.collection.get_active()
  4652. for obj in named_obj:
  4653. if obj is list:
  4654. self.on_rename_object(text)
  4655. else:
  4656. try:
  4657. obj.options['name'] = text
  4658. except Exception as e:
  4659. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4660. def convert_any2geo(self):
  4661. """
  4662. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4663. :return:
  4664. """
  4665. self.defaults.report_usage("convert_any2geo()")
  4666. def initialize(obj_init, app):
  4667. obj_init.solid_geometry = obj.solid_geometry
  4668. try:
  4669. obj_init.follow_geometry = obj.follow_geometry
  4670. except AttributeError:
  4671. pass
  4672. try:
  4673. obj_init.apertures = obj.apertures
  4674. except AttributeError:
  4675. pass
  4676. try:
  4677. if obj.tools:
  4678. obj_init.tools = obj.tools
  4679. except AttributeError:
  4680. pass
  4681. def initialize_excellon(obj_init, app):
  4682. # objs = self.collection.get_selected()
  4683. # GeometryObject.merge(objs, obj)
  4684. solid_geo = []
  4685. for tool in obj.tools:
  4686. for geo in obj.tools[tool]['solid_geometry']:
  4687. solid_geo.append(geo)
  4688. obj_init.solid_geometry = deepcopy(solid_geo)
  4689. if not self.collection.get_selected():
  4690. log.warning("App.convert_any2geo --> No object selected")
  4691. self.inform.emit('[WARNING_NOTCL] %s' %
  4692. _("No object is selected. Select an object and try again."))
  4693. return
  4694. for obj in self.collection.get_selected():
  4695. obj_name = obj.options["name"]
  4696. try:
  4697. if isinstance(obj, ExcellonObject):
  4698. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4699. else:
  4700. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4701. except Exception as e:
  4702. return "Operation failed: %s" % str(e)
  4703. def convert_any2gerber(self):
  4704. """
  4705. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4706. :return:
  4707. """
  4708. self.defaults.report_usage("convert_any2gerber()")
  4709. def initialize_geometry(obj_init, app):
  4710. apertures = {}
  4711. apid = 0
  4712. apertures[str(apid)] = {}
  4713. apertures[str(apid)]['geometry'] = []
  4714. for obj_orig in obj.solid_geometry:
  4715. new_elem = {}
  4716. new_elem['solid'] = obj_orig
  4717. try:
  4718. new_elem['follow'] = obj_orig.exterior
  4719. except AttributeError:
  4720. pass
  4721. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4722. apertures[str(apid)]['size'] = 0.0
  4723. apertures[str(apid)]['type'] = 'C'
  4724. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4725. obj_init.apertures = deepcopy(apertures)
  4726. def initialize_excellon(obj_init, app):
  4727. apertures = {}
  4728. apid = 10
  4729. for tool in obj.tools:
  4730. apertures[str(apid)] = {}
  4731. apertures[str(apid)]['geometry'] = []
  4732. for geo in obj.tools[tool]['solid_geometry']:
  4733. new_el = {}
  4734. new_el['solid'] = geo
  4735. new_el['follow'] = geo.exterior
  4736. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4737. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4738. apertures[str(apid)]['type'] = 'C'
  4739. apid += 1
  4740. # create solid_geometry
  4741. solid_geometry = []
  4742. for apid in apertures:
  4743. for geo_el in apertures[apid]['geometry']:
  4744. solid_geometry.append(geo_el['solid'])
  4745. solid_geometry = MultiPolygon(solid_geometry)
  4746. solid_geometry = solid_geometry.buffer(0.0000001)
  4747. obj_init.solid_geometry = deepcopy(solid_geometry)
  4748. obj_init.apertures = deepcopy(apertures)
  4749. # clear the working objects (perhaps not necessary due of Python GC)
  4750. apertures.clear()
  4751. if not self.collection.get_selected():
  4752. log.warning("App.convert_any2gerber --> No object selected")
  4753. self.inform.emit('[WARNING_NOTCL] %s' %
  4754. _("No object is selected. Select an object and try again."))
  4755. return
  4756. for obj in self.collection.get_selected():
  4757. obj_name = obj.options["name"]
  4758. try:
  4759. if isinstance(obj, ExcellonObject):
  4760. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4761. elif isinstance(obj, GeometryObject):
  4762. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4763. else:
  4764. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4765. except Exception as e:
  4766. return "Operation failed: %s" % str(e)
  4767. def abort_all_tasks(self):
  4768. """
  4769. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4770. on the first possible occasion.
  4771. :return:
  4772. """
  4773. if self.abort_flag is False:
  4774. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4775. self.abort_flag = True
  4776. self.cleanup.emit()
  4777. def app_is_idle(self):
  4778. if self.abort_flag:
  4779. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4780. self.abort_flag = False
  4781. def on_selectall(self):
  4782. """
  4783. Will draw a selection box shape around the selected objects.
  4784. :return:
  4785. """
  4786. self.defaults.report_usage("on_selectall()")
  4787. # delete the possible selection box around a possible selected object
  4788. self.delete_selection_shape()
  4789. for name in self.collection.get_names():
  4790. self.collection.set_active(name)
  4791. curr_sel_obj = self.collection.get_by_name(name)
  4792. # create the selection box around the selected object
  4793. if self.defaults['global_selection_shape'] is True:
  4794. self.draw_selection_shape(curr_sel_obj)
  4795. def on_preferences(self):
  4796. """
  4797. Adds the Preferences in a Tab in Plot Area
  4798. :return:
  4799. """
  4800. # add the tab if it was closed
  4801. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4802. # delete the absolute and relative position and messages in the infobar
  4803. self.ui.position_label.setText("")
  4804. self.ui.rel_position_label.setText("")
  4805. # Switch plot_area to preferences page
  4806. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4807. # self.ui.show()
  4808. # detect changes in the preferences
  4809. for idx in range(self.ui.pref_tab_area.count()):
  4810. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4811. try:
  4812. try:
  4813. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4814. except (TypeError, AttributeError):
  4815. pass
  4816. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4817. except AttributeError:
  4818. pass
  4819. try:
  4820. try:
  4821. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4822. except (TypeError, AttributeError):
  4823. pass
  4824. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4825. except AttributeError:
  4826. pass
  4827. try:
  4828. try:
  4829. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4830. except (TypeError, AttributeError):
  4831. pass
  4832. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4833. except AttributeError:
  4834. pass
  4835. try:
  4836. try:
  4837. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4838. except (TypeError, AttributeError):
  4839. pass
  4840. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4841. except AttributeError:
  4842. pass
  4843. try:
  4844. try:
  4845. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4846. except (TypeError, AttributeError):
  4847. pass
  4848. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4849. except AttributeError:
  4850. pass
  4851. def on_tools_database(self, source='app'):
  4852. """
  4853. Adds the Tools Database in a Tab in Plot Area.
  4854. :return:
  4855. """
  4856. for idx in range(self.ui.plot_tab_area.count()):
  4857. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4858. # there can be only one instance of Tools Database at one time
  4859. return
  4860. if source == 'app':
  4861. self.tools_db_tab = ToolsDB2(
  4862. app=self,
  4863. parent=self.ui,
  4864. callback_on_edited=self.on_tools_db_edited,
  4865. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4866. )
  4867. elif source == 'ncc':
  4868. self.tools_db_tab = ToolsDB2(
  4869. app=self,
  4870. parent=self.ui,
  4871. callback_on_edited=self.on_tools_db_edited,
  4872. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4873. )
  4874. elif source == 'paint':
  4875. self.tools_db_tab = ToolsDB2(
  4876. app=self,
  4877. parent=self.ui,
  4878. callback_on_edited=self.on_tools_db_edited,
  4879. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4880. )
  4881. # add the tab if it was closed
  4882. try:
  4883. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4884. self.tools_db_tab.setObjectName("database_tab")
  4885. except Exception as e:
  4886. log.debug("App.on_tools_database() --> %s" % str(e))
  4887. return
  4888. # delete the absolute and relative position and messages in the infobar
  4889. self.ui.position_label.setText("")
  4890. self.ui.rel_position_label.setText("")
  4891. # Switch plot_area to preferences page
  4892. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4893. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4894. self.tools_db_tab.ui_connect()
  4895. def on_tools_db_edited(self):
  4896. """
  4897. Executed whenever a tool is edited in Tools Database.
  4898. Will color the text of the Tools Database tab to Red color.
  4899. :return:
  4900. """
  4901. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4902. for idx in range(self.ui.plot_tab_area.count()):
  4903. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4904. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4905. self.tools_db_changed_flag = True
  4906. def on_geometry_tool_add_from_db_executed(self, tool):
  4907. """
  4908. Here add the tool from DB in the selected geometry object.
  4909. :return:
  4910. """
  4911. tool_from_db = deepcopy(tool)
  4912. obj = self.collection.get_active()
  4913. if isinstance(obj, GeometryObject):
  4914. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4915. # close the tab and delete it
  4916. for idx in range(self.ui.plot_tab_area.count()):
  4917. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4918. wdg = self.ui.plot_tab_area.widget(idx)
  4919. wdg.deleteLater()
  4920. self.ui.plot_tab_area.removeTab(idx)
  4921. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4922. else:
  4923. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4924. def on_plot_area_tab_closed(self, tab_obj_name):
  4925. """
  4926. Executed whenever a QTab is closed in the Plot Area.
  4927. :param title: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4928. :return:
  4929. """
  4930. if tab_obj_name == "preferences_tab":
  4931. self.preferencesUiManager.on_close_preferences_tab()
  4932. elif tab_obj_name == "database_tab":
  4933. # disconnect the signals from the table widget in tab
  4934. self.tools_db_tab.ui_disconnect()
  4935. if self.tools_db_changed_flag is True:
  4936. msgbox = QtWidgets.QMessageBox()
  4937. msgbox.setText(_("One or more Tools are edited.\n"
  4938. "Do you want to update the Tools Database?"))
  4939. msgbox.setWindowTitle(_("Save Tools Database"))
  4940. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4941. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4942. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4943. msgbox.setDefaultButton(bt_yes)
  4944. msgbox.exec_()
  4945. response = msgbox.clickedButton()
  4946. if response == bt_yes:
  4947. self.tools_db_tab.on_save_tools_db()
  4948. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4949. else:
  4950. self.tools_db_changed_flag = False
  4951. self.inform.emit('')
  4952. return
  4953. self.tools_db_tab.deleteLater()
  4954. elif tab_obj_name == "text_editor_tab":
  4955. self.toggle_codeeditor = False
  4956. elif tab_obj_name == "bookmarks_tab":
  4957. self.book_dialog_tab.rebuild_actions()
  4958. self.book_dialog_tab.deleteLater()
  4959. else:
  4960. return
  4961. def on_plotarea_tab_closed(self, tab_idx):
  4962. """
  4963. :param tab_idx: Index of the Tab from the plotarea that was closed
  4964. :return:
  4965. """
  4966. widget = self.ui.plot_tab_area.widget(tab_idx)
  4967. if widget is not None:
  4968. widget.deleteLater()
  4969. self.ui.plot_tab_area.removeTab(tab_idx)
  4970. def on_flipy(self):
  4971. """
  4972. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4973. :return:
  4974. """
  4975. self.defaults.report_usage("on_flipy()")
  4976. obj_list = self.collection.get_selected()
  4977. xminlist = []
  4978. yminlist = []
  4979. xmaxlist = []
  4980. ymaxlist = []
  4981. if not obj_list:
  4982. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4983. else:
  4984. try:
  4985. # first get a bounding box to fit all
  4986. for obj in obj_list:
  4987. xmin, ymin, xmax, ymax = obj.bounds()
  4988. xminlist.append(xmin)
  4989. yminlist.append(ymin)
  4990. xmaxlist.append(xmax)
  4991. ymaxlist.append(ymax)
  4992. # get the minimum x,y and maximum x,y for all objects selected
  4993. xminimal = min(xminlist)
  4994. yminimal = min(yminlist)
  4995. xmaximal = max(xmaxlist)
  4996. ymaximal = max(ymaxlist)
  4997. px = 0.5 * (xminimal + xmaximal)
  4998. py = 0.5 * (yminimal + ymaximal)
  4999. # execute mirroring
  5000. for obj in obj_list:
  5001. obj.mirror('X', [px, py])
  5002. obj.plot()
  5003. self.object_changed.emit(obj)
  5004. self.inform.emit('[success] %s' %
  5005. _("Flip on Y axis done."))
  5006. except Exception as e:
  5007. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5008. return
  5009. def on_flipx(self):
  5010. """
  5011. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5012. :return:
  5013. """
  5014. self.defaults.report_usage("on_flipx()")
  5015. obj_list = self.collection.get_selected()
  5016. xminlist = []
  5017. yminlist = []
  5018. xmaxlist = []
  5019. ymaxlist = []
  5020. if not obj_list:
  5021. self.inform.emit('[WARNING_NOTCL] %s' %
  5022. _("No object selected to Flip on X axis."))
  5023. else:
  5024. try:
  5025. # first get a bounding box to fit all
  5026. for obj in obj_list:
  5027. xmin, ymin, xmax, ymax = obj.bounds()
  5028. xminlist.append(xmin)
  5029. yminlist.append(ymin)
  5030. xmaxlist.append(xmax)
  5031. ymaxlist.append(ymax)
  5032. # get the minimum x,y and maximum x,y for all objects selected
  5033. xminimal = min(xminlist)
  5034. yminimal = min(yminlist)
  5035. xmaximal = max(xmaxlist)
  5036. ymaximal = max(ymaxlist)
  5037. px = 0.5 * (xminimal + xmaximal)
  5038. py = 0.5 * (yminimal + ymaximal)
  5039. # execute mirroring
  5040. for obj in obj_list:
  5041. obj.mirror('Y', [px, py])
  5042. obj.plot()
  5043. self.object_changed.emit(obj)
  5044. self.inform.emit('[success] %s' %
  5045. _("Flip on X axis done."))
  5046. except Exception as e:
  5047. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5048. return
  5049. def on_rotate(self, silent=False, preset=None):
  5050. """
  5051. Executed when Options -> Rotate Selection menu entry is clicked.
  5052. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5053. :param preset: A value to be used as predefined angle for rotation.
  5054. :return:
  5055. """
  5056. self.defaults.report_usage("on_rotate()")
  5057. obj_list = self.collection.get_selected()
  5058. xminlist = []
  5059. yminlist = []
  5060. xmaxlist = []
  5061. ymaxlist = []
  5062. if not obj_list:
  5063. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5064. else:
  5065. if silent is False:
  5066. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5067. min=-360, max=360, decimals=4,
  5068. init_val=float(self.defaults['tools_transform_rotate']))
  5069. num, ok = rotatebox.get_value()
  5070. else:
  5071. num = preset
  5072. ok = True
  5073. if ok:
  5074. try:
  5075. # first get a bounding box to fit all
  5076. for obj in obj_list:
  5077. xmin, ymin, xmax, ymax = obj.bounds()
  5078. xminlist.append(xmin)
  5079. yminlist.append(ymin)
  5080. xmaxlist.append(xmax)
  5081. ymaxlist.append(ymax)
  5082. # get the minimum x,y and maximum x,y for all objects selected
  5083. xminimal = min(xminlist)
  5084. yminimal = min(yminlist)
  5085. xmaximal = max(xmaxlist)
  5086. ymaximal = max(ymaxlist)
  5087. px = 0.5 * (xminimal + xmaximal)
  5088. py = 0.5 * (yminimal + ymaximal)
  5089. for sel_obj in obj_list:
  5090. sel_obj.rotate(-float(num), point=(px, py))
  5091. sel_obj.plot()
  5092. self.object_changed.emit(sel_obj)
  5093. self.inform.emit('[success] %s' %
  5094. _("Rotation done."))
  5095. except Exception as e:
  5096. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5097. return
  5098. def on_skewx(self):
  5099. """
  5100. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5101. :return:
  5102. """
  5103. self.defaults.report_usage("on_skewx()")
  5104. obj_list = self.collection.get_selected()
  5105. xminlist = []
  5106. yminlist = []
  5107. if not obj_list:
  5108. self.inform.emit('[WARNING_NOTCL] %s' %
  5109. _("No object selected to Skew/Shear on X axis."))
  5110. else:
  5111. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5112. min=-360, max=360, decimals=4,
  5113. init_val=float(self.defaults['tools_transform_skew_x']))
  5114. num, ok = skewxbox.get_value()
  5115. if ok:
  5116. # first get a bounding box to fit all
  5117. for obj in obj_list:
  5118. xmin, ymin, xmax, ymax = obj.bounds()
  5119. xminlist.append(xmin)
  5120. yminlist.append(ymin)
  5121. # get the minimum x,y and maximum x,y for all objects selected
  5122. xminimal = min(xminlist)
  5123. yminimal = min(yminlist)
  5124. for obj in obj_list:
  5125. obj.skew(num, 0, point=(xminimal, yminimal))
  5126. obj.plot()
  5127. self.object_changed.emit(obj)
  5128. self.inform.emit('[success] %s' %
  5129. _("Skew on X axis done."))
  5130. def on_skewy(self):
  5131. """
  5132. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5133. :return:
  5134. """
  5135. self.defaults.report_usage("on_skewy()")
  5136. obj_list = self.collection.get_selected()
  5137. xminlist = []
  5138. yminlist = []
  5139. if not obj_list:
  5140. self.inform.emit('[WARNING_NOTCL] %s' %
  5141. _("No object selected to Skew/Shear on Y axis."))
  5142. else:
  5143. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5144. min=-360, max=360, decimals=4,
  5145. init_val=float(self.defaults['tools_transform_skew_y']))
  5146. num, ok = skewybox.get_value()
  5147. if ok:
  5148. # first get a bounding box to fit all
  5149. for obj in obj_list:
  5150. xmin, ymin, xmax, ymax = obj.bounds()
  5151. xminlist.append(xmin)
  5152. yminlist.append(ymin)
  5153. # get the minimum x,y and maximum x,y for all objects selected
  5154. xminimal = min(xminlist)
  5155. yminimal = min(yminlist)
  5156. for obj in obj_list:
  5157. obj.skew(0, num, point=(xminimal, yminimal))
  5158. obj.plot()
  5159. self.object_changed.emit(obj)
  5160. self.inform.emit('[success] %s' %
  5161. _("Skew on Y axis done."))
  5162. def on_plots_updated(self):
  5163. """
  5164. Callback used to report when the plots have changed.
  5165. Adjust axes and zooms to fit.
  5166. :return: None
  5167. """
  5168. if self.is_legacy is False:
  5169. self.plotcanvas.update()
  5170. else:
  5171. self.plotcanvas.auto_adjust_axes()
  5172. self.on_zoom_fit(None)
  5173. self.collection.update_view()
  5174. # self.inform.emit(_("Plots updated ..."))
  5175. def on_toolbar_replot(self):
  5176. """
  5177. Callback for toolbar button. Re-plots all objects.
  5178. :return: None
  5179. """
  5180. self.defaults.report_usage("on_toolbar_replot")
  5181. self.log.debug("on_toolbar_replot()")
  5182. try:
  5183. self.collection.get_active().read_form()
  5184. except AttributeError:
  5185. self.log.debug("on_toolbar_replot(): AttributeError")
  5186. pass
  5187. self.plot_all()
  5188. def on_row_activated(self, index):
  5189. if index.isValid():
  5190. if index.internalPointer().parent_item != self.collection.root_item:
  5191. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5192. self.collection.on_item_activated(index)
  5193. def on_row_selected(self, obj_name):
  5194. """
  5195. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5196. It mean we clicked outside of the items and deselected all
  5197. :param obj_name:
  5198. :return:
  5199. """
  5200. if obj_name == 'none':
  5201. for act in self.ui.menuobjects.actions():
  5202. act.setChecked(False)
  5203. return
  5204. # get the name of the selected objects and add them to a list
  5205. name_list = []
  5206. for obj in self.collection.get_selected():
  5207. name_list.append(obj.options['name'])
  5208. # set all actions as unchecked but the ones selected make them checked
  5209. for act in self.ui.menuobjects.actions():
  5210. act.setChecked(False)
  5211. if act.text() in name_list:
  5212. act.setChecked(True)
  5213. def on_collection_updated(self, obj, state, old_name):
  5214. """
  5215. Create a menu from the object loaded in the collection.
  5216. :param obj: object that was changed (added, deleted, renamed)
  5217. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5218. :param old_name: the old name of the object before the action that triggered this slot happened
  5219. :return: None
  5220. """
  5221. icon_files = {
  5222. "gerber": self.resource_location + "/flatcam_icon16.png",
  5223. "excellon": self.resource_location + "/drill16.png",
  5224. "cncjob": self.resource_location + "/cnc16.png",
  5225. "geometry": self.resource_location + "/geometry16.png",
  5226. "script": self.resource_location + "/script_new16.png",
  5227. "document": self.resource_location + "/notes16_1.png"
  5228. }
  5229. if state == 'append':
  5230. for act in self.ui.menuobjects.actions():
  5231. try:
  5232. act.triggered.disconnect()
  5233. except TypeError:
  5234. pass
  5235. self.ui.menuobjects.clear()
  5236. gerber_list = []
  5237. exc_list = []
  5238. cncjob_list = []
  5239. geo_list = []
  5240. script_list = []
  5241. doc_list = []
  5242. for name in self.collection.get_names():
  5243. obj_named = self.collection.get_by_name(name)
  5244. if obj_named.kind == 'gerber':
  5245. gerber_list.append(name)
  5246. elif obj_named.kind == 'excellon':
  5247. exc_list.append(name)
  5248. elif obj_named.kind == 'cncjob':
  5249. cncjob_list.append(name)
  5250. elif obj_named.kind == 'geometry':
  5251. geo_list.append(name)
  5252. elif obj_named.kind == 'script':
  5253. script_list.append(name)
  5254. elif obj_named.kind == 'document':
  5255. doc_list.append(name)
  5256. def add_act(o_name):
  5257. obj_for_icon = self.collection.get_by_name(o_name)
  5258. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5259. add_action.setCheckable(True)
  5260. add_action.setText(o_name)
  5261. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5262. add_action.triggered.connect(
  5263. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5264. self.collection.set_inactive(o_name))
  5265. self.ui.menuobjects.addAction(add_action)
  5266. for name in gerber_list:
  5267. add_act(name)
  5268. self.ui.menuobjects.addSeparator()
  5269. for name in exc_list:
  5270. add_act(name)
  5271. self.ui.menuobjects.addSeparator()
  5272. for name in cncjob_list:
  5273. add_act(name)
  5274. self.ui.menuobjects.addSeparator()
  5275. for name in geo_list:
  5276. add_act(name)
  5277. self.ui.menuobjects.addSeparator()
  5278. for name in script_list:
  5279. add_act(name)
  5280. self.ui.menuobjects.addSeparator()
  5281. for name in doc_list:
  5282. add_act(name)
  5283. self.ui.menuobjects.addSeparator()
  5284. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5285. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5286. _('Select All')
  5287. )
  5288. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5289. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5290. _('Deselect All')
  5291. )
  5292. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5293. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5294. elif state == 'delete':
  5295. for act in self.ui.menuobjects.actions():
  5296. if act.text() == obj.options['name']:
  5297. try:
  5298. act.triggered.disconnect()
  5299. except TypeError:
  5300. pass
  5301. self.ui.menuobjects.removeAction(act)
  5302. break
  5303. elif state == 'rename':
  5304. for act in self.ui.menuobjects.actions():
  5305. if act.text() == old_name:
  5306. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5307. add_action.setText(obj.options['name'])
  5308. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5309. add_action.triggered.connect(
  5310. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5311. self.collection.set_inactive(obj.options['name']))
  5312. self.ui.menuobjects.insertAction(act, add_action)
  5313. try:
  5314. act.triggered.disconnect()
  5315. except TypeError:
  5316. pass
  5317. self.ui.menuobjects.removeAction(act)
  5318. break
  5319. elif state == 'delete_all':
  5320. for act in self.ui.menuobjects.actions():
  5321. try:
  5322. act.triggered.disconnect()
  5323. except TypeError:
  5324. pass
  5325. self.ui.menuobjects.clear()
  5326. self.ui.menuobjects.addSeparator()
  5327. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5328. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5329. _('Select All')
  5330. )
  5331. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5332. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5333. _('Deselect All')
  5334. )
  5335. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5336. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5337. def on_objects_selection(self, on_off):
  5338. obj_list = self.collection.get_names()
  5339. if on_off is True:
  5340. self.collection.set_all_active()
  5341. for act in self.ui.menuobjects.actions():
  5342. try:
  5343. act.setChecked(True)
  5344. except Exception:
  5345. pass
  5346. if obj_list:
  5347. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5348. else:
  5349. self.collection.set_all_inactive()
  5350. for act in self.ui.menuobjects.actions():
  5351. try:
  5352. act.setChecked(False)
  5353. except Exception:
  5354. pass
  5355. if obj_list:
  5356. self.inform.emit('%s' % _("Objects selection is cleared."))
  5357. else:
  5358. self.inform.emit('')
  5359. def grid_status(self):
  5360. if self.ui.grid_snap_btn.isChecked():
  5361. return True
  5362. else:
  5363. return False
  5364. def populate_cmenu_grids(self):
  5365. units = self.defaults['units'].lower()
  5366. # for act in self.ui.cmenu_gridmenu.actions():
  5367. # act.triggered.disconnect()
  5368. self.ui.cmenu_gridmenu.clear()
  5369. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5370. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5371. _("Grid On/Off"))
  5372. grid_toggle.setCheckable(True)
  5373. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5374. self.ui.cmenu_gridmenu.addSeparator()
  5375. for grid in sorted_list:
  5376. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5377. "%s" % str(grid))
  5378. action.triggered.connect(self.set_grid)
  5379. self.ui.cmenu_gridmenu.addSeparator()
  5380. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5381. _("Add"))
  5382. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5383. _("Delete"))
  5384. grid_add.triggered.connect(self.on_grid_add)
  5385. grid_delete.triggered.connect(self.on_grid_delete)
  5386. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5387. def set_grid(self):
  5388. menu_action = self.sender()
  5389. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5390. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5391. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5392. def on_grid_add(self):
  5393. # ## Current application units in lower Case
  5394. units = self.defaults['units'].lower()
  5395. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5396. text=_('Enter a Grid Value:'),
  5397. min=0.0000, max=99.9999, decimals=4)
  5398. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5399. val, ok = grid_add_popup.get_value()
  5400. if ok:
  5401. if float(val) == 0:
  5402. self.inform.emit('[WARNING_NOTCL] %s' %
  5403. _("Please enter a grid value with non-zero value, in Float format."))
  5404. return
  5405. else:
  5406. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5407. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5408. self.inform.emit('[success] %s...' %
  5409. _("New Grid added"))
  5410. else:
  5411. self.inform.emit('[WARNING_NOTCL] %s...' %
  5412. _("Grid already exists"))
  5413. else:
  5414. self.inform.emit('[WARNING_NOTCL] %s...' %
  5415. _("Adding New Grid cancelled"))
  5416. def on_grid_delete(self):
  5417. # ## Current application units in lower Case
  5418. units = self.defaults['units'].lower()
  5419. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5420. text='Enter a Grid Value:',
  5421. min=0.0000, max=99.9999, decimals=4)
  5422. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5423. val, ok = grid_del_popup.get_value()
  5424. if ok:
  5425. if float(val) == 0:
  5426. self.inform.emit('[WARNING_NOTCL] %s' %
  5427. _("Please enter a grid value with non-zero value, in Float format."))
  5428. return
  5429. else:
  5430. try:
  5431. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5432. except ValueError:
  5433. self.inform.emit('[ERROR_NOTCL]%s...' %
  5434. _(" Grid Value does not exist"))
  5435. return
  5436. self.inform.emit('[success] %s...' %
  5437. _("Grid Value deleted"))
  5438. else:
  5439. self.inform.emit('[WARNING_NOTCL] %s...' %
  5440. _("Delete Grid value cancelled"))
  5441. def on_shortcut_list(self):
  5442. self.defaults.report_usage("on_shortcut_list()")
  5443. # add the tab if it was closed
  5444. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5445. # delete the absolute and relative position and messages in the infobar
  5446. self.ui.position_label.setText("")
  5447. self.ui.rel_position_label.setText("")
  5448. # Switch plot_area to preferences page
  5449. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5450. # self.ui.show()
  5451. def on_select_tab(self, name):
  5452. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5453. if self.ui.splitter.sizes()[0] == 0:
  5454. self.ui.splitter.setSizes([1, 1])
  5455. else:
  5456. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5457. self.ui.splitter.setSizes([0, 1])
  5458. if name == 'project':
  5459. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5460. elif name == 'selected':
  5461. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5462. elif name == 'tool':
  5463. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5464. def on_copy_name(self):
  5465. self.defaults.report_usage("on_copy_name()")
  5466. obj = self.collection.get_active()
  5467. try:
  5468. name = obj.options["name"]
  5469. except AttributeError:
  5470. log.debug("on_copy_name() --> No object selected to copy it's name")
  5471. self.inform.emit('[WARNING_NOTCL]%s' %
  5472. _(" No object selected to copy it's name"))
  5473. return
  5474. self.clipboard.setText(name)
  5475. self.inform.emit(_("Name copied on clipboard ..."))
  5476. def on_mouse_click_over_plot(self, event):
  5477. """
  5478. Default actions are:
  5479. :param event: Contains information about the event, like which button
  5480. was clicked, the pixel coordinates and the axes coordinates.
  5481. :return: None
  5482. """
  5483. self.pos = []
  5484. if self.is_legacy is False:
  5485. event_pos = event.pos
  5486. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5487. # # Set the mouse button for panning
  5488. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5489. else:
  5490. event_pos = (event.xdata, event.ydata)
  5491. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5492. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5493. # So it can receive key presses
  5494. self.plotcanvas.native.setFocus()
  5495. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5496. if self.grid_status():
  5497. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5498. else:
  5499. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5500. try:
  5501. if event.button == 1:
  5502. # Reset here the relative coordinates so there is a new reference on the click position
  5503. if self.rel_point1 is None:
  5504. self.rel_point1 = self.pos
  5505. else:
  5506. self.rel_point2 = copy(self.rel_point1)
  5507. self.rel_point1 = self.pos
  5508. self.on_mouse_move_over_plot(event, origin_click=True)
  5509. except Exception as e:
  5510. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5511. def on_mouse_double_click_over_plot(self, event):
  5512. if event.button == 1:
  5513. self.doubleclick = True
  5514. def on_mouse_move_over_plot(self, event, origin_click=None):
  5515. """
  5516. Callback for the mouse motion event over the plot.
  5517. :param event: Contains information about the event.
  5518. :param origin_click
  5519. :return: None
  5520. """
  5521. if self.is_legacy is False:
  5522. event_pos = event.pos
  5523. if self.defaults["global_pan_button"] == '2':
  5524. pan_button = 2
  5525. else:
  5526. pan_button = 3
  5527. self.event_is_dragging = event.is_dragging
  5528. else:
  5529. event_pos = (event.xdata, event.ydata)
  5530. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5531. if self.defaults["global_pan_button"] == '2':
  5532. pan_button = 3
  5533. else:
  5534. pan_button = 2
  5535. self.event_is_dragging = self.plotcanvas.is_dragging
  5536. # So it can receive key presses but not when the Tcl Shell is active
  5537. if not self.ui.shell_dock.isVisible():
  5538. if not self.plotcanvas.native.hasFocus():
  5539. self.plotcanvas.native.setFocus()
  5540. self.pos_jump = event_pos
  5541. self.ui.popMenu.mouse_is_panning = False
  5542. if origin_click is None:
  5543. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5544. if event.button == pan_button and self.event_is_dragging == 1:
  5545. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5546. if self.ui.popMenu.popup_active:
  5547. self.ui.popMenu.popup_active = False
  5548. return
  5549. self.ui.popMenu.mouse_is_panning = True
  5550. return
  5551. if self.rel_point1 is not None:
  5552. try: # May fail in case mouse not within axes
  5553. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5554. if self.grid_status():
  5555. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5556. # Update cursor
  5557. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5558. symbol='++', edge_color=self.cursor_color_3D,
  5559. edge_width=self.defaults["global_cursor_width"],
  5560. size=self.defaults["global_cursor_size"])
  5561. else:
  5562. pos = (pos_canvas[0], pos_canvas[1])
  5563. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5564. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5565. self.dx = pos[0] - float(self.rel_point1[0])
  5566. self.dy = pos[1] - float(self.rel_point1[1])
  5567. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5568. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5569. self.mouse = [pos[0], pos[1]]
  5570. # if the mouse is moved and the LMB is clicked then the action is a selection
  5571. if self.event_is_dragging == 1 and event.button == 1:
  5572. self.delete_selection_shape()
  5573. if self.dx < 0:
  5574. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5575. face_color=self.defaults['global_alt_sel_fill'])
  5576. self.selection_type = False
  5577. elif self.dx >= 0:
  5578. self.draw_moving_selection_shape(self.pos, pos)
  5579. self.selection_type = True
  5580. else:
  5581. self.selection_type = None
  5582. else:
  5583. self.selection_type = None
  5584. # hover effect - enabled in Preferences -> General -> GUI Settings
  5585. if self.defaults['global_hover']:
  5586. for obj in self.collection.get_list():
  5587. try:
  5588. # select the object(s) only if it is enabled (plotted)
  5589. if obj.options['plot']:
  5590. if obj not in self.collection.get_selected():
  5591. poly_obj = Polygon(
  5592. [(obj.options['xmin'], obj.options['ymin']),
  5593. (obj.options['xmax'], obj.options['ymin']),
  5594. (obj.options['xmax'], obj.options['ymax']),
  5595. (obj.options['xmin'], obj.options['ymax'])]
  5596. )
  5597. if Point(pos).within(poly_obj):
  5598. if obj.isHovering is False:
  5599. obj.isHovering = True
  5600. obj.notHovering = True
  5601. # create the selection box around the selected object
  5602. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5603. else:
  5604. if obj.notHovering is True:
  5605. obj.notHovering = False
  5606. obj.isHovering = False
  5607. self.delete_hover_shape()
  5608. except Exception:
  5609. # the Exception here will happen if we try to select on screen and we have an
  5610. # newly (and empty) just created Geometry or Excellon object that do not have the
  5611. # xmin, xmax, ymin, ymax options.
  5612. # In this case poly_obj creation (see above) will fail
  5613. pass
  5614. except Exception:
  5615. self.ui.position_label.setText("")
  5616. self.ui.rel_position_label.setText("")
  5617. self.mouse = None
  5618. def on_mouse_click_release_over_plot(self, event):
  5619. """
  5620. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5621. and has been registered in ''self.__init__()''.
  5622. :param event: contains information about the event.
  5623. :return:
  5624. """
  5625. if self.is_legacy is False:
  5626. event_pos = event.pos
  5627. right_button = 2
  5628. else:
  5629. event_pos = (event.xdata, event.ydata)
  5630. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5631. right_button = 3
  5632. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5633. if self.grid_status():
  5634. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5635. else:
  5636. pos = (pos_canvas[0], pos_canvas[1])
  5637. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5638. # canvas menu
  5639. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5640. self.ui.popMenu.mouse_is_panning = False
  5641. self.cursor = QtGui.QCursor()
  5642. self.populate_cmenu_grids()
  5643. self.ui.popMenu.popup(self.cursor.pos())
  5644. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5645. # selection and then select a type of selection ("enclosing" or "touching")
  5646. if event.button == 1: # left click
  5647. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5648. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5649. if modifiers == QtCore.Qt.ShiftModifier:
  5650. # do not auto open the Project Tab
  5651. self.click_noproject = True
  5652. self.clipboard.setText(
  5653. self.defaults["global_point_clipboard_format"] %
  5654. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5655. )
  5656. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5657. return
  5658. if self.doubleclick is True:
  5659. self.doubleclick = False
  5660. if self.collection.get_selected():
  5661. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5662. if self.ui.splitter.sizes()[0] == 0:
  5663. self.ui.splitter.setSizes([1, 1])
  5664. try:
  5665. # delete the selection shape(S) as it may be in the way
  5666. self.delete_selection_shape()
  5667. self.delete_hover_shape()
  5668. except Exception as e:
  5669. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5670. return
  5671. else:
  5672. # WORKAROUND for LEGACY MODE
  5673. if self.is_legacy is True:
  5674. # if there is no move on canvas then we have no dragging selection
  5675. if self.dx == 0 or self.dy == 0:
  5676. self.selection_type = None
  5677. if self.selection_type is not None:
  5678. try:
  5679. self.selection_area_handler(self.pos, pos, self.selection_type)
  5680. self.selection_type = None
  5681. except Exception as e:
  5682. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5683. return
  5684. else:
  5685. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5686. if key_modifier == QtCore.Qt.ShiftModifier:
  5687. mod_key = 'Shift'
  5688. elif key_modifier == QtCore.Qt.ControlModifier:
  5689. mod_key = 'Control'
  5690. else:
  5691. mod_key = None
  5692. try:
  5693. if mod_key == self.defaults["global_mselect_key"]:
  5694. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5695. # deselect, and if it's not selected then it will be selected
  5696. # If there is no active command (self.command_active is None) then we check if we clicked
  5697. # on a object by checking the bounding limits against mouse click position
  5698. if self.command_active is None:
  5699. self.select_objects(key='multisel')
  5700. self.delete_hover_shape()
  5701. else:
  5702. # If there is no active command (self.command_active is None) then we check if we clicked
  5703. # on a object by checking the bounding limits against mouse click position
  5704. if self.command_active is None:
  5705. self.select_objects()
  5706. self.delete_hover_shape()
  5707. except Exception as e:
  5708. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5709. return
  5710. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5711. """
  5712. :param start_pos: mouse position when the selection LMB click was done
  5713. :param end_pos: mouse position when the left mouse button is released
  5714. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5715. :return:
  5716. """
  5717. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5718. # delete previous selection shape
  5719. self.delete_selection_shape()
  5720. # make all objects inactive
  5721. self.collection.set_all_inactive()
  5722. for obj in self.collection.get_list():
  5723. try:
  5724. # select the object(s) only if it is enabled (plotted)
  5725. if obj.options['plot']:
  5726. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5727. (obj.options['xmax'], obj.options['ymin']),
  5728. (obj.options['xmax'], obj.options['ymax']),
  5729. (obj.options['xmin'], obj.options['ymax'])])
  5730. if sel_type is True:
  5731. if poly_obj.within(poly_selection):
  5732. # create the selection box around the selected object
  5733. if self.defaults['global_selection_shape'] is True:
  5734. self.draw_selection_shape(obj)
  5735. self.collection.set_active(obj.options['name'])
  5736. else:
  5737. if poly_selection.intersects(poly_obj):
  5738. # create the selection box around the selected object
  5739. if self.defaults['global_selection_shape'] is True:
  5740. self.draw_selection_shape(obj)
  5741. self.collection.set_active(obj.options['name'])
  5742. obj.selection_shape_drawn = True
  5743. except Exception as e:
  5744. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5745. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5746. # In this case poly_obj creation (see above) will fail
  5747. log.debug("App.selection_area_handler() --> %s" % str(e))
  5748. def select_objects(self, key=None):
  5749. """
  5750. Will select objects clicked on canvas
  5751. :param key: for future use in cumulative selection
  5752. :return:
  5753. """
  5754. # list where we store the overlapped objects under our mouse left click position
  5755. if key is None:
  5756. self.objects_under_the_click_list = []
  5757. # Populate the list with the overlapped objects on the click position
  5758. curr_x, curr_y = self.pos
  5759. for obj in self.all_objects_list:
  5760. # ScriptObject and DocumentObject objects can't be selected
  5761. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5762. continue
  5763. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5764. continue
  5765. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5766. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5767. if obj.options['name'] not in self.objects_under_the_click_list:
  5768. if obj.options['plot']:
  5769. # add objects to the objects_under_the_click list only if the object is plotted
  5770. # (active and not disabled)
  5771. self.objects_under_the_click_list.append(obj.options['name'])
  5772. try:
  5773. if self.objects_under_the_click_list:
  5774. curr_sel_obj = self.collection.get_active()
  5775. # case when there is only an object under the click and we toggle it
  5776. if len(self.objects_under_the_click_list) == 1:
  5777. if curr_sel_obj is None:
  5778. self.collection.set_active(self.objects_under_the_click_list[0])
  5779. curr_sel_obj = self.collection.get_active()
  5780. # create the selection box around the selected object
  5781. if self.defaults['global_selection_shape'] is True:
  5782. self.draw_selection_shape(curr_sel_obj)
  5783. curr_sel_obj.selection_shape_drawn = True
  5784. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5785. self.on_objects_selection(False)
  5786. self.delete_selection_shape()
  5787. curr_sel_obj.selection_shape_drawn = False
  5788. self.collection.set_active(self.objects_under_the_click_list[0])
  5789. curr_sel_obj = self.collection.get_active()
  5790. # create the selection box around the selected object
  5791. if self.defaults['global_selection_shape'] is True:
  5792. self.draw_selection_shape(curr_sel_obj)
  5793. curr_sel_obj.selection_shape_drawn = True
  5794. self.selected_message(curr_sel_obj=curr_sel_obj)
  5795. elif curr_sel_obj.selection_shape_drawn is False:
  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. else:
  5800. self.on_objects_selection(False)
  5801. self.delete_selection_shape()
  5802. if self.call_source != 'app':
  5803. self.call_source = 'app'
  5804. self.selected_message(curr_sel_obj=curr_sel_obj)
  5805. else:
  5806. # If there is no selected object
  5807. # make active the first element of the overlapped objects list
  5808. if self.collection.get_active() is None:
  5809. self.collection.set_active(self.objects_under_the_click_list[0])
  5810. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5811. name_sel_obj = self.collection.get_active().options['name']
  5812. # In case that there is a selected object but it is not in the overlapped object list
  5813. # make that object inactive and activate the first element in the overlapped object list
  5814. if name_sel_obj not in self.objects_under_the_click_list:
  5815. self.collection.set_inactive(name_sel_obj)
  5816. name_sel_obj = self.objects_under_the_click_list[0]
  5817. self.collection.set_active(name_sel_obj)
  5818. else:
  5819. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5820. self.collection.set_all_inactive()
  5821. self.collection.set_active(
  5822. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5823. curr_sel_obj = self.collection.get_active()
  5824. # delete the possible selection box around a possible selected object
  5825. self.delete_selection_shape()
  5826. curr_sel_obj.selection_shape_drawn = False
  5827. # create the selection box around the selected object
  5828. if self.defaults['global_selection_shape'] is True:
  5829. self.draw_selection_shape(curr_sel_obj)
  5830. curr_sel_obj.selection_shape_drawn = True
  5831. self.selected_message(curr_sel_obj=curr_sel_obj)
  5832. else:
  5833. # deselect everything
  5834. self.on_objects_selection(False)
  5835. # delete the possible selection box around a possible selected object
  5836. self.delete_selection_shape()
  5837. for o in self.collection.get_list():
  5838. o.selection_shape_drawn = False
  5839. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5840. # only when working on App
  5841. if self.call_source == 'app':
  5842. if self.click_noproject is False:
  5843. # if the Tool Tab is in focus don't change focus to Project Tab
  5844. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5845. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5846. else:
  5847. # restore auto open the Project Tab
  5848. self.click_noproject = False
  5849. # delete any text in the status bar, implicitly the last object name that was selected
  5850. # self.inform.emit("")
  5851. else:
  5852. self.call_source = 'app'
  5853. except Exception as e:
  5854. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5855. def selected_message(self, curr_sel_obj):
  5856. if curr_sel_obj:
  5857. if curr_sel_obj.kind == 'gerber':
  5858. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5859. color='green',
  5860. name=str(curr_sel_obj.options['name']),
  5861. tx=_("selected"))
  5862. )
  5863. elif curr_sel_obj.kind == 'excellon':
  5864. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5865. color='brown',
  5866. name=str(curr_sel_obj.options['name']),
  5867. tx=_("selected"))
  5868. )
  5869. elif curr_sel_obj.kind == 'cncjob':
  5870. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5871. color='blue',
  5872. name=str(curr_sel_obj.options['name']),
  5873. tx=_("selected"))
  5874. )
  5875. elif curr_sel_obj.kind == 'geometry':
  5876. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5877. color='red',
  5878. name=str(curr_sel_obj.options['name']),
  5879. tx=_("selected"))
  5880. )
  5881. def delete_hover_shape(self):
  5882. self.hover_shapes.clear()
  5883. self.hover_shapes.redraw()
  5884. def draw_hover_shape(self, sel_obj, color=None):
  5885. """
  5886. :param sel_obj: The object for which the hover shape must be drawn
  5887. :param color: The color of the hover shape
  5888. :return: None
  5889. """
  5890. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5891. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5892. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5893. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5894. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5895. if self.defaults['units'].upper() == 'MM':
  5896. hover_rect = hover_rect.buffer(-0.1)
  5897. hover_rect = hover_rect.buffer(0.2)
  5898. else:
  5899. hover_rect = hover_rect.buffer(-0.00393)
  5900. hover_rect = hover_rect.buffer(0.00787)
  5901. # if color:
  5902. # face = Color(color)
  5903. # face.alpha = 0.2
  5904. # outline = Color(color, alpha=0.8)
  5905. # else:
  5906. # face = Color(self.defaults['global_sel_fill'])
  5907. # face.alpha = 0.2
  5908. # outline = self.defaults['global_sel_line']
  5909. if color:
  5910. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5911. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5912. else:
  5913. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5914. outline = self.defaults['global_sel_line']
  5915. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5916. if self.is_legacy is True:
  5917. self.hover_shapes.redraw()
  5918. def delete_selection_shape(self):
  5919. self.move_tool.sel_shapes.clear()
  5920. self.move_tool.sel_shapes.redraw()
  5921. def draw_selection_shape(self, sel_obj, color=None):
  5922. """
  5923. Will draw a selection shape around the selected object.
  5924. :param sel_obj: The object for which the selection shape must be drawn
  5925. :param color: The color for the selection shape.
  5926. :return: None
  5927. """
  5928. if sel_obj is None:
  5929. return
  5930. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5931. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5932. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5933. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5934. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5935. if self.defaults['units'].upper() == 'MM':
  5936. sel_rect = sel_rect.buffer(-0.1)
  5937. sel_rect = sel_rect.buffer(0.2)
  5938. else:
  5939. sel_rect = sel_rect.buffer(-0.00393)
  5940. sel_rect = sel_rect.buffer(0.00787)
  5941. if color:
  5942. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5943. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5944. else:
  5945. if self.is_legacy is False:
  5946. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5947. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5948. else:
  5949. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5950. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5951. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5952. color=outline,
  5953. face_color=face,
  5954. update=True,
  5955. layer=0,
  5956. tolerance=None))
  5957. if self.is_legacy is True:
  5958. self.move_tool.sel_shapes.redraw()
  5959. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5960. """
  5961. Will draw a selection shape when dragging mouse on canvas.
  5962. :param old_coords: Old coordinates
  5963. :param coords: New coordinates
  5964. :param kwargs: Keyword arguments
  5965. :return:
  5966. """
  5967. if 'color' in kwargs:
  5968. color = kwargs['color']
  5969. else:
  5970. color = self.defaults['global_sel_line']
  5971. if 'face_color' in kwargs:
  5972. face_color = kwargs['face_color']
  5973. else:
  5974. face_color = self.defaults['global_sel_fill']
  5975. if 'face_alpha' in kwargs:
  5976. face_alpha = kwargs['face_alpha']
  5977. else:
  5978. face_alpha = 0.3
  5979. x0, y0 = old_coords
  5980. x1, y1 = coords
  5981. pt1 = (x0, y0)
  5982. pt2 = (x1, y0)
  5983. pt3 = (x1, y1)
  5984. pt4 = (x0, y1)
  5985. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5986. # color_t = Color(face_color)
  5987. # color_t.alpha = face_alpha
  5988. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5989. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5990. layer=0, tolerance=None)
  5991. if self.is_legacy is True:
  5992. self.move_tool.sel_shapes.redraw()
  5993. def on_file_new_click(self):
  5994. """
  5995. Callback for menu item File -> New.
  5996. Executed on clicking the Menu -> File -> New Project
  5997. :return:
  5998. """
  5999. if self.collection.get_list() and self.should_we_save:
  6000. msgbox = QtWidgets.QMessageBox()
  6001. # msgbox.setText("<B>Save changes ...</B>")
  6002. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6003. "Creating a New project will delete them.\n"
  6004. "Do you want to Save the project?"))
  6005. msgbox.setWindowTitle(_("Save changes"))
  6006. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6007. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6008. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6009. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6010. msgbox.setDefaultButton(bt_yes)
  6011. msgbox.exec_()
  6012. response = msgbox.clickedButton()
  6013. if response == bt_yes:
  6014. self.on_file_saveprojectas()
  6015. elif response == bt_cancel:
  6016. return
  6017. elif response == bt_no:
  6018. self.on_file_new()
  6019. else:
  6020. self.on_file_new()
  6021. self.inform.emit('[success] %s...' % _("New Project created"))
  6022. def on_file_new(self, cli=None):
  6023. """
  6024. Returns the application to its startup state. This method is thread-safe.
  6025. :param cli: Boolean. If True this method was run from command line
  6026. :return: None
  6027. """
  6028. self.defaults.report_usage("on_file_new")
  6029. # Remove everything from memory
  6030. App.log.debug("on_file_new()")
  6031. if self.call_source != 'app':
  6032. self.editor2object(cleanup=True)
  6033. # ## EDITOR section
  6034. self.geo_editor = FlatCAMGeoEditor(self)
  6035. self.exc_editor = FlatCAMExcEditor(self)
  6036. self.grb_editor = FlatCAMGrbEditor(self)
  6037. # Clear pool
  6038. self.clear_pool()
  6039. for obj in self.collection.get_list():
  6040. # delete shapes left drawn from mark shape_collections, if any
  6041. if isinstance(obj, GerberObject):
  6042. try:
  6043. for el in obj.mark_shapes:
  6044. obj.mark_shapes[el].clear(update=True)
  6045. obj.mark_shapes[el].enabled = False
  6046. del el
  6047. except AttributeError:
  6048. pass
  6049. # also delete annotation shapes, if any
  6050. elif isinstance(obj, CNCJobObject):
  6051. try:
  6052. obj.text_col.enabled = False
  6053. del obj.text_col
  6054. obj.annotation.clear(update=True)
  6055. del obj.annotation
  6056. except AttributeError:
  6057. pass
  6058. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6059. self.shell.init_tcl()
  6060. self.delete_selection_shape()
  6061. self.collection.delete_all()
  6062. self.setup_component_editor()
  6063. # Clear project filename
  6064. self.project_filename = None
  6065. # Load the application defaults
  6066. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6067. # Re-fresh project options
  6068. self.on_options_app2project()
  6069. # Init Tools
  6070. self.init_tools()
  6071. if cli is None:
  6072. # Close any Tabs opened in the Plot Tab Area section
  6073. for index in range(self.ui.plot_tab_area.count()):
  6074. self.ui.plot_tab_area.closeTab(index)
  6075. # for whatever reason previous command does not close the last tab so I do it manually
  6076. self.ui.plot_tab_area.closeTab(0)
  6077. # # And then add again the Plot Area
  6078. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6079. self.ui.plot_tab_area.protectTab(0)
  6080. # take the focus of the Notebook on Project Tab.
  6081. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6082. self.set_ui_title(name=_("New Project - Not saved"))
  6083. def obj_properties(self):
  6084. """
  6085. Will launch the object Properties Tool
  6086. :return:
  6087. """
  6088. self.defaults.report_usage("obj_properties()")
  6089. self.properties_tool.run(toggle=False)
  6090. def on_project_context_save(self):
  6091. """
  6092. Wrapper, will save the object function of it's type
  6093. :return:
  6094. """
  6095. obj = self.collection.get_active()
  6096. if type(obj) == GeometryObject:
  6097. self.on_file_exportdxf()
  6098. elif type(obj) == ExcellonObject:
  6099. self.on_file_saveexcellon()
  6100. elif type(obj) == CNCJobObject:
  6101. obj.on_exportgcode_button_click()
  6102. elif type(obj) == GerberObject:
  6103. self.on_file_savegerber()
  6104. elif type(obj) == ScriptObject:
  6105. self.on_file_savescript()
  6106. elif type(obj) == DocumentObject:
  6107. self.on_file_savedocument()
  6108. def obj_move(self):
  6109. """
  6110. Callback for the Move menu entry in various Context Menu's.
  6111. :return:
  6112. """
  6113. self.defaults.report_usage("obj_move()")
  6114. self.move_tool.run(toggle=False)
  6115. def on_fileopengerber(self, signal, name=None):
  6116. """
  6117. File menu callback for opening a Gerber.
  6118. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6119. :param name:
  6120. :return: None
  6121. """
  6122. self.defaults.report_usage("on_fileopengerber")
  6123. App.log.debug("on_fileopengerber()")
  6124. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6125. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6126. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6127. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6128. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6129. "*.mil);;" \
  6130. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6131. "Allegro Files (*.art);;" \
  6132. "Mentor Files (*.pho *.gdo);;" \
  6133. "All Files (*.*)"
  6134. if name is None:
  6135. try:
  6136. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6137. directory=self.get_last_folder(),
  6138. filter=_filter_)
  6139. except TypeError:
  6140. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6141. filenames = [str(filename) for filename in filenames]
  6142. else:
  6143. filenames = [name]
  6144. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6145. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6146. _("Opening Gerber file.")),
  6147. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6148. color=QtGui.QColor("gray"))
  6149. if len(filenames) == 0:
  6150. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6151. else:
  6152. for filename in filenames:
  6153. if filename != '':
  6154. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6155. def on_fileopenexcellon(self, signal, name=None):
  6156. """
  6157. File menu callback for opening an Excellon file.
  6158. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6159. :param name:
  6160. :return: None
  6161. """
  6162. self.defaults.report_usage("on_fileopenexcellon")
  6163. App.log.debug("on_fileopenexcellon()")
  6164. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6165. "All Files (*.*)"
  6166. if name is None:
  6167. try:
  6168. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6169. directory=self.get_last_folder(),
  6170. filter=_filter_)
  6171. except TypeError:
  6172. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6173. filenames = [str(filename) for filename in filenames]
  6174. else:
  6175. filenames = [str(name)]
  6176. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6177. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6178. _("Opening Excellon file.")),
  6179. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6180. color=QtGui.QColor("gray"))
  6181. if len(filenames) == 0:
  6182. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6183. else:
  6184. for filename in filenames:
  6185. if filename != '':
  6186. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6187. def on_fileopengcode(self, signal, name=None):
  6188. """
  6189. File menu call back for opening gcode.
  6190. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6191. :param name:
  6192. :return:
  6193. """
  6194. self.defaults.report_usage("on_fileopengcode")
  6195. App.log.debug("on_fileopengcode()")
  6196. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6197. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6198. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6199. "All Files (*.*)"
  6200. if name is None:
  6201. try:
  6202. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6203. directory=self.get_last_folder(),
  6204. filter=_filter_)
  6205. except TypeError:
  6206. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6207. filenames = [str(filename) for filename in filenames]
  6208. else:
  6209. filenames = [name]
  6210. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6211. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6212. _("Opening G-Code file.")),
  6213. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6214. color=QtGui.QColor("gray"))
  6215. if len(filenames) == 0:
  6216. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6217. else:
  6218. for filename in filenames:
  6219. if filename != '':
  6220. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6221. def on_file_openproject(self, signal):
  6222. """
  6223. File menu callback for opening a project.
  6224. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6225. :return: None
  6226. """
  6227. self.defaults.report_usage("on_file_openproject")
  6228. App.log.debug("on_file_openproject()")
  6229. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6230. try:
  6231. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6232. directory=self.get_last_folder(), filter=_filter_)
  6233. except TypeError:
  6234. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6235. # The Qt methods above will return a QString which can cause problems later.
  6236. # So far json.dump() will fail to serialize it.
  6237. # TODO: Improve the serialization methods and remove this fix.
  6238. filename = str(filename)
  6239. if filename == "":
  6240. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6241. else:
  6242. # self.worker_task.emit({'fcn': self.open_project,
  6243. # 'params': [filename]})
  6244. # The above was failing because open_project() is not
  6245. # thread safe. The new_project()
  6246. self.open_project(filename)
  6247. def on_fileopenhpgl2(self, signal, name=None):
  6248. """
  6249. File menu callback for opening a HPGL2.
  6250. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6251. :param name:
  6252. :return: None
  6253. """
  6254. self.defaults.report_usage("on_fileopenhpgl2")
  6255. App.log.debug("on_fileopenhpgl2()")
  6256. _filter_ = "HPGL2 Files (*.plt);;" \
  6257. "All Files (*.*)"
  6258. if name is None:
  6259. try:
  6260. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6261. directory=self.get_last_folder(),
  6262. filter=_filter_)
  6263. except TypeError:
  6264. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6265. filenames = [str(filename) for filename in filenames]
  6266. else:
  6267. filenames = [name]
  6268. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6269. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6270. _("Opening HPGL2 file.")),
  6271. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6272. color=QtGui.QColor("gray"))
  6273. if len(filenames) == 0:
  6274. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6275. else:
  6276. for filename in filenames:
  6277. if filename != '':
  6278. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6279. def on_file_openconfig(self, signal):
  6280. """
  6281. File menu callback for opening a config file.
  6282. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6283. :return: None
  6284. """
  6285. self.defaults.report_usage("on_file_openconfig")
  6286. App.log.debug("on_file_openconfig()")
  6287. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6288. try:
  6289. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6290. directory=self.data_path, filter=_filter_)
  6291. except TypeError:
  6292. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6293. filter=_filter_)
  6294. if filename == "":
  6295. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6296. else:
  6297. self.open_config_file(filename)
  6298. def on_file_exportsvg(self):
  6299. """
  6300. Callback for menu item File->Export SVG.
  6301. :return: None
  6302. """
  6303. self.defaults.report_usage("on_file_exportsvg")
  6304. App.log.debug("on_file_exportsvg()")
  6305. obj = self.collection.get_active()
  6306. if obj is None:
  6307. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6308. msg = _("Please Select a Geometry object to export")
  6309. msgbox = QtWidgets.QMessageBox()
  6310. msgbox.setInformativeText(msg)
  6311. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6312. msgbox.setDefaultButton(bt_ok)
  6313. msgbox.exec_()
  6314. return
  6315. # Check for more compatible types and add as required
  6316. if (not isinstance(obj, GeometryObject)
  6317. and not isinstance(obj, GerberObject)
  6318. and not isinstance(obj, CNCJobObject)
  6319. and not isinstance(obj, ExcellonObject)):
  6320. msg = '[ERROR_NOTCL] %s' % \
  6321. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6322. msgbox = QtWidgets.QMessageBox()
  6323. msgbox.setInformativeText(msg)
  6324. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6325. msgbox.setDefaultButton(bt_ok)
  6326. msgbox.exec_()
  6327. return
  6328. name = obj.options["name"]
  6329. _filter = "SVG File (*.svg);;All Files (*.*)"
  6330. try:
  6331. filename, _f = FCFileSaveDialog.get_saved_filename(
  6332. caption=_("Export SVG"),
  6333. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6334. filter=_filter)
  6335. except TypeError:
  6336. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6337. filename = str(filename)
  6338. if filename == "":
  6339. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6340. return
  6341. else:
  6342. self.export_svg(name, filename)
  6343. if self.defaults["global_open_style"] is False:
  6344. self.file_opened.emit("SVG", filename)
  6345. self.file_saved.emit("SVG", filename)
  6346. def on_file_exportpng(self):
  6347. self.defaults.report_usage("on_file_exportpng")
  6348. App.log.debug("on_file_exportpng()")
  6349. self.date = str(datetime.today()).rpartition('.')[0]
  6350. self.date = ''.join(c for c in self.date if c not in ':-')
  6351. self.date = self.date.replace(' ', '_')
  6352. if self.is_legacy is False:
  6353. image = _screenshot()
  6354. data = np.asarray(image)
  6355. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6356. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6357. return
  6358. filter_ = "PNG File (*.png);;All Files (*.*)"
  6359. try:
  6360. filename, _f = FCFileSaveDialog.get_saved_filename(
  6361. caption=_("Export PNG Image"),
  6362. directory=self.get_last_save_folder() + '/png_' + self.date,
  6363. filter=filter_)
  6364. except TypeError:
  6365. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6366. filename = str(filename)
  6367. if filename == "":
  6368. self.inform.emit(_("Cancelled."))
  6369. return
  6370. else:
  6371. if self.is_legacy is False:
  6372. write_png(filename, data)
  6373. else:
  6374. self.plotcanvas.figure.savefig(filename)
  6375. if self.defaults["global_open_style"] is False:
  6376. self.file_opened.emit("png", filename)
  6377. self.file_saved.emit("png", filename)
  6378. def on_file_savegerber(self):
  6379. """
  6380. Callback for menu item in Project context menu.
  6381. :return: None
  6382. """
  6383. self.defaults.report_usage("on_file_savegerber")
  6384. App.log.debug("on_file_savegerber()")
  6385. obj = self.collection.get_active()
  6386. if obj is None:
  6387. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6388. return
  6389. # Check for more compatible types and add as required
  6390. if not isinstance(obj, GerberObject):
  6391. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6392. return
  6393. name = self.collection.get_active().options["name"]
  6394. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6395. try:
  6396. filename, _f = FCFileSaveDialog.get_saved_filename(
  6397. caption="Save Gerber source file",
  6398. directory=self.get_last_save_folder() + '/' + name,
  6399. filter=_filter)
  6400. except TypeError:
  6401. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6402. filename = str(filename)
  6403. if filename == "":
  6404. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6405. return
  6406. else:
  6407. self.save_source_file(name, filename)
  6408. if self.defaults["global_open_style"] is False:
  6409. self.file_opened.emit("Gerber", filename)
  6410. self.file_saved.emit("Gerber", filename)
  6411. def on_file_savescript(self):
  6412. """
  6413. Callback for menu item in Project context menu.
  6414. :return: None
  6415. """
  6416. self.defaults.report_usage("on_file_savescript")
  6417. App.log.debug("on_file_savescript()")
  6418. obj = self.collection.get_active()
  6419. if obj is None:
  6420. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6421. return
  6422. # Check for more compatible types and add as required
  6423. if not isinstance(obj, ScriptObject):
  6424. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6425. return
  6426. name = self.collection.get_active().options["name"]
  6427. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6428. try:
  6429. filename, _f = FCFileSaveDialog.get_saved_filename(
  6430. caption="Save Script source file",
  6431. directory=self.get_last_save_folder() + '/' + name,
  6432. filter=_filter)
  6433. except TypeError:
  6434. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6435. filename = str(filename)
  6436. if filename == "":
  6437. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6438. return
  6439. else:
  6440. self.save_source_file(name, filename)
  6441. if self.defaults["global_open_style"] is False:
  6442. self.file_opened.emit("Script", filename)
  6443. self.file_saved.emit("Script", filename)
  6444. def on_file_savedocument(self):
  6445. """
  6446. Callback for menu item in Project context menu.
  6447. :return: None
  6448. """
  6449. self.defaults.report_usage("on_file_savedocument")
  6450. App.log.debug("on_file_savedocument()")
  6451. obj = self.collection.get_active()
  6452. if obj is None:
  6453. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6454. return
  6455. # Check for more compatible types and add as required
  6456. if not isinstance(obj, ScriptObject):
  6457. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6458. return
  6459. name = self.collection.get_active().options["name"]
  6460. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6461. try:
  6462. filename, _f = FCFileSaveDialog.get_saved_filename(
  6463. caption="Save Document source file",
  6464. directory=self.get_last_save_folder() + '/' + name,
  6465. filter=_filter)
  6466. except TypeError:
  6467. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6468. filename = str(filename)
  6469. if filename == "":
  6470. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6471. return
  6472. else:
  6473. self.save_source_file(name, filename)
  6474. if self.defaults["global_open_style"] is False:
  6475. self.file_opened.emit("Document", filename)
  6476. self.file_saved.emit("Document", filename)
  6477. def on_file_saveexcellon(self):
  6478. """
  6479. Callback for menu item in project context menu.
  6480. :return: None
  6481. """
  6482. self.defaults.report_usage("on_file_saveexcellon")
  6483. App.log.debug("on_file_saveexcellon()")
  6484. obj = self.collection.get_active()
  6485. if obj is None:
  6486. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6487. return
  6488. # Check for more compatible types and add as required
  6489. if not isinstance(obj, ExcellonObject):
  6490. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6491. return
  6492. name = self.collection.get_active().options["name"]
  6493. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6494. try:
  6495. filename, _f = FCFileSaveDialog.get_saved_filename(
  6496. caption=_("Save Excellon source file"),
  6497. directory=self.get_last_save_folder() + '/' + name,
  6498. filter=_filter)
  6499. except TypeError:
  6500. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6501. filename = str(filename)
  6502. if filename == "":
  6503. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6504. return
  6505. else:
  6506. self.save_source_file(name, filename)
  6507. if self.defaults["global_open_style"] is False:
  6508. self.file_opened.emit("Excellon", filename)
  6509. self.file_saved.emit("Excellon", filename)
  6510. def on_file_exportexcellon(self):
  6511. """
  6512. Callback for menu item File->Export->Excellon.
  6513. :return: None
  6514. """
  6515. self.defaults.report_usage("on_file_exportexcellon")
  6516. App.log.debug("on_file_exportexcellon()")
  6517. obj = self.collection.get_active()
  6518. if obj is None:
  6519. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6520. return
  6521. # Check for more compatible types and add as required
  6522. if not isinstance(obj, ExcellonObject):
  6523. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6524. return
  6525. name = self.collection.get_active().options["name"]
  6526. _filter = self.defaults["excellon_save_filters"]
  6527. try:
  6528. filename, _f = FCFileSaveDialog.get_saved_filename(
  6529. caption=_("Export Excellon"),
  6530. directory=self.get_last_save_folder() + '/' + name,
  6531. filter=_filter)
  6532. except TypeError:
  6533. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6534. filename = str(filename)
  6535. if filename == "":
  6536. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6537. return
  6538. else:
  6539. used_extension = filename.rpartition('.')[2]
  6540. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6541. self.export_excellon(name, filename)
  6542. if self.defaults["global_open_style"] is False:
  6543. self.file_opened.emit("Excellon", filename)
  6544. self.file_saved.emit("Excellon", filename)
  6545. def on_file_exportgerber(self):
  6546. """
  6547. Callback for menu item File->Export->Gerber.
  6548. :return: None
  6549. """
  6550. self.defaults.report_usage("on_file_exportgerber")
  6551. App.log.debug("on_file_exportgerber()")
  6552. obj = self.collection.get_active()
  6553. if obj is None:
  6554. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6555. return
  6556. # Check for more compatible types and add as required
  6557. if not isinstance(obj, GerberObject):
  6558. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6559. return
  6560. name = self.collection.get_active().options["name"]
  6561. _filter_ = self.defaults['gerber_save_filters']
  6562. try:
  6563. filename, _f = FCFileSaveDialog.get_saved_filename(
  6564. caption=_("Export Gerber"),
  6565. directory=self.get_last_save_folder() + '/' + name,
  6566. filter=_filter_)
  6567. except TypeError:
  6568. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6569. filename = str(filename)
  6570. if filename == "":
  6571. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6572. return
  6573. else:
  6574. used_extension = filename.rpartition('.')[2]
  6575. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6576. self.export_gerber(name, filename)
  6577. if self.defaults["global_open_style"] is False:
  6578. self.file_opened.emit("Gerber", filename)
  6579. self.file_saved.emit("Gerber", filename)
  6580. def on_file_exportdxf(self):
  6581. """
  6582. Callback for menu item File->Export DXF.
  6583. :return: None
  6584. """
  6585. self.defaults.report_usage("on_file_exportdxf")
  6586. App.log.debug("on_file_exportdxf()")
  6587. obj = self.collection.get_active()
  6588. if obj is None:
  6589. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6590. msg = _("Please Select a Geometry object to export")
  6591. msgbox = QtWidgets.QMessageBox()
  6592. msgbox.setInformativeText(msg)
  6593. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6594. msgbox.setDefaultButton(bt_ok)
  6595. msgbox.exec_()
  6596. return
  6597. # Check for more compatible types and add as required
  6598. if not isinstance(obj, GeometryObject):
  6599. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6600. msgbox = QtWidgets.QMessageBox()
  6601. msgbox.setInformativeText(msg)
  6602. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6603. msgbox.setDefaultButton(bt_ok)
  6604. msgbox.exec_()
  6605. return
  6606. name = self.collection.get_active().options["name"]
  6607. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6608. try:
  6609. filename, _f = FCFileSaveDialog.get_saved_filename(
  6610. caption=_("Export DXF"),
  6611. directory=self.get_last_save_folder() + '/' + name,
  6612. filter=_filter_)
  6613. except TypeError:
  6614. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6615. filename = str(filename)
  6616. if filename == "":
  6617. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6618. return
  6619. else:
  6620. self.export_dxf(name, filename)
  6621. if self.defaults["global_open_style"] is False:
  6622. self.file_opened.emit("DXF", filename)
  6623. self.file_saved.emit("DXF", filename)
  6624. def on_file_importsvg(self, type_of_obj):
  6625. """
  6626. Callback for menu item File->Import SVG.
  6627. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6628. :type type_of_obj: str
  6629. :return: None
  6630. """
  6631. self.defaults.report_usage("on_file_importsvg")
  6632. App.log.debug("on_file_importsvg()")
  6633. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6634. try:
  6635. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6636. directory=self.get_last_folder(), filter=_filter_)
  6637. except TypeError:
  6638. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6639. filter=_filter_)
  6640. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6641. type_of_obj = "geometry"
  6642. filenames = [str(filename) for filename in filenames]
  6643. if len(filenames) == 0:
  6644. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6645. else:
  6646. for filename in filenames:
  6647. if filename != '':
  6648. self.worker_task.emit({'fcn': self.import_svg,
  6649. 'params': [filename, type_of_obj]})
  6650. def on_file_importdxf(self, type_of_obj):
  6651. """
  6652. Callback for menu item File->Import DXF.
  6653. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6654. :type type_of_obj: str
  6655. :return: None
  6656. """
  6657. self.defaults.report_usage("on_file_importdxf")
  6658. App.log.debug("on_file_importdxf()")
  6659. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6660. try:
  6661. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6662. directory=self.get_last_folder(),
  6663. filter=_filter_)
  6664. except TypeError:
  6665. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6666. filter=_filter_)
  6667. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6668. type_of_obj = "geometry"
  6669. filenames = [str(filename) for filename in filenames]
  6670. if len(filenames) == 0:
  6671. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6672. else:
  6673. for filename in filenames:
  6674. if filename != '':
  6675. self.worker_task.emit({'fcn': self.import_dxf,
  6676. 'params': [filename, type_of_obj]})
  6677. # ###############################################################################################################
  6678. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6679. # ###############################################################################################################
  6680. def init_code_editor(self, name):
  6681. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6682. # add the tab if it was closed
  6683. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6684. self.text_editor_tab.setObjectName('text_editor_tab')
  6685. # delete the absolute and relative position and messages in the infobar
  6686. self.ui.position_label.setText("")
  6687. self.ui.rel_position_label.setText("")
  6688. # first clear previous text in text editor (if any)
  6689. self.text_editor_tab.code_editor.clear()
  6690. self.text_editor_tab.code_editor.setReadOnly(False)
  6691. self.toggle_codeeditor = True
  6692. self.text_editor_tab.code_editor.completer_enable = False
  6693. self.text_editor_tab.buttonRun.hide()
  6694. # make sure to keep a reference to the code editor
  6695. self.reference_code_editor = self.text_editor_tab.code_editor
  6696. # Switch plot_area to CNCJob tab
  6697. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6698. def on_view_source(self):
  6699. """
  6700. Called when the user wants to see the source file of the selected object
  6701. :return:
  6702. """
  6703. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6704. self.proc_container.view.set_busy(_("Loading..."))
  6705. try:
  6706. obj = self.collection.get_active()
  6707. except Exception as e:
  6708. log.debug("App.on_view_source() --> %s" % str(e))
  6709. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6710. return 'fail'
  6711. if obj is None:
  6712. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6713. return 'fail'
  6714. flt = "All Files (*.*)"
  6715. if obj.kind == 'gerber':
  6716. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6717. elif obj.kind == 'excellon':
  6718. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6719. elif obj.kind == 'cncjob':
  6720. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6721. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6722. # add the tab if it was closed
  6723. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6724. self.source_editor_tab.setObjectName('source_editor_tab')
  6725. # delete the absolute and relative position and messages in the infobar
  6726. self.ui.position_label.setText("")
  6727. self.ui.rel_position_label.setText("")
  6728. # first clear previous text in text editor (if any)
  6729. self.source_editor_tab.code_editor.clear()
  6730. self.source_editor_tab.code_editor.setReadOnly(False)
  6731. self.source_editor_tab.code_editor.completer_enable = False
  6732. self.source_editor_tab.buttonRun.hide()
  6733. # Switch plot_area to CNCJob tab
  6734. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6735. try:
  6736. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6737. except TypeError:
  6738. pass
  6739. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6740. try:
  6741. self.source_editor_tab.buttonSave.clicked.disconnect()
  6742. except TypeError:
  6743. pass
  6744. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6745. # then append the text from GCode to the text editor
  6746. if obj.kind == 'cncjob':
  6747. try:
  6748. file = obj.export_gcode(
  6749. preamble=self.defaults["cncjob_prepend"],
  6750. postamble=self.defaults["cncjob_append"],
  6751. to_file=True)
  6752. if file == 'fail':
  6753. return 'fail'
  6754. except AttributeError:
  6755. self.inform.emit('[WARNING_NOTCL] %s' %
  6756. _("There is no selected object for which to see it's source file code."))
  6757. return 'fail'
  6758. else:
  6759. try:
  6760. file = StringIO(obj.source_file)
  6761. except (AttributeError, TypeError):
  6762. self.inform.emit('[WARNING_NOTCL] %s' %
  6763. _("There is no selected object for which to see it's source file code."))
  6764. return 'fail'
  6765. self.source_editor_tab.t_frame.hide()
  6766. try:
  6767. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6768. # for line in file:
  6769. # QtWidgets.QApplication.processEvents()
  6770. # proc_line = str(line).strip('\n')
  6771. # self.source_editor_tab.code_editor.append(proc_line)
  6772. except Exception as e:
  6773. log.debug('App.on_view_source() -->%s' % str(e))
  6774. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6775. return
  6776. self.source_editor_tab.handleTextChanged()
  6777. self.source_editor_tab.t_frame.show()
  6778. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6779. self.proc_container.view.set_idle()
  6780. # self.ui.show()
  6781. def on_toggle_code_editor(self):
  6782. self.defaults.report_usage("on_toggle_code_editor()")
  6783. if self.toggle_codeeditor is False:
  6784. self.init_code_editor(name=_("Code Editor"))
  6785. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6786. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6787. self.text_editor_tab.buttonSave.clicked.disconnect()
  6788. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6789. else:
  6790. for idx in range(self.ui.plot_tab_area.count()):
  6791. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6792. self.ui.plot_tab_area.closeTab(idx)
  6793. break
  6794. self.toggle_codeeditor = False
  6795. def on_code_editor_close(self):
  6796. self.toggle_codeeditor = False
  6797. def goto_text_line(self):
  6798. """
  6799. Will scroll a text to the specified text line.
  6800. :return: None
  6801. """
  6802. dia_box = Dialog_box(title=_("Go to Line ..."),
  6803. label=_("Line:"),
  6804. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6805. initial_text='')
  6806. try:
  6807. line = int(dia_box.location) - 1
  6808. except (ValueError, TypeError):
  6809. line = 0
  6810. if dia_box.ok:
  6811. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6812. # at the top of the window
  6813. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6814. # get the document() of the TextEditor
  6815. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6816. # create a Text Cursor based on the searched line
  6817. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6818. # set cursor of the code editor with the cursor at the searcehd line
  6819. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6820. def on_filenewscript(self, silent=False, name=None, text=None):
  6821. """
  6822. Will create a new script file and open it in the Code Editor
  6823. :param silent: if True will not display status messages
  6824. :param name: if specified will be the name of the new script
  6825. :param text: pass a source file to the newly created script to be loaded in it
  6826. :return: None
  6827. """
  6828. if silent is False:
  6829. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6830. # delete the absolute and relative position and messages in the infobar
  6831. self.ui.position_label.setText("")
  6832. self.ui.rel_position_label.setText("")
  6833. if name is not None:
  6834. self.new_script_object(name=name, text=text)
  6835. else:
  6836. self.new_script_object(text=text)
  6837. # script_text = script_obj.source_file
  6838. #
  6839. # self.proc_container.view.set_busy(_("Loading..."))
  6840. # script_obj.script_editor_tab.t_frame.hide()
  6841. #
  6842. # script_obj.script_editor_tab.t_frame.show()
  6843. # self.proc_container.view.set_idle()
  6844. def on_fileopenscript(self, name=None, silent=False):
  6845. """
  6846. Will open a Tcl script file into the Code Editor
  6847. :param silent: if True will not display status messages
  6848. :param name: name of a Tcl script file to open
  6849. :return:
  6850. """
  6851. self.defaults.report_usage("on_fileopenscript")
  6852. App.log.debug("on_fileopenscript()")
  6853. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6854. "All Files (*.*)"
  6855. if name:
  6856. filenames = [name]
  6857. else:
  6858. try:
  6859. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6860. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6861. except TypeError:
  6862. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6863. if len(filenames) == 0:
  6864. if silent is False:
  6865. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6866. else:
  6867. for filename in filenames:
  6868. if filename != '':
  6869. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6870. def on_fileopenscript_example(self, name=None, silent=False):
  6871. """
  6872. Will open a Tcl script file into the Code Editor
  6873. :param silent: if True will not display status messages
  6874. :param name: name of a Tcl script file to open
  6875. :return:
  6876. """
  6877. self.report_usage("on_fileopenscript_example")
  6878. App.log.debug("on_fileopenscript_example()")
  6879. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6880. "All Files (*.*)"
  6881. # test if the app was frozen and choose the path for the configuration file
  6882. if getattr(sys, "frozen", False) is True:
  6883. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6884. else:
  6885. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6886. if name:
  6887. filenames = [name]
  6888. else:
  6889. try:
  6890. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6891. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6892. except TypeError:
  6893. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6894. if len(filenames) == 0:
  6895. if silent is False:
  6896. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6897. else:
  6898. for filename in filenames:
  6899. if filename != '':
  6900. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6901. def on_filerunscript(self, name=None, silent=False):
  6902. """
  6903. File menu callback for loading and running a TCL script.
  6904. :param silent: if True will not display status messages
  6905. :param name: name of a Tcl script file to be run by FlatCAM
  6906. :return: None
  6907. """
  6908. self.defaults.report_usage("on_filerunscript")
  6909. App.log.debug("on_file_runscript()")
  6910. if name:
  6911. filename = name
  6912. if self.cmd_line_headless != 1:
  6913. self.splash.showMessage('%s: %ssec\n%s' %
  6914. (_("Canvas initialization started.\n"
  6915. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6916. _("Executing ScriptObject file.")
  6917. ),
  6918. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6919. color=QtGui.QColor("gray"))
  6920. else:
  6921. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6922. "All Files (*.*)"
  6923. try:
  6924. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6925. directory=self.get_last_folder(), filter=_filter_)
  6926. except TypeError:
  6927. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6928. # The Qt methods above will return a QString which can cause problems later.
  6929. # So far json.dump() will fail to serialize it.
  6930. filename = str(filename)
  6931. if filename == "":
  6932. if silent is False:
  6933. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6934. else:
  6935. if self.cmd_line_headless != 1:
  6936. if self.ui.shell_dock.isHidden():
  6937. self.ui.shell_dock.show()
  6938. try:
  6939. with open(filename, "r") as tcl_script:
  6940. cmd_line_shellfile_content = tcl_script.read()
  6941. if self.cmd_line_headless != 1:
  6942. self.shell.exec_command(cmd_line_shellfile_content)
  6943. else:
  6944. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6945. if silent is False:
  6946. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6947. except Exception as e:
  6948. log.debug("App.on_filerunscript() -> %s" % str(e))
  6949. sys.exit(2)
  6950. def on_file_saveproject(self, silent=False):
  6951. """
  6952. Callback for menu item File->Save Project. Saves the project to
  6953. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6954. if set to None. The project is saved by calling ``self.save_project()``.
  6955. :param silent: if True will not display status messages
  6956. :return: None
  6957. """
  6958. self.defaults.report_usage("on_file_saveproject")
  6959. if self.project_filename is None:
  6960. self.on_file_saveprojectas()
  6961. else:
  6962. self.worker_task.emit({'fcn': self.save_project,
  6963. 'params': [self.project_filename, silent]})
  6964. if self.defaults["global_open_style"] is False:
  6965. self.file_opened.emit("project", self.project_filename)
  6966. self.file_saved.emit("project", self.project_filename)
  6967. self.set_ui_title(name=self.project_filename)
  6968. self.should_we_save = False
  6969. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6970. """
  6971. Callback for menu item File->Save Project As... Opens a file
  6972. chooser and saves the project to the given file via
  6973. ``self.save_project()``.
  6974. :param make_copy if to be create a copy of the project; boolean
  6975. :param use_thread: if to be run in a separate thread; boolean
  6976. :param quit_action: if to be followed by quiting the application; boolean
  6977. :return: None
  6978. """
  6979. self.defaults.report_usage("on_file_saveprojectas")
  6980. self.date = str(datetime.today()).rpartition('.')[0]
  6981. self.date = ''.join(c for c in self.date if c not in ':-')
  6982. self.date = self.date.replace(' ', '_')
  6983. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6984. try:
  6985. filename, _f = FCFileSaveDialog.get_saved_filename(
  6986. caption=_("Save Project As ..."),
  6987. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6988. proj=_("Project")),
  6989. filter=filter_
  6990. )
  6991. except TypeError:
  6992. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6993. filename = str(filename)
  6994. if filename == '':
  6995. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6996. return
  6997. if use_thread is True:
  6998. self.worker_task.emit({'fcn': self.save_project,
  6999. 'params': [filename, quit_action]})
  7000. else:
  7001. self.save_project(filename, quit_action)
  7002. # self.save_project(filename)
  7003. if self.defaults["global_open_style"] is False:
  7004. self.file_opened.emit("project", filename)
  7005. self.file_saved.emit("project", filename)
  7006. if not make_copy:
  7007. self.project_filename = filename
  7008. self.set_ui_title(name=self.project_filename)
  7009. self.should_we_save = False
  7010. def on_file_save_objects_pdf(self, use_thread=True):
  7011. self.date = str(datetime.today()).rpartition('.')[0]
  7012. self.date = ''.join(c for c in self.date if c not in ':-')
  7013. self.date = self.date.replace(' ', '_')
  7014. try:
  7015. obj_selection = self.collection.get_selected()
  7016. if len(obj_selection) == 1:
  7017. obj_name = str(obj_selection[0].options['name'])
  7018. else:
  7019. obj_name = _("FlatCAM objects print")
  7020. except AttributeError as err:
  7021. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7022. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7023. return
  7024. if not obj_selection:
  7025. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7026. return
  7027. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7028. try:
  7029. filename, _f = FCFileSaveDialog.get_saved_filename(
  7030. caption=_("Save Object as PDF ..."),
  7031. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7032. obj_name=obj_name,
  7033. date=self.date),
  7034. filter=filter_
  7035. )
  7036. except TypeError:
  7037. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7038. filename = str(filename)
  7039. if filename == '':
  7040. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7041. return
  7042. if use_thread is True:
  7043. proc = self.proc_container.new(_("Printing PDF ... Please wait."))
  7044. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7045. else:
  7046. self.save_pdf(filename, obj_selection)
  7047. # self.save_project(filename)
  7048. if self.defaults["global_open_style"] is False:
  7049. self.file_opened.emit("pdf", filename)
  7050. self.file_saved.emit("pdf", filename)
  7051. def save_pdf(self, file_name, obj_selection):
  7052. p_size = self.defaults['global_workspaceT']
  7053. orientation = self.defaults['global_workspace_orientation']
  7054. color = 'black'
  7055. transparency_level = 1.0
  7056. self.pagesize = {}
  7057. self.pagesize.update(
  7058. {
  7059. 'Bounds': None,
  7060. 'A0': (841 * mm, 1189 * mm),
  7061. 'A1': (594 * mm, 841 * mm),
  7062. 'A2': (420 * mm, 594 * mm),
  7063. 'A3': (297 * mm, 420 * mm),
  7064. 'A4': (210 * mm, 297 * mm),
  7065. 'A5': (148 * mm, 210 * mm),
  7066. 'A6': (105 * mm, 148 * mm),
  7067. 'A7': (74 * mm, 105 * mm),
  7068. 'A8': (52 * mm, 74 * mm),
  7069. 'A9': (37 * mm, 52 * mm),
  7070. 'A10': (26 * mm, 37 * mm),
  7071. 'B0': (1000 * mm, 1414 * mm),
  7072. 'B1': (707 * mm, 1000 * mm),
  7073. 'B2': (500 * mm, 707 * mm),
  7074. 'B3': (353 * mm, 500 * mm),
  7075. 'B4': (250 * mm, 353 * mm),
  7076. 'B5': (176 * mm, 250 * mm),
  7077. 'B6': (125 * mm, 176 * mm),
  7078. 'B7': (88 * mm, 125 * mm),
  7079. 'B8': (62 * mm, 88 * mm),
  7080. 'B9': (44 * mm, 62 * mm),
  7081. 'B10': (31 * mm, 44 * mm),
  7082. 'C0': (917 * mm, 1297 * mm),
  7083. 'C1': (648 * mm, 917 * mm),
  7084. 'C2': (458 * mm, 648 * mm),
  7085. 'C3': (324 * mm, 458 * mm),
  7086. 'C4': (229 * mm, 324 * mm),
  7087. 'C5': (162 * mm, 229 * mm),
  7088. 'C6': (114 * mm, 162 * mm),
  7089. 'C7': (81 * mm, 114 * mm),
  7090. 'C8': (57 * mm, 81 * mm),
  7091. 'C9': (40 * mm, 57 * mm),
  7092. 'C10': (28 * mm, 40 * mm),
  7093. # American paper sizes
  7094. 'LETTER': (8.5 * inch, 11 * inch),
  7095. 'LEGAL': (8.5 * inch, 14 * inch),
  7096. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7097. # From https://en.wikipedia.org/wiki/Paper_size
  7098. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7099. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7100. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7101. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7102. 'LEDGER': (17 * inch, 11 * inch),
  7103. }
  7104. )
  7105. exported_svg = []
  7106. for obj in obj_selection:
  7107. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7108. scale_factor_x=None, scale_factor_y=None,
  7109. skew_factor_x=None, skew_factor_y=None,
  7110. mirror=None)
  7111. if obj.kind.lower() == 'gerber':
  7112. # color = self.defaults["gerber_plot_fill"][:-2]
  7113. color = obj.fill_color[:-2]
  7114. elif obj.kind.lower() == 'excellon':
  7115. color = '#C40000'
  7116. elif obj.kind.lower() == 'geometry':
  7117. color = self.defaults["global_draw_color"]
  7118. # Change the attributes of the exported SVG
  7119. # We don't need stroke-width
  7120. # We set opacity to maximum
  7121. # We set the colour to WHITE
  7122. root = ET.fromstring(svg_obj)
  7123. for child in root:
  7124. child.set('fill', str(color))
  7125. child.set('opacity', str(transparency_level))
  7126. child.set('stroke', str(color))
  7127. exported_svg.append(ET.tostring(root))
  7128. xmin = Inf
  7129. ymin = Inf
  7130. xmax = -Inf
  7131. ymax = -Inf
  7132. for obj in obj_selection:
  7133. try:
  7134. gxmin, gymin, gxmax, gymax = obj.bounds()
  7135. xmin = min([xmin, gxmin])
  7136. ymin = min([ymin, gymin])
  7137. xmax = max([xmax, gxmax])
  7138. ymax = max([ymax, gymax])
  7139. except Exception as e:
  7140. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7141. # Determine bounding area for svg export
  7142. bounds = [xmin, ymin, xmax, ymax]
  7143. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7144. # This contain the measure units
  7145. uom = obj_selection[0].units.lower()
  7146. # Define a boundary around SVG of about 1.0mm (~39mils)
  7147. if uom in "mm":
  7148. boundary = 1.0
  7149. else:
  7150. boundary = 0.0393701
  7151. # Convert everything to strings for use in the xml doc
  7152. svgwidth = str(size[0] + (2 * boundary))
  7153. svgheight = str(size[1] + (2 * boundary))
  7154. minx = str(bounds[0] - boundary)
  7155. miny = str(bounds[1] + boundary + size[1])
  7156. # Add a SVG Header and footer to the svg output from shapely
  7157. # The transform flips the Y Axis so that everything renders
  7158. # properly within svg apps such as inkscape
  7159. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7160. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7161. svg_header += 'width="' + svgwidth + uom + '" '
  7162. svg_header += 'height="' + svgheight + uom + '" '
  7163. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7164. svg_header += '>'
  7165. svg_header += '<g transform="scale(1,-1)">'
  7166. svg_footer = '</g> </svg>'
  7167. svg_elem = str(svg_header)
  7168. for svg_item in exported_svg:
  7169. svg_elem += str(svg_item)
  7170. svg_elem += str(svg_footer)
  7171. # Parse the xml through a xml parser just to add line feeds
  7172. # and to make it look more pretty for the output
  7173. doc = parse_xml_string(svg_elem)
  7174. doc_final = doc.toprettyxml()
  7175. try:
  7176. if self.defaults['units'].upper() == 'IN':
  7177. unit = inch
  7178. else:
  7179. unit = mm
  7180. doc_final = StringIO(doc_final)
  7181. drawing = svg2rlg(doc_final)
  7182. if p_size == 'Bounds':
  7183. renderPDF.drawToFile(drawing, file_name)
  7184. else:
  7185. if orientation == 'p':
  7186. page_size = portrait(self.pagesize[p_size])
  7187. else:
  7188. page_size = landscape(self.pagesize[p_size])
  7189. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7190. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7191. renderPDF.draw(drawing, my_canvas, 0, 0)
  7192. my_canvas.save()
  7193. except Exception as e:
  7194. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7195. return 'fail'
  7196. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7197. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7198. """
  7199. Exports a Geometry Object to an SVG file.
  7200. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7201. :param filename: Path to the SVG file to save to.
  7202. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7203. :return:
  7204. """
  7205. self.defaults.report_usage("export_svg()")
  7206. if filename is None:
  7207. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7208. is not None else self.defaults["global_last_folder"]
  7209. self.log.debug("export_svg()")
  7210. try:
  7211. obj = self.collection.get_by_name(str(obj_name))
  7212. except Exception:
  7213. # TODO: The return behavior has not been established... should raise exception?
  7214. return "Could not retrieve object: %s" % obj_name
  7215. with self.proc_container.new(_("Exporting SVG")) as proc:
  7216. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7217. # Determine bounding area for svg export
  7218. bounds = obj.bounds()
  7219. size = obj.size()
  7220. # Convert everything to strings for use in the xml doc
  7221. svgwidth = str(size[0])
  7222. svgheight = str(size[1])
  7223. minx = str(bounds[0])
  7224. miny = str(bounds[1] - size[1])
  7225. uom = obj.units.lower()
  7226. # Add a SVG Header and footer to the svg output from shapely
  7227. # The transform flips the Y Axis so that everything renders
  7228. # properly within svg apps such as inkscape
  7229. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7230. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7231. svg_header += 'width="' + svgwidth + uom + '" '
  7232. svg_header += 'height="' + svgheight + uom + '" '
  7233. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7234. svg_header += '<g transform="scale(1,-1)">'
  7235. svg_footer = '</g> </svg>'
  7236. svg_elem = svg_header + exported_svg + svg_footer
  7237. # Parse the xml through a xml parser just to add line feeds
  7238. # and to make it look more pretty for the output
  7239. svgcode = parse_xml_string(svg_elem)
  7240. svgcode = svgcode.toprettyxml()
  7241. try:
  7242. with open(filename, 'w') as fp:
  7243. fp.write(svgcode)
  7244. except PermissionError:
  7245. self.inform.emit('[WARNING] %s' %
  7246. _("Permission denied, saving not possible.\n"
  7247. "Most likely another app is holding the file open and not accessible."))
  7248. return 'fail'
  7249. if self.defaults["global_open_style"] is False:
  7250. self.file_opened.emit("SVG", filename)
  7251. self.file_saved.emit("SVG", filename)
  7252. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7253. def save_source_file(self, obj_name, filename, use_thread=True):
  7254. """
  7255. Exports a FlatCAM Object to an Gerber/Excellon file.
  7256. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7257. :param filename: Path to the Gerber file to save to.
  7258. :param use_thread: if to be run in a separate thread
  7259. :return:
  7260. """
  7261. self.defaults.report_usage("save source file()")
  7262. if filename is None:
  7263. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7264. is not None else self.defaults["global_last_folder"]
  7265. self.log.debug("save source file()")
  7266. obj = self.collection.get_by_name(obj_name)
  7267. file_string = StringIO(obj.source_file)
  7268. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7269. if file_string.getvalue() == '':
  7270. self.inform.emit('[ERROR_NOTCL] %s' %
  7271. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7272. return 'fail'
  7273. try:
  7274. with open(filename, 'w') as file:
  7275. file.writelines('G04*\n')
  7276. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7277. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7278. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7279. file.writelines('G04 Created on : %s*\n' % time_string)
  7280. for line in file_string:
  7281. file.writelines(line)
  7282. except PermissionError:
  7283. self.inform.emit('[WARNING] %s' %
  7284. _("Permission denied, saving not possible.\n"
  7285. "Most likely another app is holding the file open and not accessible."))
  7286. return 'fail'
  7287. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7288. """
  7289. Exports a Excellon Object to an Excellon file.
  7290. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7291. :param filename: Path to the Excellon file to save to.
  7292. :param local_use:
  7293. :param use_thread: if to be run in a separate thread
  7294. :return:
  7295. """
  7296. self.defaults.report_usage("export_excellon()")
  7297. if filename is None:
  7298. if self.defaults["global_last_save_folder"]:
  7299. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7300. else:
  7301. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7302. self.log.debug("export_excellon()")
  7303. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7304. self.defaults["excellon_exp_decimals"]
  7305. )
  7306. if local_use is None:
  7307. try:
  7308. obj = self.collection.get_by_name(str(obj_name))
  7309. except Exception:
  7310. return "Could not retrieve object: %s" % obj_name
  7311. else:
  7312. obj = local_use
  7313. if not isinstance(obj, ExcellonObject):
  7314. self.inform.emit('[ERROR_NOTCL] %s' %
  7315. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7316. return
  7317. # updated units
  7318. eunits = self.defaults["excellon_exp_units"]
  7319. ewhole = self.defaults["excellon_exp_integer"]
  7320. efract = self.defaults["excellon_exp_decimals"]
  7321. ezeros = self.defaults["excellon_exp_zeros"]
  7322. eformat = self.defaults["excellon_exp_format"]
  7323. slot_type = self.defaults["excellon_exp_slot_type"]
  7324. fc_units = self.defaults['units'].upper()
  7325. if fc_units == 'MM':
  7326. factor = 1 if eunits == 'METRIC' else 0.03937
  7327. else:
  7328. factor = 25.4 if eunits == 'METRIC' else 1
  7329. def make_excellon():
  7330. try:
  7331. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7332. header = 'M48\n'
  7333. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7334. (str(self.version), str(self.version_date))
  7335. header += ';Filename: %s' % str(obj_name) + '\n'
  7336. header += ';Created on : %s' % time_str + '\n'
  7337. if eformat == 'dec':
  7338. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7339. header += eunits + '\n'
  7340. for tool in obj.tools:
  7341. if eunits == 'METRIC':
  7342. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7343. tool=str(tool),
  7344. dec=2)
  7345. else:
  7346. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7347. tool=str(tool),
  7348. dec=4)
  7349. else:
  7350. if ezeros == 'LZ':
  7351. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7352. form='ndec', e_zeros='LZ', factor=factor,
  7353. slot_type=slot_type)
  7354. header += '%s,%s\n' % (eunits, 'LZ')
  7355. header += format_exc
  7356. for tool in obj.tools:
  7357. if eunits == 'METRIC':
  7358. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7359. tool=str(tool),
  7360. dec=2)
  7361. else:
  7362. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7363. tool=str(tool),
  7364. dec=4)
  7365. else:
  7366. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7367. form='ndec', e_zeros='TZ', factor=factor,
  7368. slot_type=slot_type)
  7369. header += '%s,%s\n' % (eunits, 'TZ')
  7370. header += format_exc
  7371. for tool in obj.tools:
  7372. if eunits == 'METRIC':
  7373. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7374. tool=str(tool),
  7375. dec=2)
  7376. else:
  7377. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7378. tool=str(tool),
  7379. dec=4)
  7380. header += '%\n'
  7381. footer = 'M30\n'
  7382. exported_excellon = header
  7383. exported_excellon += excellon_code
  7384. exported_excellon += footer
  7385. if local_use is None:
  7386. try:
  7387. with open(filename, 'w') as fp:
  7388. fp.write(exported_excellon)
  7389. except PermissionError:
  7390. self.inform.emit('[WARNING] %s' %
  7391. _("Permission denied, saving not possible.\n"
  7392. "Most likely another app is holding the file open and not accessible."))
  7393. return 'fail'
  7394. if self.defaults["global_open_style"] is False:
  7395. self.file_opened.emit("Excellon", filename)
  7396. self.file_saved.emit("Excellon", filename)
  7397. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7398. else:
  7399. return exported_excellon
  7400. except Exception as e:
  7401. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7402. return 'fail'
  7403. if use_thread is True:
  7404. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7405. def job_thread_exc(app_obj):
  7406. ret = make_excellon()
  7407. if ret == 'fail':
  7408. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7409. return
  7410. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7411. else:
  7412. eret = make_excellon()
  7413. if eret == 'fail':
  7414. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7415. return 'fail'
  7416. if local_use is not None:
  7417. return eret
  7418. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7419. """
  7420. Exports a Gerber Object to an Gerber file.
  7421. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7422. :param filename: Path to the Gerber file to save to.
  7423. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7424. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7425. :param use_thread: if to be run in a separate thread
  7426. :return:
  7427. """
  7428. self.defaults.report_usage("export_gerber()")
  7429. if filename is None:
  7430. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7431. is not None else self.defaults["global_last_folder"]
  7432. self.log.debug("export_gerber()")
  7433. if local_use is None:
  7434. try:
  7435. obj = self.collection.get_by_name(str(obj_name))
  7436. except Exception:
  7437. return "Could not retrieve object: %s" % obj_name
  7438. else:
  7439. obj = local_use
  7440. # updated units
  7441. gunits = self.defaults["gerber_exp_units"]
  7442. gwhole = self.defaults["gerber_exp_integer"]
  7443. gfract = self.defaults["gerber_exp_decimals"]
  7444. gzeros = self.defaults["gerber_exp_zeros"]
  7445. fc_units = self.defaults['units'].upper()
  7446. if fc_units == 'MM':
  7447. factor = 1 if gunits == 'MM' else 0.03937
  7448. else:
  7449. factor = 25.4 if gunits == 'MM' else 1
  7450. def make_gerber():
  7451. try:
  7452. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7453. header = 'G04*\n'
  7454. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7455. (str(self.version), str(self.version_date))
  7456. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7457. header += 'G04 Created on : %s*' % time_str + '\n'
  7458. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7459. header += "%MO{units}*%\n".format(units=gunits)
  7460. for apid in obj.apertures:
  7461. if obj.apertures[apid]['type'] == 'C':
  7462. header += "%ADD{apid}{type},{size}*%\n".format(
  7463. apid=str(apid),
  7464. type='C',
  7465. size=(factor * obj.apertures[apid]['size'])
  7466. )
  7467. elif obj.apertures[apid]['type'] == 'R':
  7468. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7469. apid=str(apid),
  7470. type='R',
  7471. width=(factor * obj.apertures[apid]['width']),
  7472. height=(factor * obj.apertures[apid]['height'])
  7473. )
  7474. elif obj.apertures[apid]['type'] == 'O':
  7475. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7476. apid=str(apid),
  7477. type='O',
  7478. width=(factor * obj.apertures[apid]['width']),
  7479. height=(factor * obj.apertures[apid]['height'])
  7480. )
  7481. header += '\n'
  7482. # obsolete units but some software may need it
  7483. if gunits == 'IN':
  7484. header += 'G70*\n'
  7485. else:
  7486. header += 'G71*\n'
  7487. # Absolute Mode
  7488. header += 'G90*\n'
  7489. header += 'G01*\n'
  7490. # positive polarity
  7491. header += '%LPD*%\n'
  7492. footer = 'M02*\n'
  7493. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7494. exported_gerber = header
  7495. exported_gerber += gerber_code
  7496. exported_gerber += footer
  7497. if local_use is None:
  7498. try:
  7499. with open(filename, 'w') as fp:
  7500. fp.write(exported_gerber)
  7501. except PermissionError:
  7502. self.inform.emit('[WARNING] %s' %
  7503. _("Permission denied, saving not possible.\n"
  7504. "Most likely another app is holding the file open and not accessible."))
  7505. return 'fail'
  7506. if self.defaults["global_open_style"] is False:
  7507. self.file_opened.emit("Gerber", filename)
  7508. self.file_saved.emit("Gerber", filename)
  7509. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7510. else:
  7511. return exported_gerber
  7512. except Exception as e:
  7513. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7514. return 'fail'
  7515. if use_thread is True:
  7516. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7517. def job_thread_grb(app_obj):
  7518. ret = make_gerber()
  7519. if ret == 'fail':
  7520. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7521. return
  7522. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7523. else:
  7524. gret = make_gerber()
  7525. if gret == 'fail':
  7526. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7527. return 'fail'
  7528. if local_use is not None:
  7529. return gret
  7530. def export_dxf(self, obj_name, filename, use_thread=True):
  7531. """
  7532. Exports a Geometry Object to an DXF file.
  7533. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7534. :param filename: Path to the DXF file to save to.
  7535. :param use_thread: if to be run in a separate thread
  7536. :return:
  7537. """
  7538. self.defaults.report_usage("export_dxf()")
  7539. if filename is None:
  7540. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7541. is not None else self.defaults["global_last_folder"]
  7542. self.log.debug("export_dxf()")
  7543. try:
  7544. obj = self.collection.get_by_name(str(obj_name))
  7545. except Exception:
  7546. # TODO: The return behavior has not been established... should raise exception?
  7547. return "Could not retrieve object: %s" % obj_name
  7548. def make_dxf():
  7549. try:
  7550. dxf_code = obj.export_dxf()
  7551. dxf_code.saveas(filename)
  7552. if self.defaults["global_open_style"] is False:
  7553. self.file_opened.emit("DXF", filename)
  7554. self.file_saved.emit("DXF", filename)
  7555. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7556. except Exception:
  7557. return 'fail'
  7558. if use_thread is True:
  7559. with self.proc_container.new(_("Exporting DXF")) as proc:
  7560. def job_thread_exc(app_obj):
  7561. ret_dxf_val = make_dxf()
  7562. if ret_dxf_val == 'fail':
  7563. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7564. return
  7565. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7566. else:
  7567. ret = make_dxf()
  7568. if ret == 'fail':
  7569. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7570. return
  7571. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7572. """
  7573. Adds a new Geometry Object to the projects and populates
  7574. it with shapes extracted from the SVG file.
  7575. :param filename: Path to the SVG file.
  7576. :param geo_type: Type of FlatCAM object that will be created from SVG
  7577. :param outname:
  7578. :return:
  7579. """
  7580. self.defaults.report_usage("import_svg()")
  7581. log.debug("App.import_svg()")
  7582. obj_type = ""
  7583. if geo_type is None or geo_type == "geometry":
  7584. obj_type = "geometry"
  7585. elif geo_type == "gerber":
  7586. obj_type = "gerber"
  7587. else:
  7588. self.inform.emit('[ERROR_NOTCL] %s' %
  7589. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7590. return
  7591. units = self.defaults['units'].upper()
  7592. def obj_init(geo_obj, app_obj):
  7593. geo_obj.import_svg(filename, obj_type, units=units)
  7594. geo_obj.multigeo = False
  7595. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7596. with self.proc_container.new(_("Importing SVG")) as proc:
  7597. # Object name
  7598. name = outname or filename.split('/')[-1].split('\\')[-1]
  7599. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7600. if ret == 'fail':
  7601. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7602. return 'fail'
  7603. # Register recent file
  7604. self.file_opened.emit("svg", filename)
  7605. # GUI feedback
  7606. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7607. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7608. """
  7609. Adds a new Geometry Object to the projects and populates
  7610. it with shapes extracted from the DXF file.
  7611. :param filename: Path to the DXF file.
  7612. :param geo_type: Type of FlatCAM object that will be created from DXF
  7613. :param outname: Name for the imported Geometry
  7614. :return:
  7615. """
  7616. self.defaults.report_usage("import_dxf()")
  7617. obj_type = ""
  7618. if geo_type is None or geo_type == "geometry":
  7619. obj_type = "geometry"
  7620. elif geo_type == "gerber":
  7621. obj_type = geo_type
  7622. else:
  7623. self.inform.emit('[ERROR_NOTCL] %s' %
  7624. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7625. return
  7626. units = self.defaults['units'].upper()
  7627. def obj_init(geo_obj, app_obj):
  7628. geo_obj.import_dxf(filename, obj_type, units=units)
  7629. geo_obj.multigeo = False
  7630. with self.proc_container.new(_("Importing DXF")):
  7631. # Object name
  7632. name = outname or filename.split('/')[-1].split('\\')[-1]
  7633. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7634. if ret == 'fail':
  7635. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7636. return 'fail'
  7637. # Register recent file
  7638. self.file_opened.emit("dxf", filename)
  7639. # GUI feedback
  7640. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7641. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7642. """
  7643. Opens a Gerber file, parses it and creates a new object for
  7644. it in the program. Thread-safe.
  7645. :param outname: Name of the resulting object. None causes the
  7646. name to be that of the file. Str.
  7647. :param filename: Gerber file filename
  7648. :type filename: str
  7649. :param plot: boolean, to plot or not the resulting object
  7650. :param from_tcl: True if run from Tcl Shell
  7651. :return: None
  7652. """
  7653. # How the object should be initialized
  7654. def obj_init(gerber_obj, app_obj):
  7655. assert isinstance(gerber_obj, GerberObject), \
  7656. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7657. # Opening the file happens here
  7658. try:
  7659. gerber_obj.parse_file(filename)
  7660. except IOError:
  7661. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7662. return "fail"
  7663. except ParseError as err:
  7664. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7665. app_obj.log.error(str(err))
  7666. return "fail"
  7667. except Exception as e:
  7668. log.debug("App.open_gerber() --> %s" % str(e))
  7669. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7670. msg += traceback.format_exc()
  7671. app_obj.inform.emit(msg)
  7672. return "fail"
  7673. if gerber_obj.is_empty():
  7674. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7675. _("Object is not Gerber file or empty. Aborting object creation."))
  7676. return "fail"
  7677. App.log.debug("open_gerber()")
  7678. with self.proc_container.new(_("Opening Gerber")):
  7679. # Object name
  7680. name = outname or filename.split('/')[-1].split('\\')[-1]
  7681. # # ## Object creation # ##
  7682. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7683. if ret_val == 'fail':
  7684. if from_tcl:
  7685. filename = self.defaults['global_tcl_path'] + '/' + name
  7686. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7687. if ret_val == 'fail':
  7688. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7689. return 'fail'
  7690. # Register recent file
  7691. self.file_opened.emit("gerber", filename)
  7692. # GUI feedback
  7693. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7694. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7695. """
  7696. Opens an Excellon file, parses it and creates a new object for
  7697. it in the program. Thread-safe.
  7698. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7699. :param filename: Excellon file filename
  7700. :type filename: str
  7701. :param plot: boolean, to plot or not the resulting object
  7702. :param from_tcl: True if run from Tcl Shell
  7703. :return: None
  7704. """
  7705. App.log.debug("open_excellon()")
  7706. # How the object should be initialized
  7707. def obj_init(excellon_obj, app_obj):
  7708. try:
  7709. ret = excellon_obj.parse_file(filename=filename)
  7710. if ret == "fail":
  7711. log.debug("Excellon parsing failed.")
  7712. self.inform.emit('[ERROR_NOTCL] %s' %
  7713. _("This is not Excellon file."))
  7714. return "fail"
  7715. except IOError:
  7716. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7717. (_("Cannot open file"), filename))
  7718. log.debug("Could not open Excellon object.")
  7719. return "fail"
  7720. except Exception:
  7721. msg = '[ERROR_NOTCL] %s' % \
  7722. _("An internal error has occurred. See shell.\n")
  7723. msg += traceback.format_exc()
  7724. app_obj.inform.emit(msg)
  7725. return "fail"
  7726. ret = excellon_obj.create_geometry()
  7727. if ret == 'fail':
  7728. log.debug("Could not create geometry for Excellon object.")
  7729. return "fail"
  7730. for tool in excellon_obj.tools:
  7731. if excellon_obj.tools[tool]['solid_geometry']:
  7732. return
  7733. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7734. return "fail"
  7735. with self.proc_container.new(_("Opening Excellon.")):
  7736. # Object name
  7737. name = outname or filename.split('/')[-1].split('\\')[-1]
  7738. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7739. if ret_val == 'fail':
  7740. if from_tcl:
  7741. filename = self.defaults['global_tcl_path'] + '/' + name
  7742. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7743. if ret_val == 'fail':
  7744. self.inform.emit('[ERROR_NOTCL] %s' %
  7745. _('Open Excellon file failed. Probable not an Excellon file.'))
  7746. return
  7747. # Register recent file
  7748. self.file_opened.emit("excellon", filename)
  7749. # GUI feedback
  7750. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7751. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7752. """
  7753. Opens a G-gcode file, parses it and creates a new object for
  7754. it in the program. Thread-safe.
  7755. :param filename: G-code file filename
  7756. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7757. :param force_parsing:
  7758. :param plot: If True plot the object on canvas
  7759. :param from_tcl: True if run from Tcl Shell
  7760. :return: None
  7761. """
  7762. App.log.debug("open_gcode()")
  7763. # How the object should be initialized
  7764. def obj_init(job_obj, app_obj_):
  7765. """
  7766. :param job_obj: the resulting object
  7767. :type app_obj_: App
  7768. """
  7769. assert isinstance(app_obj_, App), \
  7770. "Initializer expected App, got %s" % type(app_obj_)
  7771. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7772. try:
  7773. f = open(filename)
  7774. gcode = f.read()
  7775. f.close()
  7776. except IOError:
  7777. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7778. return "fail"
  7779. job_obj.gcode = gcode
  7780. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7781. if gcode_ret == "fail":
  7782. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7783. return "fail"
  7784. job_obj.create_geometry()
  7785. with self.proc_container.new(_("Opening G-Code.")):
  7786. # Object name
  7787. name = outname or filename.split('/')[-1].split('\\')[-1]
  7788. # New object creation and file processing
  7789. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7790. if ret_val == 'fail':
  7791. if from_tcl:
  7792. filename = self.defaults['global_tcl_path'] + '/' + name
  7793. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7794. if ret_val == 'fail':
  7795. self.inform.emit('[ERROR_NOTCL] %s' %
  7796. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7797. "Try to load it from File menu.\n "
  7798. "Attempting to create a FlatCAM CNCJob Object from "
  7799. "G-Code file failed during processing"))
  7800. return "fail"
  7801. # Register recent file
  7802. self.file_opened.emit("cncjob", filename)
  7803. # GUI feedback
  7804. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7805. def open_hpgl2(self, filename, outname=None):
  7806. """
  7807. Opens a HPGL2 file, parses it and creates a new object for
  7808. it in the program. Thread-safe.
  7809. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7810. :param filename: HPGL2 file filename
  7811. :return: None
  7812. """
  7813. filename = filename
  7814. # How the object should be initialized
  7815. def obj_init(geo_obj, app_obj):
  7816. assert isinstance(geo_obj, GeometryObject), \
  7817. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7818. # Opening the file happens here
  7819. obj = HPGL2(self)
  7820. try:
  7821. HPGL2.parse_file(obj, filename)
  7822. except IOError:
  7823. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7824. return "fail"
  7825. except ParseError as err:
  7826. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7827. app_obj.log.error(str(err))
  7828. return "fail"
  7829. except Exception as e:
  7830. log.debug("App.open_hpgl2() --> %s" % str(e))
  7831. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7832. msg += traceback.format_exc()
  7833. app_obj.inform.emit(msg)
  7834. return "fail"
  7835. geo_obj.multigeo = True
  7836. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7837. geo_obj.tools = deepcopy(obj.tools)
  7838. geo_obj.source_file = deepcopy(obj.source_file)
  7839. del obj
  7840. if not geo_obj.solid_geometry:
  7841. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7842. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7843. return "fail"
  7844. App.log.debug("open_hpgl2()")
  7845. with self.proc_container.new(_("Opening HPGL2")) as proc:
  7846. # Object name
  7847. name = outname or filename.split('/')[-1].split('\\')[-1]
  7848. # # ## Object creation # ##
  7849. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7850. if ret == 'fail':
  7851. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7852. return 'fail'
  7853. # Register recent file
  7854. self.file_opened.emit("geometry", filename)
  7855. # GUI feedback
  7856. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7857. def open_script(self, filename, outname=None, silent=False):
  7858. """
  7859. Opens a Script file, parses it and creates a new object for
  7860. it in the program. Thread-safe.
  7861. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7862. :param filename: Script file filename
  7863. :return: None
  7864. """
  7865. App.log.debug("open_script()")
  7866. with self.proc_container.new(_("Opening TCL Script...")):
  7867. try:
  7868. with open(filename, "r") as opened_script:
  7869. script_content = opened_script.readlines()
  7870. script_content = ''.join(script_content)
  7871. if silent is False:
  7872. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7873. except Exception as e:
  7874. log.debug("App.open_script() -> %s" % str(e))
  7875. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  7876. return
  7877. # Object name
  7878. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7879. # New object creation and file processing
  7880. self.on_filenewscript(name=script_name, text=script_content)
  7881. # Register recent file
  7882. self.file_opened.emit("script", filename)
  7883. # GUI feedback
  7884. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7885. def open_config_file(self, filename, run_from_arg=None):
  7886. """
  7887. Loads a config file from the specified file.
  7888. :param filename: Name of the file from which to load.
  7889. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7890. :return: None
  7891. """
  7892. App.log.debug("Opening config file: " + filename)
  7893. if run_from_arg:
  7894. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7895. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7896. _("Opening FlatCAM Config file.")),
  7897. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7898. color=QtGui.QColor("gray"))
  7899. # # add the tab if it was closed
  7900. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7901. # # first clear previous text in text editor (if any)
  7902. # self.ui.text_editor_tab.code_editor.clear()
  7903. #
  7904. # # Switch plot_area to CNCJob tab
  7905. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7906. # close the Code editor if already open
  7907. if self.toggle_codeeditor:
  7908. self.on_toggle_code_editor()
  7909. self.on_toggle_code_editor()
  7910. try:
  7911. if filename:
  7912. f = QtCore.QFile(filename)
  7913. if f.open(QtCore.QIODevice.ReadOnly):
  7914. stream = QtCore.QTextStream(f)
  7915. code_edited = stream.readAll()
  7916. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7917. f.close()
  7918. except IOError:
  7919. App.log.error("Failed to open config file: %s" % filename)
  7920. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7921. (_("Failed to open config file"), filename))
  7922. return
  7923. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7924. """
  7925. Loads a project from the specified file.
  7926. 1) Loads and parses file
  7927. 2) Registers the file as recently opened.
  7928. 3) Calls on_file_new()
  7929. 4) Updates options
  7930. 5) Calls new_object() with the object's from_dict() as init method.
  7931. 6) Calls plot_all() if plot=True
  7932. :param filename: Name of the file from which to load.
  7933. :param run_from_arg: True if run for arguments
  7934. :param plot: If True plot all objects in the project
  7935. :param cli: Run from command line
  7936. :param from_tcl: True if run from Tcl Sehll
  7937. :return: None
  7938. """
  7939. App.log.debug("Opening project: " + filename)
  7940. # block autosaving while a project is loaded
  7941. self.block_autosave = True
  7942. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7943. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7944. if cli is None:
  7945. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7946. if run_from_arg:
  7947. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7948. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7949. _("Opening FlatCAM Project file.")),
  7950. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7951. color=QtGui.QColor("gray"))
  7952. # Open and parse an uncompressed Project file
  7953. try:
  7954. f = open(filename, 'r')
  7955. except IOError:
  7956. if from_tcl:
  7957. name = filename.split('/')[-1].split('\\')[-1]
  7958. filename = self.defaults['global_tcl_path'] + '/' + name
  7959. try:
  7960. f = open(filename, 'r')
  7961. except IOError:
  7962. log.error("Failed to open project file: %s" % filename)
  7963. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7964. return
  7965. else:
  7966. log.error("Failed to open project file: %s" % filename)
  7967. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7968. return
  7969. try:
  7970. d = json.load(f, object_hook=dict2obj)
  7971. except Exception as e:
  7972. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7973. (filename, str(e)))
  7974. f.close()
  7975. # Open and parse a compressed Project file
  7976. try:
  7977. with lzma.open(filename) as f:
  7978. file_content = f.read().decode('utf-8')
  7979. d = json.loads(file_content, object_hook=dict2obj)
  7980. except Exception as e:
  7981. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7982. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7983. (_("Failed to open project file"), filename))
  7984. return
  7985. # Clear the current project
  7986. # # NOT THREAD SAFE # ##
  7987. if run_from_arg is True:
  7988. pass
  7989. elif cli is True:
  7990. self.delete_selection_shape()
  7991. else:
  7992. self.on_file_new()
  7993. # Project options
  7994. self.options.update(d['options'])
  7995. self.project_filename = filename
  7996. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7997. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7998. if cli is None:
  7999. self.set_screen_units(self.options["units"])
  8000. # Re create objects
  8001. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8002. for obj in d['objs']:
  8003. try:
  8004. def obj_init(obj_inst, app_inst):
  8005. obj_inst.from_dict(obj)
  8006. App.log.debug("Recreating from opened project an %s object: %s" %
  8007. (obj['kind'].capitalize(), obj['options']['name']))
  8008. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8009. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8010. if cli is None:
  8011. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8012. obj['kind'].upper(),
  8013. obj['options']['name']
  8014. )
  8015. )
  8016. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8017. except Exception as e:
  8018. print('App.open_project() --> ' + str(e))
  8019. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8020. self.should_we_save = False
  8021. self.file_opened.emit("project", filename)
  8022. # restore autosaving after a project was loaded
  8023. self.block_autosave = False
  8024. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8025. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8026. if cli is None:
  8027. self.set_ui_title(name=self.project_filename)
  8028. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8029. def plot_all(self, fit_view=True, use_thread=True):
  8030. """
  8031. Re-generates all plots from all objects.
  8032. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8033. :param use_thread: if True will use threading for plotting the objects
  8034. :return: None
  8035. """
  8036. self.log.debug("Plot_all()")
  8037. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8038. for plot_obj in self.collection.get_list():
  8039. def worker_task(obj):
  8040. with self.proc_container.new("Plotting"):
  8041. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8042. if fit_view is True:
  8043. self.object_plotted.emit(obj)
  8044. if use_thread is True:
  8045. # Send to worker
  8046. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8047. else:
  8048. worker_task(plot_obj)
  8049. def register_folder(self, filename):
  8050. """
  8051. Register the last folder used by the app to open something
  8052. :param filename: the last folder is extracted from the filename
  8053. :return: None
  8054. """
  8055. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8056. def register_save_folder(self, filename):
  8057. """
  8058. Register the last folder used by the app to save something
  8059. :param filename: the last folder is extracted from the filename
  8060. :return: None
  8061. """
  8062. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8063. # def set_progress_bar(self, percentage, text=""):
  8064. # """
  8065. # Set a progress bar to a value (percentage)
  8066. #
  8067. # :param percentage: Value set to the progressbar
  8068. # :param text: Not used
  8069. # :return: None
  8070. # """
  8071. # self.ui.progress_bar.setValue(int(percentage))
  8072. def setup_recent_items(self):
  8073. """
  8074. Setup a dictionary with the recent files accessed, organized by type
  8075. :return:
  8076. """
  8077. icons = {
  8078. "gerber": self.resource_location + "/flatcam_icon16.png",
  8079. "excellon": self.resource_location + "/drill16.png",
  8080. 'geometry': self.resource_location + "/geometry16.png",
  8081. "cncjob": self.resource_location + "/cnc16.png",
  8082. "script": self.resource_location + "/script_new24.png",
  8083. "document": self.resource_location + "/notes16_1.png",
  8084. "project": self.resource_location + "/project16.png",
  8085. "svg": self.resource_location + "/geometry16.png",
  8086. "dxf": self.resource_location + "/dxf16.png",
  8087. "pdf": self.resource_location + "/pdf32.png",
  8088. "image": self.resource_location + "/image16.png"
  8089. }
  8090. try:
  8091. image_opener = self.image_tool.import_image
  8092. except AttributeError:
  8093. image_opener = None
  8094. openers = {
  8095. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8096. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8097. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8098. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8099. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8100. "document": None,
  8101. 'project': self.open_project,
  8102. 'svg': self.import_svg,
  8103. 'dxf': self.import_dxf,
  8104. 'image': image_opener,
  8105. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8106. }
  8107. # Open recent file for files
  8108. try:
  8109. f = open(self.data_path + '/recent.json')
  8110. except IOError:
  8111. App.log.error("Failed to load recent item list.")
  8112. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8113. return
  8114. try:
  8115. self.recent = json.load(f)
  8116. except json.errors.JSONDecodeError:
  8117. App.log.error("Failed to parse recent item list.")
  8118. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8119. f.close()
  8120. return
  8121. f.close()
  8122. # Open recent file for projects
  8123. try:
  8124. fp = open(self.data_path + '/recent_projects.json')
  8125. except IOError:
  8126. App.log.error("Failed to load recent project item list.")
  8127. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8128. return
  8129. try:
  8130. self.recent_projects = json.load(fp)
  8131. except json.errors.JSONDecodeError:
  8132. App.log.error("Failed to parse recent project item list.")
  8133. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8134. fp.close()
  8135. return
  8136. fp.close()
  8137. # Closure needed to create callbacks in a loop.
  8138. # Otherwise late binding occurs.
  8139. def make_callback(func, fname):
  8140. def opener():
  8141. func(fname)
  8142. return opener
  8143. def reset_recent_files():
  8144. # Reset menu
  8145. self.ui.recent.clear()
  8146. self.recent = []
  8147. try:
  8148. ff = open(self.data_path + '/recent.json', 'w')
  8149. except IOError:
  8150. App.log.error("Failed to open recent items file for writing.")
  8151. return
  8152. json.dump(self.recent, ff)
  8153. def reset_recent_projects():
  8154. # Reset menu
  8155. self.ui.recent_projects.clear()
  8156. self.recent_projects = []
  8157. try:
  8158. frp = open(self.data_path + '/recent_projects.json', 'w')
  8159. except IOError:
  8160. App.log.error("Failed to open recent projects items file for writing.")
  8161. return
  8162. json.dump(self.recent, frp)
  8163. # Reset menu
  8164. self.ui.recent.clear()
  8165. self.ui.recent_projects.clear()
  8166. # Create menu items for projects
  8167. for recent in self.recent_projects:
  8168. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8169. if recent['kind'] == 'project':
  8170. try:
  8171. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8172. # Attach callback
  8173. o = make_callback(openers[recent["kind"]], recent['filename'])
  8174. action.triggered.connect(o)
  8175. self.ui.recent_projects.addAction(action)
  8176. except KeyError:
  8177. App.log.error("Unsupported file type: %s" % recent["kind"])
  8178. # Last action in Recent Files menu is one that Clear the content
  8179. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8180. (_("Clear Recent projects")), self)
  8181. clear_action_proj.triggered.connect(reset_recent_projects)
  8182. self.ui.recent_projects.addSeparator()
  8183. self.ui.recent_projects.addAction(clear_action_proj)
  8184. # Create menu items for files
  8185. for recent in self.recent:
  8186. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8187. if recent['kind'] != 'project':
  8188. try:
  8189. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8190. # Attach callback
  8191. o = make_callback(openers[recent["kind"]], recent['filename'])
  8192. action.triggered.connect(o)
  8193. self.ui.recent.addAction(action)
  8194. except KeyError:
  8195. App.log.error("Unsupported file type: %s" % recent["kind"])
  8196. # Last action in Recent Files menu is one that Clear the content
  8197. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8198. (_("Clear Recent files")), self)
  8199. clear_action.triggered.connect(reset_recent_files)
  8200. self.ui.recent.addSeparator()
  8201. self.ui.recent.addAction(clear_action)
  8202. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8203. # self.ui.menufilerecent.set_submenu(recent_menu)
  8204. # recent_menu.show_all()
  8205. # self.ui.recent.show()
  8206. self.log.debug("Recent items list has been populated.")
  8207. def setup_component_editor(self):
  8208. """
  8209. Default text for the Selected tab when is not taken by the Object UI.
  8210. :return:
  8211. """
  8212. # label = QtWidgets.QLabel("Choose an item from Project")
  8213. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8214. sel_title = QtWidgets.QTextEdit(
  8215. _('<b>Shortcut Key List</b>'))
  8216. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8217. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8218. f_settings = QSettings("Open Source", "FlatCAM")
  8219. if f_settings.contains("notebook_font_size"):
  8220. fsize = f_settings.value('notebook_font_size', type=int)
  8221. else:
  8222. fsize = 12
  8223. tsize = fsize + int(fsize / 2)
  8224. # selected_text = (_('''
  8225. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8226. # </p>
  8227. #
  8228. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8229. # The normal flow when working in FlatCAM is the following:</span></p>
  8230. #
  8231. # <ol>
  8232. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8233. # file into
  8234. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8235. # even dragging and dropping the files on the GUI.<br />
  8236. # <br />
  8237. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8238. # drop of the
  8239. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8240. # &nbsp;</li>
  8241. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8242. # and then
  8243. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8244. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8245. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8246. # <br />
  8247. # If the selection of the object is done on the canvas by single click instead, and the
  8248. # <strong>SELECTED TAB</strong>
  8249. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8250. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8251. # it even if it was out of focus.<br />
  8252. # <br />
  8253. # You can change the parameters in this screen and the flow direction is like this:<br />
  8254. # <br />
  8255. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8256. # <strong> Geometry Object
  8257. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8258. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8259. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8260. # </ol>
  8261. #
  8262. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8263. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8264. # <strong>F3</strong>.</span></p>
  8265. #
  8266. # ''').format(fsize=fsize, tsize=tsize))
  8267. selected_text = '''
  8268. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8269. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8270. {s1}</span></p>
  8271. <ol>
  8272. <li><span style="font-size:{fsize}px">{s2}<br />
  8273. <br />
  8274. {s3}</span><br />
  8275. &nbsp;</li>
  8276. <li><span style="font-size:{fsize}px">{s4}<br />
  8277. &nbsp;</li>
  8278. <br />
  8279. <li><span style="font-size:{fsize}px">{s5}<br />
  8280. &nbsp;</li>
  8281. <br />
  8282. <li><span style="font-size:{fsize}px">{s6}<br />
  8283. <br />
  8284. {s7}</span></li>
  8285. </ol>
  8286. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8287. '''.format(
  8288. title=_("Selected Tab - Choose an Item from Project Tab"),
  8289. subtitle=_("Details"),
  8290. s1=_("The normal flow when working in FlatCAM is the following:"),
  8291. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8292. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8293. "files on the GUI."),
  8294. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8295. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8296. "actions offered within the app."),
  8297. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8298. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8299. "SELECTED TAB will be updated with the object properties according to its kind: "
  8300. "Gerber, Excellon, Geometry or CNCJob object."),
  8301. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8302. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8303. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8304. "the SELECTED TAB and populate it even if it was out of focus."),
  8305. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8306. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8307. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8308. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8309. "(again, done in SELECTED TAB) --> Save GCode."),
  8310. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8311. "or through its own key shortcut: <b>F3</b>."),
  8312. tsize=tsize,
  8313. fsize=fsize
  8314. )
  8315. sel_title.setText(selected_text)
  8316. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8317. self.ui.selected_scroll_area.setWidget(sel_title)
  8318. def setup_obj_classes(self):
  8319. """
  8320. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8321. class.
  8322. :return: None
  8323. """
  8324. FlatCAMObj.app = self
  8325. ObjectCollection.app = self
  8326. Gerber.app = self
  8327. Excellon.app = self
  8328. Geometry.app = self
  8329. CNCjob.app = self
  8330. FCProcess.app = self
  8331. FCProcessContainer.app = self
  8332. OptionsGroupUI.app = self
  8333. def version_check(self):
  8334. """
  8335. Checks for the latest version of the program. Alerts the
  8336. user if theirs is outdated. This method is meant to be run
  8337. in a separate thread.
  8338. :return: None
  8339. """
  8340. self.log.debug("version_check()")
  8341. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8342. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8343. App.version_url,
  8344. str(self.defaults['global_serial']),
  8345. str(self.version),
  8346. str(self.os),
  8347. urllib.parse.urlencode(self.defaults["global_stats"])
  8348. )
  8349. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8350. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8351. # urllib.parse.urlencode(self.defaults["global_stats"])
  8352. else:
  8353. # no_stats dict; just so it won't break things on website
  8354. no_ststs_dict = {}
  8355. no_ststs_dict["global_ststs"] = {}
  8356. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) +\
  8357. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8358. App.log.debug("Checking for updates @ %s" % full_url)
  8359. # ## Get the data
  8360. try:
  8361. f = urllib.request.urlopen(full_url)
  8362. except Exception:
  8363. # App.log.warning("Failed checking for latest version. Could not connect.")
  8364. self.log.warning("Failed checking for latest version. Could not connect.")
  8365. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8366. return
  8367. try:
  8368. data = json.load(f)
  8369. except Exception as e:
  8370. App.log.error("Could not parse information about latest version.")
  8371. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8372. App.log.debug("json.load(): %s" % str(e))
  8373. f.close()
  8374. return
  8375. f.close()
  8376. # ## Latest version?
  8377. if self.version >= data["version"]:
  8378. App.log.debug("FlatCAM is up to date!")
  8379. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8380. return
  8381. App.log.debug("Newer version available.")
  8382. self.message.emit(
  8383. _("Newer Version Available"),
  8384. '%s<br><br>><b>%s</b><br>%s' % (
  8385. _("There is a newer version of FlatCAM available for download:"),
  8386. str(data["name"]),
  8387. str(data["message"])
  8388. ),
  8389. _("info")
  8390. )
  8391. def on_plotcanvas_setup(self, container=None):
  8392. """
  8393. This is doing the setup for the plot area (canvas).
  8394. :param container: QT Widget where to install the canvas
  8395. :return: None
  8396. """
  8397. if container:
  8398. plot_container = container
  8399. else:
  8400. plot_container = self.ui.right_layout
  8401. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8402. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8403. self.is_legacy = True
  8404. self.defaults["global_graphic_engine"] = "2D"
  8405. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8406. else:
  8407. try:
  8408. self.plotcanvas = PlotCanvas(plot_container, self)
  8409. except Exception as er:
  8410. msg_txt = traceback.format_exc()
  8411. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8412. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8413. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8414. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8415. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8416. msg += msg_txt
  8417. self.inform.emit(msg)
  8418. return 'fail'
  8419. # So it can receive key presses
  8420. self.plotcanvas.native.setFocus()
  8421. if self.is_legacy is False:
  8422. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8423. # Set the mouse button for panning
  8424. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8425. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8426. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8427. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8428. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8429. # Keys over plot enabled
  8430. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8431. if self.defaults['global_cursor_type'] == 'small':
  8432. self.app_cursor = self.plotcanvas.new_cursor()
  8433. else:
  8434. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8435. if self.ui.grid_snap_btn.isChecked():
  8436. self.app_cursor.enabled = True
  8437. else:
  8438. self.app_cursor.enabled = False
  8439. if self.is_legacy is False:
  8440. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8441. else:
  8442. # will use the default Matplotlib axes
  8443. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8444. def on_zoom_fit(self, event):
  8445. """
  8446. Callback for zoom-fit request. This can be either from the corresponding
  8447. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8448. with axes limits from the geometry bounds of all objects.
  8449. :param event: Ignored.
  8450. :return: None
  8451. """
  8452. if self.is_legacy is False:
  8453. self.plotcanvas.fit_view()
  8454. else:
  8455. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8456. width = xmax - xmin
  8457. height = ymax - ymin
  8458. xmin -= 0.05 * width
  8459. xmax += 0.05 * width
  8460. ymin -= 0.05 * height
  8461. ymax += 0.05 * height
  8462. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8463. def on_zoom_in(self):
  8464. """
  8465. Callback for zoom-in request.
  8466. :return:
  8467. """
  8468. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8469. def on_zoom_out(self):
  8470. """
  8471. Callback for zoom-out request.
  8472. :return:
  8473. """
  8474. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8475. def disable_all_plots(self):
  8476. self.defaults.report_usage("disable_all_plots()")
  8477. self.disable_plots(self.collection.get_list())
  8478. self.inform.emit('[success] %s' %
  8479. _("All plots disabled."))
  8480. def disable_other_plots(self):
  8481. self.defaults.report_usage("disable_other_plots()")
  8482. self.disable_plots(self.collection.get_non_selected())
  8483. self.inform.emit('[success] %s' %
  8484. _("All non selected plots disabled."))
  8485. def enable_all_plots(self):
  8486. self.defaults.report_usage("enable_all_plots()")
  8487. self.enable_plots(self.collection.get_list())
  8488. self.inform.emit('[success] %s' %
  8489. _("All plots enabled."))
  8490. def on_enable_sel_plots(self):
  8491. log.debug("App.on_enable_sel_plot()")
  8492. object_list = self.collection.get_selected()
  8493. self.enable_plots(objects=object_list)
  8494. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8495. def on_disable_sel_plots(self):
  8496. log.debug("App.on_disable_sel_plot()")
  8497. # self.inform.emit(_("Disabling plots ..."))
  8498. object_list = self.collection.get_selected()
  8499. self.disable_plots(objects=object_list)
  8500. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8501. def enable_plots(self, objects):
  8502. """
  8503. Enable plots
  8504. :param objects: list of Objects to be enabled
  8505. :return:
  8506. """
  8507. log.debug("Enabling plots ...")
  8508. # self.inform.emit(_("Working ..."))
  8509. for obj in objects:
  8510. if obj.options['plot'] is False:
  8511. obj.options.set_change_callback(lambda x: None)
  8512. obj.options['plot'] = True
  8513. try:
  8514. # only the Gerber obj has on_plot_cb_click() method
  8515. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8516. # disable this cb while disconnected,
  8517. # in case the operation takes time the user is not allowed to change it
  8518. obj.ui.plot_cb.setDisabled(True)
  8519. except AttributeError:
  8520. pass
  8521. obj.set_form_item("plot")
  8522. try:
  8523. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8524. obj.ui.plot_cb.setDisabled(False)
  8525. except AttributeError:
  8526. pass
  8527. obj.options.set_change_callback(obj.on_options_change)
  8528. def worker_task(objs):
  8529. with self.proc_container.new(_("Enabling plots ...")):
  8530. for plot_obj in objs:
  8531. # obj.options['plot'] = True
  8532. if isinstance(plot_obj, CNCJobObject):
  8533. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8534. else:
  8535. plot_obj.plot(visible=True)
  8536. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8537. # self.plots_updated.emit()
  8538. def disable_plots(self, objects):
  8539. """
  8540. Disables plots
  8541. :param objects: list of Objects to be disabled
  8542. :return:
  8543. """
  8544. # if no objects selected then do nothing
  8545. if not self.collection.get_selected():
  8546. return
  8547. log.debug("Disabling plots ...")
  8548. # self.inform.emit(_("Working ..."))
  8549. for obj in objects:
  8550. if obj.options['plot'] is True:
  8551. obj.options.set_change_callback(lambda x: None)
  8552. obj.options['plot'] = False
  8553. try:
  8554. # only the Gerber obj has on_plot_cb_click() method
  8555. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8556. obj.ui.plot_cb.setDisabled(True)
  8557. except AttributeError:
  8558. pass
  8559. obj.set_form_item("plot")
  8560. try:
  8561. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8562. obj.ui.plot_cb.setDisabled(False)
  8563. except AttributeError:
  8564. pass
  8565. obj.options.set_change_callback(obj.on_options_change)
  8566. try:
  8567. self.delete_selection_shape()
  8568. except Exception as e:
  8569. log.debug("App.disable_plots() --> %s" % str(e))
  8570. # self.plots_updated.emit()
  8571. def worker_task(objs):
  8572. with self.proc_container.new(_("Disabling plots ...")):
  8573. for plot_obj in objs:
  8574. # obj.options['plot'] = True
  8575. if isinstance(plot_obj, CNCJobObject):
  8576. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8577. else:
  8578. plot_obj.plot(visible=False)
  8579. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8580. def toggle_plots(self, objects):
  8581. """
  8582. Toggle plots visibility
  8583. :param objects: list of Objects for which to be toggled the visibility
  8584. :return: None
  8585. """
  8586. # if no objects selected then do nothing
  8587. if not self.collection.get_selected():
  8588. return
  8589. log.debug("Toggling plots ...")
  8590. self.inform.emit(_("Working ..."))
  8591. for obj in objects:
  8592. if obj.options['plot'] is False:
  8593. obj.options['plot'] = True
  8594. else:
  8595. obj.options['plot'] = False
  8596. self.plots_updated.emit()
  8597. def clear_plots(self):
  8598. """
  8599. Clear the plots
  8600. :return: None
  8601. """
  8602. objects = self.collection.get_list()
  8603. for obj in objects:
  8604. obj.clear(obj == objects[-1])
  8605. # Clear pool to free memory
  8606. self.clear_pool()
  8607. def on_set_color_action_triggered(self):
  8608. """
  8609. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8610. :return:
  8611. """
  8612. new_color = self.defaults['gerber_plot_fill']
  8613. clicked_action = self.sender()
  8614. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8615. act_name = clicked_action.text()
  8616. sel_obj_list = self.collection.get_selected()
  8617. if not sel_obj_list:
  8618. return
  8619. # a default value, I just chose this one
  8620. alpha_level = 'BF'
  8621. for sel_obj in sel_obj_list:
  8622. if sel_obj.kind == 'excellon':
  8623. alpha_level = str(hex(
  8624. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8625. elif sel_obj.kind == 'gerber':
  8626. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8627. elif sel_obj.kind == 'geometry':
  8628. alpha_level = 'FF'
  8629. else:
  8630. log.debug(
  8631. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8632. continue
  8633. sel_obj.alpha_level = alpha_level
  8634. if act_name == _('Red'):
  8635. new_color = '#FF0000' + alpha_level
  8636. if act_name == _('Blue'):
  8637. new_color = '#0000FF' + alpha_level
  8638. if act_name == _('Yellow'):
  8639. new_color = '#FFDF00' + alpha_level
  8640. if act_name == _('Green'):
  8641. new_color = '#00FF00' + alpha_level
  8642. if act_name == _('Purple'):
  8643. new_color = '#FF00FF' + alpha_level
  8644. if act_name == _('Brown'):
  8645. new_color = '#A52A2A' + alpha_level
  8646. if act_name == _('White'):
  8647. new_color = '#FFFFFF' + alpha_level
  8648. if act_name == _('Black'):
  8649. new_color = '#000000' + alpha_level
  8650. if act_name == _('Custom'):
  8651. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8652. c_dialog = QtWidgets.QColorDialog()
  8653. plot_fill_color = c_dialog.getColor(initial=new_color)
  8654. if plot_fill_color.isValid() is False:
  8655. return
  8656. new_color = str(plot_fill_color.name()) + alpha_level
  8657. if act_name == _("Default"):
  8658. for sel_obj in sel_obj_list:
  8659. if sel_obj.kind == 'excellon':
  8660. new_color = self.defaults['excellon_plot_fill']
  8661. new_line_color = self.defaults['excellon_plot_line']
  8662. elif sel_obj.kind == 'gerber':
  8663. new_color = self.defaults['gerber_plot_fill']
  8664. new_line_color = self.defaults['gerber_plot_line']
  8665. elif sel_obj.kind == 'geometry':
  8666. new_color = self.defaults['geometry_plot_line']
  8667. new_line_color = self.defaults['geometry_plot_line']
  8668. else:
  8669. log.debug(
  8670. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8671. continue
  8672. sel_obj.fill_color = new_color
  8673. sel_obj.outline_color = new_line_color
  8674. sel_obj.shapes.redraw(
  8675. update_colors=(new_color, new_line_color)
  8676. )
  8677. return
  8678. if act_name == _("Opacity"):
  8679. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8680. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8681. if ok_button:
  8682. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8683. for sel_obj in sel_obj_list:
  8684. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8685. sel_obj.shapes.redraw(
  8686. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8687. )
  8688. return
  8689. new_line_color = color_variant(new_color[:7], 0.7)
  8690. if act_name == _("White"):
  8691. new_line_color = color_variant("#dedede", 0.7)
  8692. for sel_obj in sel_obj_list:
  8693. sel_obj.fill_color = new_color
  8694. sel_obj.outline_color = new_line_color
  8695. sel_obj.shapes.redraw(
  8696. update_colors=(new_color, new_line_color)
  8697. )
  8698. def on_grid_snap_triggered(self, state):
  8699. """
  8700. :param state: A parameter with the state of the grid, boolean
  8701. :return:
  8702. """
  8703. if state:
  8704. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_filled_16.png'))
  8705. else:
  8706. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_16.png'))
  8707. self.ui.snap_infobar_label.clicked_state = state
  8708. def on_grid_icon_snap_clicked(self):
  8709. """
  8710. Slot called by clicking a GUI element, in this case a FCLabel
  8711. :return:
  8712. """
  8713. if isinstance(self.sender(), FCLabel):
  8714. self.ui.grid_snap_btn.trigger()
  8715. def generate_cnc_job(self, objects):
  8716. """
  8717. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8718. :param objects: Selected objects in the Project Tab
  8719. :return:
  8720. """
  8721. self.defaults.report_usage("generate_cnc_job()")
  8722. # for obj in objects:
  8723. # obj.generatecncjob()
  8724. for obj in objects:
  8725. obj.on_generatecnc_button_click()
  8726. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8727. """
  8728. Saves the current project to the specified file.
  8729. :param filename: Name of the file in which to save.
  8730. :type filename: str
  8731. :param quit_action: if the project saving will be followed by an app quit; boolean
  8732. :param silent: if True will not display status messages
  8733. :param from_tcl True is run from Tcl Shell
  8734. :return: None
  8735. """
  8736. self.log.debug("save_project()")
  8737. self.save_in_progress = True
  8738. with self.proc_container.new(_("Saving FlatCAM Project")):
  8739. # Capture the latest changes
  8740. # Current object
  8741. try:
  8742. current_object = self.collection.get_active()
  8743. if current_object:
  8744. current_object.read_form()
  8745. except Exception as e:
  8746. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8747. pass
  8748. # Serialize the whole project
  8749. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8750. "options": self.options,
  8751. "version": self.version}
  8752. if self.defaults["global_save_compressed"] is True:
  8753. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8754. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8755. # # Write
  8756. f.write(g)
  8757. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8758. else:
  8759. # Open file
  8760. try:
  8761. f = open(filename, 'w')
  8762. except IOError:
  8763. App.log.error("Failed to open file for saving: %s", filename)
  8764. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8765. return
  8766. # Write
  8767. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8768. f.close()
  8769. # verification of the saved project
  8770. # Open and parse
  8771. try:
  8772. saved_f = open(filename, 'r')
  8773. except IOError:
  8774. if silent is False:
  8775. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8776. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8777. return
  8778. try:
  8779. saved_d = json.load(saved_f, object_hook=dict2obj)
  8780. except Exception:
  8781. if silent is False:
  8782. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8783. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8784. f.close()
  8785. return
  8786. saved_f.close()
  8787. if silent is False:
  8788. if 'version' in saved_d:
  8789. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8790. else:
  8791. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8792. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8793. tb_settings = QSettings("Open Source", "FlatCAM")
  8794. lock_state = self.ui.lock_action.isChecked()
  8795. tb_settings.setValue('toolbar_lock', lock_state)
  8796. # This will write the setting to the platform specific storage.
  8797. del tb_settings
  8798. # if quit:
  8799. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8800. # t.start()
  8801. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8802. def start_delayed_quit(self, delay, filename, should_quit=None):
  8803. """
  8804. :param delay: period of checking if project file size is more than zero; in seconds
  8805. :param filename: the name of the project file to be checked periodically for size more than zero
  8806. :param should_quit: if the task finished will be followed by an app quit; boolean
  8807. :return:
  8808. """
  8809. to_quit = should_quit
  8810. self.save_timer = QtCore.QTimer()
  8811. self.save_timer.setInterval(delay)
  8812. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8813. self.save_timer.start()
  8814. def check_project_file_size(self, filename, should_quit=None):
  8815. """
  8816. :param filename: the name of the project file to be checked periodically for size more than zero
  8817. :param should_quit: will quit the app if True; boolean
  8818. :return:
  8819. """
  8820. try:
  8821. if os.stat(filename).st_size > 0:
  8822. self.save_in_progress = False
  8823. self.save_timer.stop()
  8824. if should_quit:
  8825. self.app_quit.emit()
  8826. except Exception:
  8827. traceback.print_exc()
  8828. def save_project_auto(self):
  8829. """
  8830. Called periodically to save the project.
  8831. 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
  8832. # progress.
  8833. :return:
  8834. """
  8835. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8836. self.on_file_saveproject()
  8837. def save_project_auto_update(self):
  8838. """
  8839. Update the auto save time interval value.
  8840. :return:
  8841. """
  8842. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8843. try:
  8844. if self.autosave_timer.isActive():
  8845. self.autosave_timer.stop()
  8846. except Exception:
  8847. pass
  8848. if self.defaults['global_autosave'] is True:
  8849. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8850. self.autosave_timer.start()
  8851. def on_options_app2project(self):
  8852. """
  8853. Callback for Options->Transfer Options->App=>Project. Copies options
  8854. from application defaults to project defaults.
  8855. :return: None
  8856. """
  8857. self.defaults.report_usage("on_options_app2project")
  8858. self.preferencesUiManager.defaults_read_form()
  8859. self.options.update(self.defaults)
  8860. def toggle_shell(self):
  8861. """
  8862. Toggle shell: if is visible close it, if it is closed then open it
  8863. :return: None
  8864. """
  8865. self.defaults.report_usage("toggle_shell()")
  8866. if self.ui.shell_dock.isVisible():
  8867. self.ui.shell_dock.hide()
  8868. self.plotcanvas.native.setFocus()
  8869. else:
  8870. self.ui.shell_dock.show()
  8871. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8872. # self.shell._edit.setFocus()
  8873. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8874. # HACK - simulate a mouse click - alternative
  8875. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8876. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8877. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8878. # no_km)
  8879. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8880. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8881. # no_km)
  8882. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8883. def on_toggle_shell_from_settings(self, state):
  8884. """
  8885. Toggle shell: if is visible close it, if it is closed then open it
  8886. :return: None
  8887. """
  8888. self.defaults.report_usage("on_toggle_shell_from_settings()")
  8889. if state is True:
  8890. if not self.ui.shell_dock.isVisible():
  8891. self.ui.shell_dock.show()
  8892. else:
  8893. if self.ui.shell_dock.isVisible():
  8894. self.ui.shell_dock.hide()
  8895. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8896. """
  8897. Shows a message on the FlatCAM Shell
  8898. :param msg: Message to display.
  8899. :param show: Opens the shell.
  8900. :param error: Shows the message as an error.
  8901. :param warning: Shows the message as an warning.
  8902. :param success: Shows the message as an success.
  8903. :param selected: Indicate that something was selected on canvas
  8904. :return: None
  8905. """
  8906. if show:
  8907. self.ui.shell_dock.show()
  8908. try:
  8909. if error:
  8910. self.shell.append_error(msg + "\n")
  8911. elif warning:
  8912. self.shell.append_warning(msg + "\n")
  8913. elif success:
  8914. self.shell.append_success(msg + "\n")
  8915. elif selected:
  8916. self.shell.append_selected(msg + "\n")
  8917. else:
  8918. self.shell.append_output(msg + "\n")
  8919. except AttributeError:
  8920. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8921. class ArgsThread(QtCore.QObject):
  8922. open_signal = pyqtSignal(list)
  8923. start = pyqtSignal()
  8924. if sys.platform == 'win32':
  8925. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8926. else:
  8927. address = ('/tmp/testipc', 'AF_UNIX')
  8928. def __init__(self):
  8929. super(ArgsThread, self).__init__()
  8930. self.listener = None
  8931. self.thread_exit = False
  8932. self.start.connect(self.run)
  8933. def my_loop(self, address):
  8934. try:
  8935. self.listener = Listener(*address)
  8936. while self.thread_exit is False:
  8937. conn = self.listener.accept()
  8938. self.serve(conn)
  8939. except socket.error:
  8940. try:
  8941. conn = Client(*address)
  8942. conn.send(sys.argv)
  8943. conn.send('close')
  8944. # close the current instance only if there are args
  8945. if len(sys.argv) > 1:
  8946. try:
  8947. self.listener.close()
  8948. except Exception:
  8949. pass
  8950. sys.exit()
  8951. except ConnectionRefusedError:
  8952. if sys.platform == 'win32':
  8953. pass
  8954. else:
  8955. os.system('rm /tmp/testipc')
  8956. self.listener = Listener(*address)
  8957. while True:
  8958. conn = self.listener.accept()
  8959. self.serve(conn)
  8960. def serve(self, conn):
  8961. while self.thread_exit is False:
  8962. msg = conn.recv()
  8963. if msg == 'close':
  8964. break
  8965. self.open_signal.emit(msg)
  8966. conn.close()
  8967. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8968. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8969. @pyqtSlot()
  8970. def run(self):
  8971. self.my_loop(self.address)
  8972. # end of file