App.py 469 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515
  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 Common import LoudDict, color_variant, ExclusionAreas
  37. from Bookmark import BookmarkManager
  38. from AppDatabase import ToolsDB2
  39. from vispy.gloo.util import _screenshot
  40. from vispy.io import write_png
  41. # FlatCAM AppObjects
  42. from defaults import FlatCAMDefaults
  43. from AppGUI.preferences.OptionsGroupUI import OptionsGroupUI
  44. from AppGUI.preferences.PreferencesUIManager import PreferencesUIManager
  45. from AppObjects.ObjectCollection import *
  46. from AppObjects.FlatCAMObj import FlatCAMObj
  47. from AppObjects.FlatCAMCNCJob import CNCJobObject
  48. from AppObjects.FlatCAMDocument import DocumentObject
  49. from AppObjects.FlatCAMExcellon import ExcellonObject
  50. from AppObjects.FlatCAMGeometry import GeometryObject
  51. from AppObjects.FlatCAMGerber import GerberObject
  52. from AppObjects.FlatCAMScript import ScriptObject
  53. # FlatCAM Parsing files
  54. from AppParsers.ParseExcellon import Excellon
  55. from AppParsers.ParseGerber import Gerber
  56. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  57. # FlatCAM AppGUI
  58. from AppGUI.PlotCanvas import *
  59. from AppGUI.PlotCanvasLegacy import *
  60. from AppGUI.MainGUI import *
  61. from AppGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  62. # FlatCAM Pre-processors
  63. from AppPreProcessor import load_preprocessors
  64. # FlatCAM AppEditors
  65. from AppEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  66. from AppEditors.FlatCAMExcEditor import FlatCAMExcEditor
  67. from AppEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  68. from AppEditors.FlatCAMTextEditor import TextEditor
  69. from AppParsers.ParseHPGL2 import HPGL2
  70. # FlatCAM Workers
  71. from AppProcess import *
  72. from AppWorkerStack import WorkerStack
  73. # FlatCAM Tools
  74. from AppTools import *
  75. # FlatCAM Translation
  76. import gettext
  77. import AppTranslation as fcTranslate
  78. import builtins
  79. if sys.platform == 'win32':
  80. import winreg
  81. from win32comext.shell import shell, shellcon
  82. fcTranslate.apply_language('strings')
  83. if '_' not in builtins.__dict__:
  84. _ = gettext.gettext
  85. class App(QtCore.QObject):
  86. """
  87. The main application class. The constructor starts the AppGUI.
  88. """
  89. # ###############################################################################################################
  90. # ########################################## App ################################################################
  91. # ###############################################################################################################
  92. # ###############################################################################################################
  93. # ######################################### LOGGING #############################################################
  94. # ###############################################################################################################
  95. log = logging.getLogger('base')
  96. log.setLevel(logging.DEBUG)
  97. # log.setLevel(logging.WARNING)
  98. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  99. handler = logging.StreamHandler()
  100. handler.setFormatter(formatter)
  101. log.addHandler(handler)
  102. # ###############################################################################################################
  103. # #################################### Get Cmd Line Options #####################################################
  104. # ###############################################################################################################
  105. cmd_line_shellfile = ''
  106. cmd_line_shellvar = ''
  107. cmd_line_headless = None
  108. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  109. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  110. "FlatCam.py --headless=1"
  111. try:
  112. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  113. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  114. "shellvar=",
  115. "headless=",
  116. "multiprocessing-fork="])
  117. except getopt.GetoptError:
  118. print(cmd_line_help)
  119. sys.exit(2)
  120. for opt, arg in cmd_line_options:
  121. if opt == '-h':
  122. print(cmd_line_help)
  123. sys.exit()
  124. elif opt == '--shellfile':
  125. cmd_line_shellfile = arg
  126. elif opt == '--shellvar':
  127. cmd_line_shellvar = arg
  128. elif opt == '--headless':
  129. try:
  130. cmd_line_headless = eval(arg)
  131. except NameError:
  132. pass
  133. # ###############################################################################################################
  134. # ################################### Version and VERSION DATE ##################################################
  135. # ###############################################################################################################
  136. version = 8.993
  137. version_date = "2020/08/01"
  138. beta = True
  139. engine = '3D'
  140. # current date now
  141. date = str(datetime.today()).rpartition('.')[0]
  142. date = ''.join(c for c in date if c not in ':-')
  143. date = date.replace(' ', '_')
  144. # ###############################################################################################################
  145. # ############################################ URLS's ###########################################################
  146. # ###############################################################################################################
  147. # URL for update checks and statistics
  148. version_url = "http://flatcam.org/version"
  149. # App URL
  150. app_url = "http://flatcam.org"
  151. # Manual URL
  152. manual_url = "http://flatcam.org/manual/index.html"
  153. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  154. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  155. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  156. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  157. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  158. # this variable will hold the project status
  159. # if True it will mean that the project was modified and not saved
  160. should_we_save = False
  161. # flag is True if saving action has been triggered
  162. save_in_progress = False
  163. # ###############################################################################################################
  164. # ####################################### APP Signals ######################################################
  165. # ###############################################################################################################
  166. # Inform the user
  167. # Handled by:
  168. # * App.info() --> Print on the status bar
  169. inform = QtCore.pyqtSignal(str)
  170. app_quit = QtCore.pyqtSignal()
  171. # General purpose background task
  172. worker_task = QtCore.pyqtSignal(dict)
  173. # File opened
  174. # Handled by:
  175. # * register_folder()
  176. # * register_recent()
  177. # Note: Setting the parameters to unicode does not seem
  178. # to have an effect. Then are received as Qstring
  179. # anyway.
  180. # File type and filename
  181. file_opened = QtCore.pyqtSignal(str, str)
  182. # File type and filename
  183. file_saved = QtCore.pyqtSignal(str, str)
  184. # Percentage of progress
  185. progress = QtCore.pyqtSignal(int)
  186. plots_updated = QtCore.pyqtSignal()
  187. # Emitted by new_object() and passes the new object as argument, plot flag.
  188. # on_object_created() adds the object to the collection, plots on appropriate flag
  189. # and emits new_object_available.
  190. object_created = QtCore.pyqtSignal(object, bool, bool)
  191. # Emitted when a object has been changed (like scaled, mirrored)
  192. object_changed = QtCore.pyqtSignal(object)
  193. # Emitted after object has been plotted.
  194. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  195. object_plotted = QtCore.pyqtSignal(object)
  196. # Emitted when a new object has been added or deleted from/to the collection
  197. object_status_changed = QtCore.pyqtSignal(object, str, str)
  198. message = QtCore.pyqtSignal(str, str, str)
  199. # Emmited when shell command is finished(one command only)
  200. shell_command_finished = QtCore.pyqtSignal(object)
  201. # Emitted when multiprocess pool has been recreated
  202. pool_recreated = QtCore.pyqtSignal(object)
  203. # Emitted when an unhandled exception happens
  204. # in the worker task.
  205. thread_exception = QtCore.pyqtSignal(object)
  206. # used to signal that there are arguments for the app
  207. args_at_startup = QtCore.pyqtSignal(list)
  208. # a reusable signal to replot a list of objects
  209. # should be disconnected after use so it can be reused
  210. replot_signal = pyqtSignal(list)
  211. # signal emitted when jumping
  212. jump_signal = pyqtSignal(tuple)
  213. # signal emitted when jumping
  214. locate_signal = pyqtSignal(tuple, str)
  215. # close app signal
  216. close_app_signal = pyqtSignal()
  217. # will perform the cleanup operation after a Graceful Exit
  218. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  219. # graphic residues behind
  220. cleanup = pyqtSignal()
  221. def __init__(self, user_defaults=True):
  222. """
  223. Starts the application.
  224. :return: app
  225. :rtype: App
  226. """
  227. super().__init__()
  228. App.log.info("FlatCAM Starting...")
  229. self.main_thread = QtWidgets.QApplication.instance().thread()
  230. # ############################################################################################################
  231. # ################# Setup the listening thread for another instance launching with args ######################
  232. # ############################################################################################################
  233. if sys.platform == 'win32' or sys.platform == 'linux':
  234. # make sure the thread is stored by using a self. otherwise it's garbage collected
  235. self.th = QtCore.QThread()
  236. self.th.start(priority=QtCore.QThread.LowestPriority)
  237. self.new_launch = ArgsThread()
  238. self.new_launch.open_signal[list].connect(self.on_startup_args)
  239. self.new_launch.moveToThread(self.th)
  240. self.new_launch.start.emit()
  241. # ############################################################################################################
  242. # # ######################################## OS-specific #####################################################
  243. # ############################################################################################################
  244. portable = False
  245. # Folder for user settings.
  246. if sys.platform == 'win32':
  247. if platform.architecture()[0] == '32bit':
  248. App.log.debug("Win32!")
  249. else:
  250. App.log.debug("Win64!")
  251. # #######################################################################################################
  252. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  253. # #######################################################################################################
  254. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  255. try:
  256. with open(config_file, 'r'):
  257. pass
  258. except FileNotFoundError:
  259. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  260. try:
  261. with open(config_file, 'r') as f:
  262. try:
  263. for line in f:
  264. param = str(line).replace('\n', '').rpartition('=')
  265. if param[0] == 'portable':
  266. try:
  267. portable = eval(param[2])
  268. except NameError:
  269. portable = False
  270. if param[0] == 'headless':
  271. if param[2].lower() == 'true':
  272. self.cmd_line_headless = 1
  273. else:
  274. self.cmd_line_headless = None
  275. except Exception as e:
  276. log.debug('App.__init__() -->%s' % str(e))
  277. return
  278. except FileNotFoundError as e:
  279. log.debug(str(e))
  280. pass
  281. if portable is False:
  282. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  283. else:
  284. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  285. self.os = 'windows'
  286. else: # Linux/Unix/MacOS
  287. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  288. self.os = 'unix'
  289. # ############################################################################################################
  290. # ################################# Setup folders and files ##################################################
  291. # ############################################################################################################
  292. if not os.path.exists(self.data_path):
  293. os.makedirs(self.data_path)
  294. App.log.debug('Created data folder: ' + self.data_path)
  295. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  296. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  297. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  298. if not os.path.exists(self.preprocessorpaths):
  299. os.makedirs(self.preprocessorpaths)
  300. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  301. # create geo_tools_db.FlatDB file if there is none
  302. try:
  303. f = open(self.data_path + '/geo_tools_db.FlatDB')
  304. f.close()
  305. except IOError:
  306. App.log.debug('Creating empty geo_tool_db.FlatDB')
  307. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  308. json.dump({}, f)
  309. f.close()
  310. # create current_defaults.FlatConfig file if there is none
  311. try:
  312. f = open(self.data_path + '/current_defaults.FlatConfig')
  313. f.close()
  314. except IOError:
  315. App.log.debug('Creating empty current_defaults.FlatConfig')
  316. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  317. json.dump({}, f)
  318. f.close()
  319. # Write factory_defaults.FlatConfig file to disk
  320. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  321. # create a recent files json file if there is none
  322. try:
  323. f = open(self.data_path + '/recent.json')
  324. f.close()
  325. except IOError:
  326. App.log.debug('Creating empty recent.json')
  327. f = open(self.data_path + '/recent.json', 'w')
  328. json.dump([], f)
  329. f.close()
  330. # create a recent projects json file if there is none
  331. try:
  332. fp = open(self.data_path + '/recent_projects.json')
  333. fp.close()
  334. except IOError:
  335. App.log.debug('Creating empty recent_projects.json')
  336. fp = open(self.data_path + '/recent_projects.json', 'w')
  337. json.dump([], fp)
  338. fp.close()
  339. # Application directory. CHDIR to it. Otherwise, trying to load
  340. # GUI icons will fail as their path is relative.
  341. # This will fail under cx_freeze ...
  342. self.app_home = os.path.dirname(os.path.realpath(__file__))
  343. App.log.debug("Application path is " + self.app_home)
  344. App.log.debug("Started in " + os.getcwd())
  345. # cx_freeze workaround
  346. if os.path.isfile(self.app_home):
  347. self.app_home = os.path.dirname(self.app_home)
  348. os.chdir(self.app_home)
  349. # ############################################################################################################
  350. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  351. # ############################################################################################################
  352. self.defaults = FlatCAMDefaults()
  353. self.defaults["root_folder_path"] = self.app_home
  354. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  355. if user_defaults:
  356. self.defaults.load(filename=current_defaults_path)
  357. if self.defaults['units'] == 'MM':
  358. self.decimals = int(self.defaults['decimals_metric'])
  359. else:
  360. self.decimals = int(self.defaults['decimals_inch'])
  361. if self.defaults["global_gray_icons"] is False:
  362. self.resource_location = 'assets/resources'
  363. else:
  364. self.resource_location = 'assets/resources/dark_resources'
  365. self.current_units = self.defaults['units']
  366. # ###########################################################################################################
  367. # #################################### SETUP OBJECT CLASSES #################################################
  368. # ###########################################################################################################
  369. self.setup_obj_classes()
  370. # ###########################################################################################################
  371. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  372. # ###########################################################################################################
  373. self.pool = Pool()
  374. # ###########################################################################################################
  375. # ###################################### Setting the Splash Screen ##########################################
  376. # ###########################################################################################################
  377. splash_settings = QSettings("Open Source", "FlatCAM")
  378. if splash_settings.contains("splash_screen"):
  379. show_splash = splash_settings.value("splash_screen")
  380. else:
  381. splash_settings.setValue('splash_screen', 1)
  382. # This will write the setting to the platform specific storage.
  383. del splash_settings
  384. show_splash = 1
  385. if show_splash and self.cmd_line_headless != 1:
  386. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  387. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  388. # self.splash.setMask(splash_pix.mask())
  389. # move splashscreen to the current monitor
  390. desktop = QtWidgets.QApplication.desktop()
  391. screen = desktop.screenNumber(QtGui.QCursor.pos())
  392. current_screen_center = desktop.availableGeometry(screen).center()
  393. self.splash.move(current_screen_center - self.splash.rect().center())
  394. self.splash.show()
  395. self.splash.showMessage(_("FlatCAM is initializing ..."),
  396. alignment=Qt.AlignBottom | Qt.AlignLeft,
  397. color=QtGui.QColor("gray"))
  398. else:
  399. show_splash = 0
  400. # ###########################################################################################################
  401. # ######################################### Initialize GUI ##################################################
  402. # ###########################################################################################################
  403. # FlatCAM colors used in plotting
  404. self.FC_light_green = '#BBF268BF'
  405. self.FC_dark_green = '#006E20BF'
  406. self.FC_light_blue = '#a5a5ffbf'
  407. self.FC_dark_blue = '#0000ffbf'
  408. self.ui = MainGUI(self)
  409. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  410. if theme_settings.contains("theme"):
  411. theme = theme_settings.value('theme', type=str)
  412. else:
  413. theme = 'white'
  414. if self.defaults["global_cursor_color_enabled"]:
  415. self.cursor_color_3D = self.defaults["global_cursor_color"]
  416. else:
  417. if theme == 'white':
  418. self.cursor_color_3D = 'black'
  419. else:
  420. self.cursor_color_3D = 'gray'
  421. # update the defaults dict with the setting in QSetting
  422. self.defaults['global_theme'] = theme
  423. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  424. self.ui.final_save.connect(self.final_save)
  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. # #################################### LOAD PREPROCESSORS ###################################################
  436. # ###########################################################################################################
  437. # ----------------------------------------- WARNING --------------------------------------------------------
  438. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  439. # That's because the number of preprocessors can vary and here the comboboxes are populated
  440. # -----------------------------------------------------------------------------------------------------------
  441. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  442. # the preprocessor file
  443. self.preprocessors = load_preprocessors(self)
  444. # make sure that always the 'default' preprocessor is the first item in the dictionary
  445. if 'default' in self.preprocessors.keys():
  446. new_ppp_dict = {}
  447. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  448. default_pp = self.preprocessors.pop('default')
  449. new_ppp_dict['default'] = default_pp
  450. # then add the rest of the keys
  451. for name, val_class in self.preprocessors.items():
  452. new_ppp_dict[name] = val_class
  453. # and now put back the ordered dict with 'default' key first
  454. self.preprocessors = new_ppp_dict
  455. for name in list(self.preprocessors.keys()):
  456. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  457. if name.partition('_')[0] == 'Paste':
  458. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  459. continue
  460. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  461. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  462. if name == 'hpgl':
  463. continue
  464. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  465. # ###########################################################################################################
  466. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  467. # ###########################################################################################################
  468. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  469. inform=self.inform)
  470. self.preferencesUiManager.defaults_write_form()
  471. # When the self.defaults dictionary changes will update the Preferences GUI forms
  472. self.defaults.set_change_callback(self.on_defaults_dict_change)
  473. # ###########################################################################################################
  474. # ##################################### FIRST RUN SECTION ###################################################
  475. # ################################ It's done only once after install #####################################
  476. # ###########################################################################################################
  477. if self.defaults["first_run"] is True:
  478. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  479. initial_lay = 'minimal'
  480. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  481. # Set the combobox in Preferences to the current layout
  482. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  483. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  484. # after the first run, this object should be False
  485. self.defaults["first_run"] = False
  486. self.preferencesUiManager.save_defaults(silent=True)
  487. # ###########################################################################################################
  488. # ############################################ Data #########################################################
  489. # ###########################################################################################################
  490. self.recent = []
  491. self.recent_projects = []
  492. self.clipboard = QtWidgets.QApplication.clipboard()
  493. self.project_filename = None
  494. self.toggle_units_ignore = False
  495. # ###########################################################################################################
  496. # ########################################## LOAD LANGUAGES ################################################
  497. # ###########################################################################################################
  498. self.languages = fcTranslate.load_languages()
  499. for name in sorted(self.languages.values()):
  500. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  501. # ###########################################################################################################
  502. # ####################################### APPLY APP LANGUAGE ################################################
  503. # ###########################################################################################################
  504. ret_val = fcTranslate.apply_language('strings')
  505. if ret_val == "no language":
  506. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  507. log.debug("Could not find the Language files. The App strings are missing.")
  508. else:
  509. # make the current language the current selection on the language combobox
  510. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  511. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  512. # ###########################################################################################################
  513. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  514. # ###########################################################################################################
  515. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  516. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  517. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  518. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  519. self.defaults.propagate_defaults()
  520. # ###########################################################################################################
  521. # ######################################## UPDATE THE OPTIONS ###############################################
  522. # ###########################################################################################################
  523. self.options = LoudDict()
  524. # -----------------------------------------------------------------------------------------------------------
  525. # Update the self.options from the self.defaults
  526. # The self.defaults holds the application defaults while the self.options holds the object defaults
  527. # -----------------------------------------------------------------------------------------------------------
  528. # Copy app defaults to project options
  529. for def_key, def_val in self.defaults.items():
  530. self.options[def_key] = deepcopy(def_val)
  531. self.preferencesUiManager.show_preferences_gui()
  532. # ### End of Data ####
  533. # ###########################################################################################################
  534. # #################################### SETUP OBJECT COLLECTION ##############################################
  535. # ###########################################################################################################
  536. self.collection = ObjectCollection(self)
  537. self.ui.project_tab_layout.addWidget(self.collection.view)
  538. # ### Adjust tabs width ## ##
  539. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  540. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  541. self.collection.view.setMinimumWidth(290)
  542. self.log.debug("Finished creating Object Collection.")
  543. # ###########################################################################################################
  544. # ######################################## SETUP Plot Area ##################################################
  545. # ###########################################################################################################
  546. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  547. if self.defaults["global_graphic_engine"] == '3D':
  548. self.is_legacy = False
  549. else:
  550. self.is_legacy = True
  551. # Event signals disconnect id holders
  552. self.mp = None
  553. self.mm = None
  554. self.mr = None
  555. self.mdc = None
  556. self.mp_zc = None
  557. self.kp = None
  558. # Matplotlib axis
  559. self.axes = None
  560. if show_splash:
  561. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  562. "Canvas initialization started."),
  563. alignment=Qt.AlignBottom | Qt.AlignLeft,
  564. color=QtGui.QColor("gray"))
  565. start_plot_time = time.time() # debug
  566. self.plotcanvas = None
  567. self.app_cursor = None
  568. self.hover_shapes = None
  569. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  570. # setup the PlotCanvas
  571. self.on_plotcanvas_setup()
  572. end_plot_time = time.time()
  573. self.used_time = end_plot_time - start_plot_time
  574. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  575. if show_splash:
  576. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  577. "Canvas initialization started.\n"
  578. "Canvas initialization finished in"), '%.2f' % self.used_time),
  579. alignment=Qt.AlignBottom | Qt.AlignLeft,
  580. color=QtGui.QColor("gray"))
  581. self.ui.splitter.setStretchFactor(1, 2)
  582. # ###########################################################################################################
  583. # ############################################### SYS TRAY ##################################################
  584. # ###########################################################################################################
  585. if self.defaults["global_systray_icon"]:
  586. self.parent_w = QtWidgets.QWidget()
  587. if self.cmd_line_headless == 1:
  588. self.trayIcon = FlatCAMSystemTray(app=self,
  589. icon=QtGui.QIcon(self.resource_location +
  590. '/flatcam_icon32_green.png'),
  591. headless=True,
  592. parent=self.parent_w)
  593. else:
  594. self.trayIcon = FlatCAMSystemTray(app=self,
  595. icon=QtGui.QIcon(self.resource_location +
  596. '/flatcam_icon32_green.png'),
  597. parent=self.parent_w)
  598. # ###########################################################################################################
  599. # ############################################### Worker SETUP ##############################################
  600. # ###########################################################################################################
  601. if self.defaults["global_worker_number"]:
  602. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  603. else:
  604. self.workers = WorkerStack(workers_number=2)
  605. self.worker_task.connect(self.workers.add_task)
  606. self.log.debug("Finished creating Workers crew.")
  607. # ###########################################################################################################
  608. # ############################################# Activity Monitor ###########################################
  609. # ###########################################################################################################
  610. self.activity_view = FlatCAMActivityView(app=self)
  611. self.ui.infobar.addWidget(self.activity_view)
  612. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  613. # ###########################################################################################################
  614. # ############################################# Signal handling #############################################
  615. # ###########################################################################################################
  616. # ########################################## Custom signals ################################################
  617. # signal for displaying messages in status bar
  618. self.inform.connect(self.info)
  619. # signal to be called when the app is quiting
  620. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  621. self.message.connect(lambda: message_dialog(parent=self.ui))
  622. # self.progress.connect(self.set_progress_bar)
  623. # signals that are emitted when object state changes
  624. self.object_created.connect(self.on_object_created)
  625. self.object_changed.connect(self.on_object_changed)
  626. self.object_plotted.connect(self.on_object_plotted)
  627. self.plots_updated.connect(self.on_plots_updated)
  628. # signals emitted when file state change
  629. self.file_opened.connect(self.register_recent)
  630. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  631. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  632. # ########################################## Standard signals ###############################################
  633. # ### Menu
  634. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  635. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  636. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  637. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  638. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  639. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  640. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  641. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  642. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  643. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  644. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  645. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  646. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  647. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  648. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  649. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  650. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  651. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  652. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  653. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  654. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  655. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  656. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  657. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  658. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  659. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  660. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  661. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  662. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  663. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  664. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  665. self.ui.menufile_exit.triggered.connect(self.final_save)
  666. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  667. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  668. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  669. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  670. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  671. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  672. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  673. self.ui.menueditdelete.triggered.connect(self.on_delete)
  674. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  675. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  676. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  677. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  678. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  679. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  680. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  681. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  682. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  683. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  684. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  685. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  686. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  687. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  688. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  689. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  690. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  691. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  692. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  693. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  694. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  695. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  696. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  697. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  698. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  699. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  700. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  701. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  702. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  703. self.ui.menuview_replot.triggered.connect(self.plot_all)
  704. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  705. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  706. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  707. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  708. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  709. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  710. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  711. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  712. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  713. self.ui.menuview_toggle_hud.triggered.connect(self.on_toggle_hud)
  714. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  715. self.ui.menuhelp_about.triggered.connect(self.on_about)
  716. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  717. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  718. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  719. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  720. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  721. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  722. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  723. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  724. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  725. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  726. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  727. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  728. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  729. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  730. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  731. # ToolBar signals
  732. self.connect_toolbar_signals()
  733. # Notebook and Plot Tab Area signals
  734. # make the right click on the notebook tab and plot tab area tab raise a menu
  735. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  736. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  737. self.on_tab_setup_context_menu()
  738. # activate initial state
  739. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  740. # Context Menu
  741. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  742. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  743. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  744. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  745. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  746. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  747. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  748. self.ui.clearplot.triggered.connect(self.clear_plots)
  749. self.ui.replot.triggered.connect(self.plot_all)
  750. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  751. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  752. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  753. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  754. self.ui.popmenu_move.triggered.connect(self.obj_move)
  755. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  756. # Project Context Menu -> Color Setting
  757. for act in self.ui.menuprojectcolor.actions():
  758. act.triggered.connect(self.on_set_color_action_triggered)
  759. # ###########################################################################################################
  760. # #################################### GUI PREFERENCES SIGNALS ##############################################
  761. # ###########################################################################################################
  762. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  763. lambda: self.on_toggle_units(no_pref=False))
  764. # ##################################### Workspace Setting Signals ###########################################
  765. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  766. self.on_workspace_modified)
  767. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  768. self.on_workspace_modified
  769. )
  770. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  771. # ###########################################################################################################
  772. # ######################################## GUI SETTINGS SIGNALS #############################################
  773. # ###########################################################################################################
  774. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  775. # ######################################## Tools related signals ############################################
  776. # Film Tool
  777. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  778. self.on_film_color_entry)
  779. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  780. self.on_film_color_button)
  781. # QRCode Tool
  782. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  783. self.on_qrcode_fill_color_entry)
  784. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  785. self.on_qrcode_fill_color_button)
  786. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  787. self.on_qrcode_back_color_entry)
  788. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  789. self.on_qrcode_back_color_button)
  790. # portability changed signal
  791. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  792. # Object list
  793. self.object_status_changed.connect(self.collection.on_collection_updated)
  794. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  795. # Export Excellon parameters.
  796. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  797. self.on_update_exc_export
  798. )
  799. # call it once to make sure it is updated at startup
  800. self.on_update_exc_export(state=self.defaults["excellon_update"])
  801. # when there are arguments at application startup this get launched
  802. self.args_at_startup[list].connect(self.on_startup_args)
  803. # ###########################################################################################################
  804. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  805. # ###########################################################################################################
  806. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  807. lambda: self.restore_extensions(ext_type='excellon'))
  808. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  809. lambda: self.restore_extensions(ext_type='gcode'))
  810. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  811. lambda: self.restore_extensions(ext_type='gerber'))
  812. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  813. lambda: self.delete_all_extensions(ext_type='excellon'))
  814. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  815. lambda: self.delete_all_extensions(ext_type='gcode'))
  816. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  817. lambda: self.delete_all_extensions(ext_type='gerber'))
  818. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  819. lambda: self.add_extension(ext_type='excellon'))
  820. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  821. lambda: self.add_extension(ext_type='gcode'))
  822. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  823. lambda: self.add_extension(ext_type='gerber'))
  824. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  825. lambda: self.del_extension(ext_type='excellon'))
  826. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  827. lambda: self.del_extension(ext_type='gcode'))
  828. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  829. lambda: self.del_extension(ext_type='gerber'))
  830. # connect the 'Apply' buttons from the Preferences/File Associations
  831. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  832. lambda: self.on_register_files(obj_type='excellon'))
  833. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  834. lambda: self.on_register_files(obj_type='gcode'))
  835. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  836. lambda: self.on_register_files(obj_type='gerber'))
  837. # ###########################################################################################################
  838. # ########################################### KEYWORDS SIGNALS ##############################################
  839. # ###########################################################################################################
  840. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  841. lambda: self.restore_extensions(ext_type='keyword'))
  842. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  843. lambda: self.delete_all_extensions(ext_type='keyword'))
  844. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  845. lambda: self.add_extension(ext_type='keyword'))
  846. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  847. lambda: self.del_extension(ext_type='keyword'))
  848. # connect the abort_all_tasks related slots to the related signals
  849. self.proc_container.idle_flag.connect(self.app_is_idle)
  850. # signal emitted when a tab is closed in the Plot Area
  851. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  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 AppEditors
  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. self.corners_tool = None
  1145. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1146. try:
  1147. self.install_tools()
  1148. except AttributeError as e:
  1149. log.debug("App.__init__() install tools() --> %s" % str(e))
  1150. # ###########################################################################################################
  1151. # ############################################ SETUP RECENT ITEMS ###########################################
  1152. # ###########################################################################################################
  1153. self.setup_recent_items()
  1154. # ###########################################################################################################
  1155. # ######################################### BookMarks Manager ###############################################
  1156. # ###########################################################################################################
  1157. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1158. self.install_bookmarks()
  1159. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1160. # ###########################################################################################################
  1161. # ########################################### Tools Database ################################################
  1162. # ###########################################################################################################
  1163. self.tools_db_tab = None
  1164. # ### System Font Parsing ###
  1165. # self.f_parse = ParseFont(self)
  1166. # self.parse_system_fonts()
  1167. # ###########################################################################################################
  1168. # ######################################### Check for updates ###############################################
  1169. # ###########################################################################################################
  1170. # Separate thread (Not worker)
  1171. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1172. if (self.beta is False or self.beta is None) and \
  1173. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1174. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1175. # self.thr2 = QtCore.QThread()
  1176. self.worker_task.emit({'fcn': self.version_check,
  1177. 'params': []})
  1178. # self.thr2.start(QtCore.QThread.LowPriority)
  1179. # ###########################################################################################################
  1180. # ##################################### Register files with FlatCAM; #######################################
  1181. # ################################### It works only for Windows for now ####################################
  1182. # ###########################################################################################################
  1183. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1184. self.on_register_files()
  1185. # ###########################################################################################################
  1186. # ######################################## Variables for global usage #######################################
  1187. # ###########################################################################################################
  1188. # hold the App units
  1189. self.units = 'MM'
  1190. # coordinates for relative position display
  1191. self.rel_point1 = (0, 0)
  1192. self.rel_point2 = (0, 0)
  1193. # variable to store coordinates
  1194. self.pos = (0, 0)
  1195. self.pos_canvas = (0, 0)
  1196. self.pos_jump = (0, 0)
  1197. # variable to store mouse coordinates
  1198. self.mouse = [0, 0]
  1199. # variable to store the delta positions on cavnas
  1200. self.dx = 0
  1201. self.dy = 0
  1202. # decide if we have a double click or single click
  1203. self.doubleclick = False
  1204. # store here the is_dragging value
  1205. self.event_is_dragging = False
  1206. # variable to store if a command is active (then the var is not None) and which one it is
  1207. self.command_active = None
  1208. # variable to store the status of moving selection action
  1209. # None value means that it's not an selection action
  1210. # True value = a selection from left to right
  1211. # False value = a selection from right to left
  1212. self.selection_type = None
  1213. # List to store the objects that are currently loaded in FlatCAM
  1214. # This list is updated on each object creation or object delete
  1215. self.all_objects_list = []
  1216. self.objects_under_the_click_list = []
  1217. # List to store the objects that are selected
  1218. self.sel_objects_list = []
  1219. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1220. self.key_modifiers = None
  1221. # Variable to hold the status of the axis
  1222. self.toggle_axis = True
  1223. # Variable to hold the status of the grid lines
  1224. self.toggle_grid_lines = True
  1225. # Variable to store the status of the code editor
  1226. self.toggle_codeeditor = False
  1227. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1228. self.click_noproject = False
  1229. self.cursor = None
  1230. # Variable to store the GCODE that was edited
  1231. self.gcode_edited = ""
  1232. self.text_editor_tab = None
  1233. # reference for the self.ui.code_editor
  1234. self.reference_code_editor = None
  1235. self.script_code = ''
  1236. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1237. self.tools_db_changed_flag = False
  1238. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1239. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1240. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1241. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1242. 'tsm']
  1243. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1244. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1245. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1246. 'sbp', 'tap', 'xpi']
  1247. self.svg_list = ['svg']
  1248. self.dxf_list = ['dxf']
  1249. self.pdf_list = ['pdf']
  1250. self.prj_list = ['flatprj']
  1251. self.conf_list = ['flatconfig']
  1252. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1253. # flag for polygons not cleared
  1254. self.poly_not_cleared = False
  1255. # VisPy visuals
  1256. self.isHovering = False
  1257. self.notHovering = True
  1258. # Window geometry
  1259. self.x_pos = None
  1260. self.y_pos = None
  1261. self.width = None
  1262. self.height = None
  1263. # when True, the app has to return from any thread
  1264. self.abort_flag = False
  1265. # set the value used in the Windows Title
  1266. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1267. # this holds a widget that is installed in the Plot Area when View Source option is used
  1268. self.source_editor_tab = None
  1269. self.pagesize = {}
  1270. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1271. # VisPy visuals
  1272. if self.is_legacy is False:
  1273. try:
  1274. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1275. except AttributeError:
  1276. self.tool_shapes = None
  1277. else:
  1278. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1279. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1280. # used in the delayed shutdown self.start_delayed_quit() method
  1281. self.save_timer = None
  1282. # ###########################################################################################################
  1283. # ################################## ADDING FlatCAM EDITORS section #########################################
  1284. # ###########################################################################################################
  1285. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1286. # at the first launch of the App , the editors will not be functional.
  1287. try:
  1288. self.geo_editor = FlatCAMGeoEditor(self)
  1289. except AttributeError:
  1290. pass
  1291. try:
  1292. self.exc_editor = FlatCAMExcEditor(self)
  1293. except AttributeError:
  1294. pass
  1295. try:
  1296. self.grb_editor = FlatCAMGrbEditor(self)
  1297. except AttributeError:
  1298. pass
  1299. self.log.debug("Finished adding FlatCAM Editor's.")
  1300. self.set_ui_title(name=_("New Project - Not saved"))
  1301. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1302. current_platform = platform.architecture()[0]
  1303. if current_platform != '64bit':
  1304. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1305. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1306. # ###########################################################################################################
  1307. # ########################################### EXCLUSION AREAS ###############################################
  1308. # ###########################################################################################################
  1309. self.exc_areas = ExclusionAreas(app=self)
  1310. # ###########################################################################################################
  1311. # ##################################### Finished the CONSTRUCTOR ############################################
  1312. # ###########################################################################################################
  1313. App.log.debug("END of constructor. Releasing control.")
  1314. # ###########################################################################################################
  1315. # ########################################## SHOW GUI #######################################################
  1316. # ###########################################################################################################
  1317. # if the app is not started as headless, show it
  1318. if self.cmd_line_headless != 1:
  1319. if show_splash:
  1320. # finish the splash
  1321. self.splash.finish(self.ui)
  1322. mgui_settings = QSettings("Open Source", "FlatCAM")
  1323. if mgui_settings.contains("maximized_gui"):
  1324. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1325. if maximized_ui is True:
  1326. self.ui.showMaximized()
  1327. else:
  1328. self.ui.show()
  1329. else:
  1330. self.ui.show()
  1331. if self.defaults["global_systray_icon"]:
  1332. self.trayIcon.show()
  1333. else:
  1334. log.warning("******************* RUNNING HEADLESS *******************")
  1335. # ###########################################################################################################
  1336. # ######################################## START-UP ARGUMENTS ###############################################
  1337. # ###########################################################################################################
  1338. # test if the program was started with a script as parameter
  1339. if self.cmd_line_shellvar:
  1340. try:
  1341. cnt = 0
  1342. command_tcl = 0
  1343. for i in self.cmd_line_shellvar.split(','):
  1344. if i is not None:
  1345. # noinspection PyBroadException
  1346. try:
  1347. command_tcl = eval(i)
  1348. except Exception:
  1349. command_tcl = i
  1350. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1351. cnt += 1
  1352. # if there are Windows paths then replace the path separator with a Unix like one
  1353. if sys.platform == 'win32':
  1354. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1355. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1356. except Exception as ext:
  1357. print("ERROR: ", ext)
  1358. sys.exit(2)
  1359. if self.cmd_line_shellfile:
  1360. if self.cmd_line_headless != 1:
  1361. if self.ui.shell_dock.isHidden():
  1362. self.ui.shell_dock.show()
  1363. try:
  1364. with open(self.cmd_line_shellfile, "r") as myfile:
  1365. # if show_splash:
  1366. # self.splash.showMessage('%s: %ssec\n%s' % (
  1367. # _("Canvas initialization started.\n"
  1368. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1369. # _("Executing Tcl Script ...")),
  1370. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1371. # color=QtGui.QColor("gray"))
  1372. cmd_line_shellfile_text = myfile.read()
  1373. if self.cmd_line_headless != 1:
  1374. self.shell.exec_command(cmd_line_shellfile_text)
  1375. else:
  1376. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1377. except Exception as ext:
  1378. print("ERROR: ", ext)
  1379. sys.exit(2)
  1380. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1381. # the path/file_name must be enclosed in quotes if it contain spaces
  1382. if App.args:
  1383. self.args_at_startup.emit(App.args)
  1384. if self.defaults.old_defaults_found is True:
  1385. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1386. "Please reboot the application to update."))
  1387. self.defaults.old_defaults_found = False
  1388. # ######################################### INIT FINISHED #######################################################
  1389. # #################################################################################################################
  1390. # #################################################################################################################
  1391. # #################################################################################################################
  1392. # #################################################################################################################
  1393. # #################################################################################################################
  1394. @staticmethod
  1395. def copy_and_overwrite(from_path, to_path):
  1396. """
  1397. From here:
  1398. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1399. :param from_path: source path
  1400. :param to_path: destination path
  1401. :return: None
  1402. """
  1403. if os.path.exists(to_path):
  1404. shutil.rmtree(to_path)
  1405. try:
  1406. shutil.copytree(from_path, to_path)
  1407. except FileNotFoundError:
  1408. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1409. shutil.copytree(from_new_path, to_path)
  1410. def on_startup_args(self, args, silent=False):
  1411. """
  1412. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1413. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1414. :param args: a list containing the application args at startup
  1415. :return: None
  1416. """
  1417. if args is not None:
  1418. args_to_process = args
  1419. else:
  1420. args_to_process = App.args
  1421. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1422. for argument in args_to_process:
  1423. if '.FlatPrj'.lower() in argument.lower():
  1424. try:
  1425. project_name = str(argument)
  1426. if project_name == "":
  1427. if silent is False:
  1428. self.inform.emit(_("Cancelled."))
  1429. else:
  1430. # self.open_project(project_name)
  1431. run_from_arg = True
  1432. # self.worker_task.emit({'fcn': self.open_project,
  1433. # 'params': [project_name, run_from_arg]})
  1434. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1435. except Exception as e:
  1436. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1437. elif '.FlatConfig'.lower() in argument.lower():
  1438. try:
  1439. file_name = str(argument)
  1440. if file_name == "":
  1441. if silent is False:
  1442. self.inform.emit(_("Open Config file failed."))
  1443. else:
  1444. run_from_arg = True
  1445. # self.worker_task.emit({'fcn': self.open_config_file,
  1446. # 'params': [file_name, run_from_arg]})
  1447. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1448. except Exception as e:
  1449. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1450. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1451. try:
  1452. file_name = str(argument)
  1453. if file_name == "":
  1454. if silent is False:
  1455. self.inform.emit(_("Open Script file failed."))
  1456. else:
  1457. if silent is False:
  1458. self.on_fileopenscript(name=file_name)
  1459. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1460. self.on_filerunscript(name=file_name)
  1461. except Exception as e:
  1462. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1463. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1464. log.debug("App.on_startup_args() --> Quit event.")
  1465. sys.exit()
  1466. elif 'save'.lower() in argument.lower():
  1467. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1468. self.preferencesUiManager.save_defaults()
  1469. else:
  1470. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1471. proc_arg = argument.lower()
  1472. for ext in exc_list:
  1473. proc_ext = ext.replace(' ', '')
  1474. proc_ext = '.%s' % proc_ext
  1475. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1476. file_name = str(argument)
  1477. if file_name == "":
  1478. if silent is False:
  1479. self.inform.emit(_("Open Excellon file failed."))
  1480. else:
  1481. self.on_fileopenexcellon(name=file_name, signal=None)
  1482. return
  1483. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1484. for ext in gco_list:
  1485. proc_ext = ext.replace(' ', '')
  1486. proc_ext = '.%s' % proc_ext
  1487. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1488. file_name = str(argument)
  1489. if file_name == "":
  1490. if silent is False:
  1491. self.inform.emit(_("Open GCode file failed."))
  1492. else:
  1493. self.on_fileopengcode(name=file_name, signal=None)
  1494. return
  1495. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1496. for ext in grb_list:
  1497. proc_ext = ext.replace(' ', '')
  1498. proc_ext = '.%s' % proc_ext
  1499. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1500. file_name = str(argument)
  1501. if file_name == "":
  1502. if silent is False:
  1503. self.inform.emit(_("Open Gerber file failed."))
  1504. else:
  1505. self.on_fileopengerber(name=file_name, signal=None)
  1506. return
  1507. # if it reached here without already returning then the app was registered with a file that it does not
  1508. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1509. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1510. # for arg in args_to_process:
  1511. # if 'FlatCAM.exe' in arg:
  1512. # continue
  1513. # else:
  1514. # sys.exit(2)
  1515. def set_ui_title(self, name):
  1516. """
  1517. Sets the title of the main window.
  1518. :param name: String that store the project path and project name
  1519. :return: None
  1520. """
  1521. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1522. (self.version,
  1523. ('BETA' if self.beta else ''),
  1524. platform.architecture()[0],
  1525. self.engine,
  1526. name)
  1527. )
  1528. def on_app_restart(self):
  1529. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1530. # be left in the SySTray
  1531. try:
  1532. self.trayIcon.hide()
  1533. except Exception:
  1534. pass
  1535. fcTranslate.restart_program(app=self)
  1536. def clear_pool(self):
  1537. """
  1538. Clear the multiprocessing pool and calls garbage collector.
  1539. :return: None
  1540. """
  1541. self.pool.close()
  1542. self.pool = Pool()
  1543. self.pool_recreated.emit(self.pool)
  1544. gc.collect()
  1545. def install_tools(self):
  1546. """
  1547. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1548. Instantiation of the Tools classes.
  1549. The order that the tools are installed is important as they can depend on each other install position.
  1550. :return: None
  1551. """
  1552. self.distance_tool = Distance(self)
  1553. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1554. before=self.ui.menueditorigin,
  1555. separator=False)
  1556. self.distance_min_tool = DistanceMin(self)
  1557. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1558. pos=self.ui.menuedit,
  1559. before=self.ui.menueditorigin,
  1560. separator=True)
  1561. self.dblsidedtool = DblSidedTool(self)
  1562. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1563. self.cal_exc_tool = ToolCalibration(self)
  1564. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1565. before=self.dblsidedtool.menuAction,
  1566. separator=False)
  1567. self.align_objects_tool = AlignObjects(self)
  1568. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1569. self.edrills_tool = ToolExtractDrills(self)
  1570. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1571. self.panelize_tool = Panelize(self)
  1572. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1573. self.film_tool = Film(self)
  1574. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1575. self.paste_tool = SolderPaste(self)
  1576. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1577. self.calculator_tool = ToolCalculator(self)
  1578. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1579. self.sub_tool = ToolSub(self)
  1580. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1581. pos=self.ui.menutool, separator=True)
  1582. self.rules_tool = RulesCheck(self)
  1583. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1584. pos=self.ui.menutool, separator=False)
  1585. self.optimal_tool = ToolOptimal(self)
  1586. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1587. pos=self.ui.menutool, separator=True)
  1588. self.move_tool = ToolMove(self)
  1589. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1590. before=self.ui.menueditorigin, separator=True)
  1591. self.cutout_tool = CutOut(self)
  1592. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1593. before=self.sub_tool.menuAction)
  1594. self.ncclear_tool = NonCopperClear(self)
  1595. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1596. before=self.sub_tool.menuAction, separator=True)
  1597. self.paint_tool = ToolPaint(self)
  1598. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1599. before=self.sub_tool.menuAction, separator=True)
  1600. self.copper_thieving_tool = ToolCopperThieving(self)
  1601. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1602. pos=self.ui.menutool)
  1603. self.fiducial_tool = ToolFiducials(self)
  1604. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1605. pos=self.ui.menutool)
  1606. self.qrcode_tool = QRCode(self)
  1607. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1608. pos=self.ui.menutool)
  1609. self.punch_tool = ToolPunchGerber(self)
  1610. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1611. self.invert_tool = ToolInvertGerber(self)
  1612. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1613. self.corners_tool = ToolCorners(self)
  1614. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1615. self.transform_tool = ToolTransform(self)
  1616. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1617. pos=self.ui.menuoptions, separator=True)
  1618. self.properties_tool = Properties(self)
  1619. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1620. pos=self.ui.menuoptions)
  1621. self.pdf_tool = ToolPDF(self)
  1622. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1623. pos=self.ui.menufileimport,
  1624. separator=True)
  1625. self.image_tool = ToolImage(self)
  1626. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1627. pos=self.ui.menufileimport,
  1628. separator=True)
  1629. self.pcb_wizard_tool = PcbWizard(self)
  1630. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1631. pos=self.ui.menufileimport)
  1632. self.log.debug("Tools are installed.")
  1633. def remove_tools(self):
  1634. """
  1635. Will remove all the actions in the Tool menu.
  1636. :return: None
  1637. """
  1638. for act in self.ui.menutool.actions():
  1639. self.ui.menutool.removeAction(act)
  1640. def init_tools(self):
  1641. """
  1642. Initialize the Tool tab in the notebook side of the central widget.
  1643. Remove the actions in the Tools menu.
  1644. Instantiate again the FlatCAM tools (plugins).
  1645. All this is required when changing the layout: standard, compact etc.
  1646. :return: None
  1647. """
  1648. log.debug("init_tools()")
  1649. # delete the data currently in the Tools Tab and the Tab itself
  1650. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1651. if widget is not None:
  1652. widget.deleteLater()
  1653. self.ui.notebook.removeTab(2)
  1654. # rebuild the Tools Tab
  1655. self.ui.tool_tab = QtWidgets.QWidget()
  1656. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1657. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1658. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1659. self.ui.tool_scroll_area = VerticalScrollArea()
  1660. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1661. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1662. # first remove all of them
  1663. self.remove_tools()
  1664. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1665. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1666. '&Command Line\tS')
  1667. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1668. # third install all of them
  1669. try:
  1670. self.install_tools()
  1671. except AttributeError:
  1672. pass
  1673. self.log.debug("Tools are initialized.")
  1674. # def parse_system_fonts(self):
  1675. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1676. # 'params': []})
  1677. def connect_toolbar_signals(self):
  1678. """
  1679. Reconnect the signals to the actions in the toolbar.
  1680. This has to be done each time after the FlatCAM tools are removed/installed.
  1681. :return: None
  1682. """
  1683. # Toolbar
  1684. # File Toolbar Signals
  1685. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1686. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1687. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1688. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1689. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1690. # View Toolbar Signals
  1691. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1692. self.ui.replot_btn.triggered.connect(self.plot_all)
  1693. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1694. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1695. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1696. # Edit Toolbar Signals
  1697. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1698. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1699. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1700. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1701. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1702. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1703. self.ui.delete_btn.triggered.connect(self.on_delete)
  1704. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1705. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1706. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1707. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1708. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1709. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1710. # Scripting Toolbar Signals
  1711. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1712. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1713. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1714. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1715. # Tools Toolbar Signals
  1716. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1717. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1718. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1719. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1720. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1721. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1722. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1723. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1724. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1725. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1726. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1727. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1728. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1729. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1730. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1731. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1732. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1733. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1734. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1735. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1736. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1737. def object2editor(self):
  1738. """
  1739. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1740. :return: None
  1741. """
  1742. self.defaults.report_usage("object2editor()")
  1743. # disable the objects menu as it may interfere with the AppEditors
  1744. self.ui.menuobjects.setDisabled(True)
  1745. edited_object = self.collection.get_active()
  1746. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1747. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1748. pass
  1749. else:
  1750. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1751. return
  1752. if isinstance(edited_object, GeometryObject):
  1753. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1754. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1755. # we set the notebook to hidden
  1756. # self.ui.splitter.setSizes([0, 1])
  1757. if edited_object.multigeo is True:
  1758. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1759. if len(sel_rows) > 1:
  1760. self.inform.emit('[WARNING_NOTCL] %s' %
  1761. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1762. "is not possible.\n"
  1763. "Edit only one geometry at a time."))
  1764. # determine the tool dia of the selected tool
  1765. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1766. # now find the key in the edited_object.tools that has this tooldia
  1767. multi_tool = 1
  1768. for tool in edited_object.tools:
  1769. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1770. multi_tool = tool
  1771. break
  1772. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1773. else:
  1774. self.geo_editor.edit_fcgeometry(edited_object)
  1775. # set call source to the Editor we go into
  1776. self.call_source = 'geo_editor'
  1777. elif isinstance(edited_object, ExcellonObject):
  1778. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1779. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1780. if self.ui.splitter.sizes()[0] == 0:
  1781. self.ui.splitter.setSizes([1, 1])
  1782. self.exc_editor.edit_fcexcellon(edited_object)
  1783. # set call source to the Editor we go into
  1784. self.call_source = 'exc_editor'
  1785. elif isinstance(edited_object, GerberObject):
  1786. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1787. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1788. if self.ui.splitter.sizes()[0] == 0:
  1789. self.ui.splitter.setSizes([1, 1])
  1790. self.grb_editor.edit_fcgerber(edited_object)
  1791. # set call source to the Editor we go into
  1792. self.call_source = 'grb_editor'
  1793. # reset the following variables so the UI is built again after edit
  1794. edited_object.ui_build = False
  1795. edited_object.build_aperture_storage = False
  1796. elif isinstance(edited_object, CNCJobObject):
  1797. if self.ui.splitter.sizes()[0] == 0:
  1798. self.ui.splitter.setSizes([1, 1])
  1799. edited_object.on_edit_code_click()
  1800. return
  1801. # make sure that we can't select another object while in Editor Mode:
  1802. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1803. self.ui.project_frame.setDisabled(True)
  1804. # delete any selection shape that might be active as they are not relevant in Editor
  1805. self.delete_selection_shape()
  1806. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1807. self.ui.plot_tab_area.protectTab(0)
  1808. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1809. self.should_we_save = True
  1810. def editor2object(self, cleanup=None):
  1811. """
  1812. Transfers the Geometry or Excellon from it's editor to the current object.
  1813. :return: None
  1814. """
  1815. self.defaults.report_usage("editor2object()")
  1816. # re-enable the objects menu that was disabled on entry in Editor mode
  1817. self.ui.menuobjects.setDisabled(False)
  1818. # do not update a geometry or excellon object unless it comes out of an editor
  1819. if self.call_source != 'app':
  1820. edited_obj = self.collection.get_active()
  1821. if cleanup is None:
  1822. msgbox = QtWidgets.QMessageBox()
  1823. msgbox.setText(_("Do you want to save the edited object?"))
  1824. msgbox.setWindowTitle(_("Close Editor"))
  1825. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1826. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1827. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1828. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1829. msgbox.setDefaultButton(bt_yes)
  1830. msgbox.exec_()
  1831. response = msgbox.clickedButton()
  1832. if response == bt_yes:
  1833. # clean the Tools Tab
  1834. self.ui.tool_scroll_area.takeWidget()
  1835. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1836. self.ui.notebook.setTabText(2, "Tool")
  1837. if isinstance(edited_obj, GeometryObject):
  1838. obj_type = "Geometry"
  1839. if cleanup is None:
  1840. self.geo_editor.update_fcgeometry(edited_obj)
  1841. # self.geo_editor.update_options(edited_obj)
  1842. self.geo_editor.deactivate()
  1843. # restore GUI to the Selected TAB
  1844. # Remove anything else in the AppGUI
  1845. self.ui.tool_scroll_area.takeWidget()
  1846. # update the geo object options so it is including the bounding box values
  1847. try:
  1848. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1849. edited_obj.options['xmin'] = xmin
  1850. edited_obj.options['ymin'] = ymin
  1851. edited_obj.options['xmax'] = xmax
  1852. edited_obj.options['ymax'] = ymax
  1853. except AttributeError as e:
  1854. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1855. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1856. edited_obj.build_ui()
  1857. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1858. elif isinstance(edited_obj, GerberObject):
  1859. obj_type = "Gerber"
  1860. if cleanup is None:
  1861. self.grb_editor.update_fcgerber()
  1862. self.grb_editor.update_options(edited_obj)
  1863. self.grb_editor.deactivate_grb_editor()
  1864. # delete the old object (the source object) if it was an empty one
  1865. try:
  1866. if len(edited_obj.solid_geometry) == 0:
  1867. old_name = edited_obj.options['name']
  1868. self.collection.set_active(old_name)
  1869. self.collection.delete_active()
  1870. except TypeError:
  1871. # if the solid_geometry is a single Polygon the len() will not work
  1872. # in any case, falling here means that we have something in the solid_geometry, even if only
  1873. # a single Polygon, therefore we pass this
  1874. pass
  1875. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1876. # restore GUI to the Selected TAB
  1877. # Remove anything else in the AppGUI
  1878. self.ui.selected_scroll_area.takeWidget()
  1879. elif isinstance(edited_obj, ExcellonObject):
  1880. obj_type = "Excellon"
  1881. if cleanup is None:
  1882. self.exc_editor.update_fcexcellon(edited_obj)
  1883. # self.exc_editor.update_options(edited_obj)
  1884. self.exc_editor.deactivate()
  1885. # restore GUI to the Selected TAB
  1886. # Remove anything else in the AppGUI
  1887. self.ui.tool_scroll_area.takeWidget()
  1888. # delete the old object (the source object) if it was an empty one
  1889. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1890. old_name = edited_obj.options['name']
  1891. self.collection.delete_by_name(name=old_name)
  1892. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1893. else:
  1894. self.inform.emit('[WARNING_NOTCL] %s' %
  1895. _("Select a Gerber, Geometry or Excellon Object to update."))
  1896. return
  1897. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1898. elif response == bt_no:
  1899. # clean the Tools Tab
  1900. self.ui.tool_scroll_area.takeWidget()
  1901. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1902. self.ui.notebook.setTabText(2, "Tool")
  1903. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1904. if isinstance(edited_obj, GeometryObject):
  1905. self.geo_editor.deactivate()
  1906. edited_obj.build_ui()
  1907. elif isinstance(edited_obj, GerberObject):
  1908. self.grb_editor.deactivate_grb_editor()
  1909. edited_obj.build_ui()
  1910. elif isinstance(edited_obj, ExcellonObject):
  1911. self.exc_editor.deactivate()
  1912. edited_obj.build_ui()
  1913. else:
  1914. self.inform.emit('[WARNING_NOTCL] %s' %
  1915. _("Select a Gerber, Geometry or Excellon Object to update."))
  1916. return
  1917. elif response == bt_cancel:
  1918. return
  1919. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1920. # edited_obj.build_ui()
  1921. # Switch notebook to Selected page
  1922. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1923. else:
  1924. if isinstance(edited_obj, GeometryObject):
  1925. self.geo_editor.deactivate()
  1926. elif isinstance(edited_obj, GerberObject):
  1927. self.grb_editor.deactivate_grb_editor()
  1928. elif isinstance(edited_obj, ExcellonObject):
  1929. self.exc_editor.deactivate()
  1930. else:
  1931. self.inform.emit('[WARNING_NOTCL] %s' %
  1932. _("Select a Gerber, Geometry or Excellon Object to update."))
  1933. return
  1934. # if notebook is hidden we show it
  1935. if self.ui.splitter.sizes()[0] == 0:
  1936. self.ui.splitter.setSizes([1, 1])
  1937. # restore the call_source to app
  1938. self.call_source = 'app'
  1939. edited_obj.plot()
  1940. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1941. self.ui.plot_tab_area.protectTab(0)
  1942. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1943. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1944. self.ui.project_frame.setDisabled(False)
  1945. def get_last_folder(self):
  1946. """
  1947. Get the folder path from where the last file was opened.
  1948. :return: String, last opened folder path
  1949. """
  1950. return self.defaults["global_last_folder"]
  1951. def get_last_save_folder(self):
  1952. """
  1953. Get the folder path from where the last file was saved.
  1954. :return: String, last saved folder path
  1955. """
  1956. loc = self.defaults["global_last_save_folder"]
  1957. if loc is None:
  1958. loc = self.defaults["global_last_folder"]
  1959. if loc is None:
  1960. loc = os.path.dirname(__file__)
  1961. return loc
  1962. def info(self, msg):
  1963. """
  1964. Informs the user. Normally on the status bar, optionally
  1965. also on the shell.
  1966. :param msg: Text to write.
  1967. :return: None
  1968. """
  1969. # Type of message in brackets at the beginning of the message.
  1970. match = re.search(r"\[(.*)\](.*)", msg)
  1971. if match:
  1972. level = match.group(1)
  1973. msg_ = match.group(2)
  1974. self.ui.fcinfo.set_status(str(msg_), level=level)
  1975. if level.lower() == "error":
  1976. self.shell_message(msg, error=True, show=True)
  1977. elif level.lower() == "warning":
  1978. self.shell_message(msg, warning=True, show=True)
  1979. elif level.lower() == "error_notcl":
  1980. self.shell_message(msg, error=True, show=False)
  1981. elif level.lower() == "warning_notcl":
  1982. self.shell_message(msg, warning=True, show=False)
  1983. elif level.lower() == "success":
  1984. self.shell_message(msg, success=True, show=False)
  1985. elif level.lower() == "selected":
  1986. self.shell_message(msg, selected=True, show=False)
  1987. else:
  1988. self.shell_message(msg, show=False)
  1989. else:
  1990. self.ui.fcinfo.set_status(str(msg), level="info")
  1991. # make sure that if the message is to clear the infobar with a space
  1992. # is not printed over and over on the shell
  1993. if msg != '':
  1994. self.shell_message(msg)
  1995. def on_import_preferences(self):
  1996. """
  1997. Loads the application default settings from a saved file into
  1998. ``self.defaults`` dictionary.
  1999. :return: None
  2000. """
  2001. self.defaults.report_usage("on_import_preferences")
  2002. App.log.debug("App.on_import_preferences()")
  2003. # Show file chooser
  2004. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2005. try:
  2006. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2007. directory=self.data_path,
  2008. filter=filter_)
  2009. except TypeError:
  2010. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2011. filter=filter_)
  2012. filename = str(filename)
  2013. if filename == "":
  2014. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2015. return
  2016. # Load in the defaults from the chosen file
  2017. self.defaults.load(filename=filename)
  2018. self.preferencesUiManager.on_preferences_edited()
  2019. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2020. def on_export_preferences(self):
  2021. """
  2022. Save the defaults dictionary to a file.
  2023. :return: None
  2024. """
  2025. self.defaults.report_usage("on_export_preferences")
  2026. App.log.debug("on_export_preferences()")
  2027. # defaults_file_content = None
  2028. # Show file chooser
  2029. date = str(datetime.today()).rpartition('.')[0]
  2030. date = ''.join(c for c in date if c not in ':-')
  2031. date = date.replace(' ', '_')
  2032. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2033. try:
  2034. filename, _f = FCFileSaveDialog.get_saved_filename(
  2035. caption=_("Export FlatCAM Preferences"),
  2036. directory=self.data_path + '/preferences_' + date,
  2037. filter=filter__
  2038. )
  2039. except TypeError:
  2040. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2041. filename = str(filename)
  2042. if filename == "":
  2043. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2044. return
  2045. # Update options
  2046. self.preferencesUiManager.defaults_read_form()
  2047. self.defaults.propagate_defaults()
  2048. # Save update options
  2049. try:
  2050. self.defaults.write(filename=filename)
  2051. except Exception:
  2052. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2053. return
  2054. if self.defaults["global_open_style"] is False:
  2055. self.file_opened.emit("preferences", filename)
  2056. self.file_saved.emit("preferences", filename)
  2057. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2058. def save_to_file(self, content_to_save, txt_content):
  2059. """
  2060. Save something to a file.
  2061. :return: None
  2062. """
  2063. self.defaults.report_usage("save_to_file")
  2064. App.log.debug("save_to_file()")
  2065. self.date = str(datetime.today()).rpartition('.')[0]
  2066. self.date = ''.join(c for c in self.date if c not in ':-')
  2067. self.date = self.date.replace(' ', '_')
  2068. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2069. path_to_save = self.defaults["global_last_save_folder"] if \
  2070. self.defaults["global_last_save_folder"] is not None else self.data_path
  2071. try:
  2072. filename, _f = FCFileSaveDialog.get_saved_filename(
  2073. caption=_("Save to file"),
  2074. directory=path_to_save + '/file_' + self.date,
  2075. filter=filter__
  2076. )
  2077. except TypeError:
  2078. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2079. filename = str(filename)
  2080. if filename == "":
  2081. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2082. return
  2083. else:
  2084. try:
  2085. with open(filename, 'w') as f:
  2086. ___ = f.read()
  2087. except PermissionError:
  2088. self.inform.emit('[WARNING] %s' %
  2089. _("Permission denied, saving not possible.\n"
  2090. "Most likely another app is holding the file open and not accessible."))
  2091. return
  2092. except IOError:
  2093. App.log.debug('Creating a new file ...')
  2094. f = open(filename, 'w')
  2095. f.close()
  2096. except Exception:
  2097. e = sys.exc_info()[0]
  2098. App.log.error("Could not load the file.")
  2099. App.log.error(str(e))
  2100. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2101. return
  2102. # Save content
  2103. if filename.rpartition('.')[2].lower() == 'html':
  2104. file_content = content_to_save
  2105. else:
  2106. file_content = txt_content
  2107. try:
  2108. with open(filename, "w") as f:
  2109. f.write(file_content)
  2110. except Exception:
  2111. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2112. return
  2113. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2114. def save_geometry(self, x, y, width, height, notebook_width):
  2115. """
  2116. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2117. launch of the application.
  2118. :param x: X position of the main window
  2119. :param y: Y position of the main window
  2120. :param width: width of the main window
  2121. :param height: height of the main window
  2122. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2123. :return: None
  2124. """
  2125. self.defaults["global_def_win_x"] = x
  2126. self.defaults["global_def_win_y"] = y
  2127. self.defaults["global_def_win_w"] = width
  2128. self.defaults["global_def_win_h"] = height
  2129. self.defaults["global_def_notebook_width"] = notebook_width
  2130. self.preferencesUiManager.save_defaults()
  2131. def register_recent(self, kind, filename):
  2132. """
  2133. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2134. dictionary.
  2135. :param kind: type of file that was opened
  2136. :param filename: the path and file name for the file that was opened
  2137. :return:
  2138. """
  2139. self.log.debug("register_recent()")
  2140. self.log.debug(" %s" % kind)
  2141. self.log.debug(" %s" % filename)
  2142. record = {'kind': str(kind), 'filename': str(filename)}
  2143. if record in self.recent:
  2144. return
  2145. if record in self.recent_projects:
  2146. return
  2147. if record['kind'] == 'project':
  2148. self.recent_projects.insert(0, record)
  2149. else:
  2150. self.recent.insert(0, record)
  2151. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2152. self.recent.pop()
  2153. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2154. self.recent_projects.pop()
  2155. try:
  2156. f = open(self.data_path + '/recent.json', 'w')
  2157. except IOError:
  2158. App.log.error("Failed to open recent items file for writing.")
  2159. self.inform.emit('[ERROR_NOTCL] %s' %
  2160. _('Failed to open recent files file for writing.'))
  2161. return
  2162. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2163. f.close()
  2164. try:
  2165. fp = open(self.data_path + '/recent_projects.json', 'w')
  2166. except IOError:
  2167. App.log.error("Failed to open recent items file for writing.")
  2168. self.inform.emit('[ERROR_NOTCL] %s' %
  2169. _('Failed to open recent projects file for writing.'))
  2170. return
  2171. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2172. fp.close()
  2173. # Re-build the recent items menu
  2174. self.setup_recent_items()
  2175. def new_object(self, kind, name, initialize, plot=True, autoselected=True):
  2176. """
  2177. Creates a new specialized FlatCAMObj and attaches it to the application,
  2178. this is, updates the GUI accordingly, any other records and plots it.
  2179. This method is thread-safe.
  2180. Notes:
  2181. * If the name is in use, the self.collection will modify it
  2182. when appending it to the collection. There is no need to handle
  2183. name conflicts here.
  2184. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2185. :type kind: str
  2186. :param name: Name for the object.
  2187. :type name: str
  2188. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2189. The function is called with 2 parameters: the new object and the App instance.
  2190. :type initialize: function
  2191. :param plot: If to plot the resulting object
  2192. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2193. self.collection
  2194. :return: None
  2195. :rtype: None
  2196. """
  2197. App.log.debug("new_object()")
  2198. obj_plot = plot
  2199. obj_autoselected = autoselected
  2200. t0 = time.time() # Debug
  2201. # ## Create object
  2202. classdict = {
  2203. "gerber": GerberObject,
  2204. "excellon": ExcellonObject,
  2205. "cncjob": CNCJobObject,
  2206. "geometry": GeometryObject,
  2207. "script": ScriptObject,
  2208. "document": DocumentObject
  2209. }
  2210. App.log.debug("Calling object constructor...")
  2211. # Object creation/instantiation
  2212. obj = classdict[kind](name)
  2213. obj.units = self.options["units"]
  2214. # IMPORTANT
  2215. # The key names in defaults and options dictionary's are not random:
  2216. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2217. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2218. # copied to self.options. After that, below, depending on the type of
  2219. # object that is created, it will strip the name of the object and the underline (if the original key was
  2220. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2221. # "toolchange"
  2222. for option in self.options:
  2223. if option.find(kind + "_") == 0:
  2224. oname = option[len(kind) + 1:]
  2225. obj.options[oname] = self.options[option]
  2226. obj.isHovering = False
  2227. obj.notHovering = True
  2228. # Initialize as per user request
  2229. # User must take care to implement initialize
  2230. # in a thread-safe way as is is likely that we
  2231. # have been invoked in a separate thread.
  2232. t1 = time.time()
  2233. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2234. try:
  2235. return_value = initialize(obj, self)
  2236. except Exception as e:
  2237. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2238. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2239. msg += traceback.format_exc()
  2240. self.inform.emit(msg)
  2241. return "fail"
  2242. t2 = time.time()
  2243. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2244. if return_value == 'fail':
  2245. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2246. return "fail"
  2247. # Check units and convert if necessary
  2248. # This condition CAN be true because initialize() can change obj.units
  2249. if self.options["units"].upper() != obj.units.upper():
  2250. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2251. obj.convert_units(self.options["units"])
  2252. t3 = time.time()
  2253. self.log.debug("%f seconds converting units." % (t3 - t2))
  2254. # Create the bounding box for the object and then add the results to the obj.options
  2255. # But not for Scripts or for Documents
  2256. if kind != 'document' and kind != 'script':
  2257. try:
  2258. xmin, ymin, xmax, ymax = obj.bounds()
  2259. obj.options['xmin'] = xmin
  2260. obj.options['ymin'] = ymin
  2261. obj.options['xmax'] = xmax
  2262. obj.options['ymax'] = ymax
  2263. except Exception as e:
  2264. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2265. return "fail"
  2266. try:
  2267. if kind == 'excellon':
  2268. obj.fill_color = self.defaults["excellon_plot_fill"]
  2269. obj.outline_color = self.defaults["excellon_plot_line"]
  2270. if kind == 'gerber':
  2271. obj.fill_color = self.defaults["gerber_plot_fill"]
  2272. obj.outline_color = self.defaults["gerber_plot_line"]
  2273. except Exception as e:
  2274. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2275. # update the KeyWords list with the name of the file
  2276. self.myKeywords.append(obj.options['name'])
  2277. log.debug("Moving new object back to main thread.")
  2278. # Move the object to the main thread and let the app know that it is available.
  2279. obj.moveToThread(self.main_thread)
  2280. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2281. return obj
  2282. def new_excellon_object(self):
  2283. """
  2284. Creates a new, blank Excellon object.
  2285. :return: None
  2286. """
  2287. self.defaults.report_usage("new_excellon_object()")
  2288. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2289. def new_geometry_object(self):
  2290. """
  2291. Creates a new, blank and single-tool Geometry object.
  2292. :return: None
  2293. """
  2294. self.defaults.report_usage("new_geometry_object()")
  2295. def initialize(obj, app):
  2296. obj.multitool = False
  2297. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2298. def new_gerber_object(self):
  2299. """
  2300. Creates a new, blank Gerber object.
  2301. :return: None
  2302. """
  2303. self.defaults.report_usage("new_gerber_object()")
  2304. def initialize(grb_obj, app):
  2305. grb_obj.multitool = False
  2306. grb_obj.source_file = []
  2307. grb_obj.multigeo = False
  2308. grb_obj.follow = False
  2309. grb_obj.apertures = {}
  2310. grb_obj.solid_geometry = []
  2311. try:
  2312. grb_obj.options['xmin'] = 0
  2313. grb_obj.options['ymin'] = 0
  2314. grb_obj.options['xmax'] = 0
  2315. grb_obj.options['ymax'] = 0
  2316. except KeyError:
  2317. pass
  2318. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2319. def new_script_object(self):
  2320. """
  2321. Creates a new, blank TCL Script object.
  2322. :return: None
  2323. """
  2324. self.defaults.report_usage("new_script_object()")
  2325. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2326. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2327. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2328. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2329. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2330. # "ListSys, MillDrills,\n" \
  2331. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2332. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2333. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2334. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2335. # "# SubtractRectangle, Version, WriteGCode\n"
  2336. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2337. '# %s:\n' % _('TCL Tutorial is here') + \
  2338. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2339. '# %s:\n' % _("FlatCAM commands list")
  2340. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2341. "(displayed in Tcl Shell).")
  2342. def initialize(obj, app):
  2343. obj.source_file = deepcopy(new_source_file)
  2344. outname = 'new_script'
  2345. self.new_object('script', outname, initialize, plot=False)
  2346. def new_document_object(self):
  2347. """
  2348. Creates a new, blank Document object.
  2349. :return: None
  2350. """
  2351. self.defaults.report_usage("new_document_object()")
  2352. def initialize(obj, app):
  2353. obj.source_file = ""
  2354. self.new_object('document', 'new_document', initialize, plot=False)
  2355. def on_object_created(self, obj, plot, auto_select):
  2356. """
  2357. Event callback for object creation.
  2358. It will add the new object to the collection. After that it will plot the object in a threaded way
  2359. :param obj: The newly created FlatCAM object.
  2360. :param plot: if the newly create object t obe plotted
  2361. :param auto_select: if the newly created object to be autoselected after creation
  2362. :return: None
  2363. """
  2364. t0 = time.time() # DEBUG
  2365. self.log.debug("on_object_created()")
  2366. # The Collection might change the name if there is a collision
  2367. self.collection.append(obj)
  2368. # after adding the object to the collection always update the list of objects that are in the collection
  2369. self.all_objects_list = self.collection.get_list()
  2370. # self.inform.emit('[selected] %s created & selected: %s' %
  2371. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2372. if obj.kind == 'gerber':
  2373. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2374. kind=obj.kind.capitalize(),
  2375. color='green',
  2376. name=str(obj.options['name']), tx=_("created/selected"))
  2377. )
  2378. elif obj.kind == 'excellon':
  2379. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2380. kind=obj.kind.capitalize(),
  2381. color='brown',
  2382. name=str(obj.options['name']), tx=_("created/selected"))
  2383. )
  2384. elif obj.kind == 'cncjob':
  2385. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2386. kind=obj.kind.capitalize(),
  2387. color='blue',
  2388. name=str(obj.options['name']), tx=_("created/selected"))
  2389. )
  2390. elif obj.kind == 'geometry':
  2391. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2392. kind=obj.kind.capitalize(),
  2393. color='red',
  2394. name=str(obj.options['name']), tx=_("created/selected"))
  2395. )
  2396. elif obj.kind == 'script':
  2397. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2398. kind=obj.kind.capitalize(),
  2399. color='orange',
  2400. name=str(obj.options['name']), tx=_("created/selected"))
  2401. )
  2402. elif obj.kind == 'document':
  2403. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2404. kind=obj.kind.capitalize(),
  2405. color='darkCyan',
  2406. name=str(obj.options['name']), tx=_("created/selected"))
  2407. )
  2408. # update the SHELL auto-completer model with the name of the new object
  2409. self.shell._edit.set_model_data(self.myKeywords)
  2410. if auto_select:
  2411. # select the just opened object but deselect the previous ones
  2412. self.collection.set_all_inactive()
  2413. self.collection.set_active(obj.options["name"])
  2414. else:
  2415. self.collection.set_all_inactive()
  2416. # here it is done the object plotting
  2417. def worker_task(t_obj):
  2418. with self.proc_container.new(_("Plotting")):
  2419. if isinstance(t_obj, CNCJobObject):
  2420. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2421. else:
  2422. t_obj.plot()
  2423. t1 = time.time() # DEBUG
  2424. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2425. self.object_plotted.emit(t_obj)
  2426. # Send to worker
  2427. # self.worker.add_task(worker_task, [self])
  2428. if plot is True:
  2429. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2430. def on_object_changed(self, obj):
  2431. """
  2432. Called whenever the geometry of the object was changed in some way.
  2433. This require the update of it's bounding values so it can be the selected on canvas.
  2434. Update the bounding box data from obj.options
  2435. :param obj: the object that was changed
  2436. :return: None
  2437. """
  2438. try:
  2439. xmin, ymin, xmax, ymax = obj.bounds()
  2440. except TypeError:
  2441. return
  2442. obj.options['xmin'] = xmin
  2443. obj.options['ymin'] = ymin
  2444. obj.options['xmax'] = xmax
  2445. obj.options['ymax'] = ymax
  2446. log.debug("Object changed, updating the bounding box data on self.options")
  2447. # delete the old selection shape
  2448. self.delete_selection_shape()
  2449. self.should_we_save = True
  2450. def on_object_plotted(self):
  2451. """
  2452. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2453. :return: None
  2454. """
  2455. self.on_zoom_fit(None)
  2456. def on_about(self):
  2457. """
  2458. Displays the "about" dialog found in the Menu --> Help.
  2459. :return: None
  2460. """
  2461. self.defaults.report_usage("on_about")
  2462. version = self.version
  2463. version_date = self.version_date
  2464. beta = self.beta
  2465. class AboutDialog(QtWidgets.QDialog):
  2466. def __init__(self, app, parent=None):
  2467. QtWidgets.QDialog.__init__(self, parent)
  2468. self.app = app
  2469. # Icon and title
  2470. self.setWindowIcon(parent.app_icon)
  2471. self.setWindowTitle(_("About FlatCAM"))
  2472. self.resize(600, 200)
  2473. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2474. # self.setStyleSheet(
  2475. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2476. # "background-attachment: fixed"
  2477. # )
  2478. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2479. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2480. # palette = QtGui.QPalette()
  2481. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2482. # self.setPalette(palette)
  2483. logo = QtWidgets.QLabel()
  2484. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2485. title = QtWidgets.QLabel(
  2486. "<font size=8><B>FlatCAM</B></font><BR>"
  2487. "{title}<BR>"
  2488. "<BR>"
  2489. "<BR>"
  2490. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2491. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2492. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2493. "<B>{issue}</B></a><BR>".format(
  2494. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2495. devel=_("Development"),
  2496. down=_("DOWNLOAD"),
  2497. issue=_("Issue tracker"))
  2498. )
  2499. title.setOpenExternalLinks(True)
  2500. closebtn = QtWidgets.QPushButton(_("Close"))
  2501. tab_widget = QtWidgets.QTabWidget()
  2502. description_label = QtWidgets.QLabel(
  2503. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2504. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2505. version=version,
  2506. beta=('BETA' if beta else ''),
  2507. date=version_date,
  2508. arch=platform.architecture()[0])
  2509. )
  2510. description_label.setOpenExternalLinks(True)
  2511. lic_lbl_header = QtWidgets.QLabel(
  2512. '%s:<br>%s<br>' % (
  2513. _('Licensed under the MIT license'),
  2514. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2515. "http://www.opensource.org/licenses/mit-license.php</a>"
  2516. )
  2517. )
  2518. lic_lbl_header.setOpenExternalLinks(True)
  2519. lic_lbl_body = QtWidgets.QLabel(
  2520. _(
  2521. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2522. 'of this software and associated documentation files (the "Software"), to deal\n'
  2523. 'in the Software without restriction, including without limitation the rights\n'
  2524. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2525. 'copies of the Software, and to permit persons to whom the Software is\n'
  2526. 'furnished to do so, subject to the following conditions:\n\n'
  2527. 'The above copyright notice and this permission notice shall be included in\n'
  2528. 'all copies or substantial portions of the Software.\n\n'
  2529. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2530. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2531. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2532. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2533. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2534. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2535. 'THE SOFTWARE.'
  2536. )
  2537. )
  2538. attributions_label = QtWidgets.QLabel(
  2539. _(
  2540. 'Some of the icons used are from the following sources:<br>'
  2541. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2542. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2543. 'title="Flaticon">www.flaticon.com</a></div>'
  2544. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2545. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2546. )
  2547. )
  2548. attributions_label.setOpenExternalLinks(True)
  2549. # layouts
  2550. layout1 = QtWidgets.QVBoxLayout()
  2551. layout1_1 = QtWidgets.QHBoxLayout()
  2552. layout1_2 = QtWidgets.QHBoxLayout()
  2553. layout2 = QtWidgets.QHBoxLayout()
  2554. layout3 = QtWidgets.QHBoxLayout()
  2555. self.setLayout(layout1)
  2556. layout1.addLayout(layout1_1)
  2557. layout1.addLayout(layout1_2)
  2558. layout1.addLayout(layout2)
  2559. layout1.addLayout(layout3)
  2560. layout1_1.addStretch()
  2561. layout1_1.addWidget(description_label)
  2562. layout1_2.addWidget(tab_widget)
  2563. self.splash_tab = QtWidgets.QWidget()
  2564. self.splash_tab.setObjectName("splash_about")
  2565. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2566. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2567. tab_widget.addTab(self.splash_tab, _("Splash"))
  2568. self.programmmers_tab = QtWidgets.QWidget()
  2569. self.programmmers_tab.setObjectName("programmers_about")
  2570. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2571. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2572. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2573. self.translators_tab = QtWidgets.QWidget()
  2574. self.translators_tab.setObjectName("translators_about")
  2575. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2576. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2577. tab_widget.addTab(self.translators_tab, _("Translators"))
  2578. self.license_tab = QtWidgets.QWidget()
  2579. self.license_tab.setObjectName("license_about")
  2580. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2581. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2582. tab_widget.addTab(self.license_tab, _("License"))
  2583. self.attributions_tab = QtWidgets.QWidget()
  2584. self.attributions_tab.setObjectName("attributions_about")
  2585. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2586. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2587. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2588. self.splash_tab_layout.addWidget(logo, stretch=0)
  2589. self.splash_tab_layout.addWidget(title, stretch=1)
  2590. pal = QtGui.QPalette()
  2591. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2592. self.prog_grid_lay = QtWidgets.QGridLayout()
  2593. self.prog_grid_lay.setHorizontalSpacing(20)
  2594. self.prog_grid_lay.setColumnStretch(0, 0)
  2595. self.prog_grid_lay.setColumnStretch(2, 1)
  2596. prog_widget = QtWidgets.QWidget()
  2597. prog_widget.setLayout(self.prog_grid_lay)
  2598. prog_scroll = QtWidgets.QScrollArea()
  2599. prog_scroll.setWidget(prog_widget)
  2600. prog_scroll.setWidgetResizable(True)
  2601. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2602. prog_scroll.setPalette(pal)
  2603. self.programmmers_tab_layout.addWidget(prog_scroll)
  2604. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2605. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2606. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2607. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2608. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2609. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2610. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2611. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2612. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2613. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2614. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2615. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2616. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2617. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2618. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2619. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2620. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2621. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2622. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2623. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2624. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2625. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2626. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2627. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2628. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2629. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2630. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2631. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2632. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2633. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2634. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2635. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2636. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2637. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2638. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2639. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2640. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2641. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2642. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2643. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2644. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2645. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2646. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2647. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2648. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2649. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2650. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2651. self.translator_grid_lay = QtWidgets.QGridLayout()
  2652. self.translator_grid_lay.setColumnStretch(0, 0)
  2653. self.translator_grid_lay.setColumnStretch(1, 0)
  2654. self.translator_grid_lay.setColumnStretch(2, 1)
  2655. self.translator_grid_lay.setColumnStretch(3, 0)
  2656. # trans_widget = QtWidgets.QWidget()
  2657. # trans_widget.setLayout(self.translator_grid_lay)
  2658. # self.translators_tab_layout.addWidget(trans_widget)
  2659. # self.translators_tab_layout.addStretch()
  2660. trans_widget = QtWidgets.QWidget()
  2661. trans_widget.setLayout(self.translator_grid_lay)
  2662. trans_scroll = QtWidgets.QScrollArea()
  2663. trans_scroll.setWidget(trans_widget)
  2664. trans_scroll.setWidgetResizable(True)
  2665. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2666. trans_scroll.setPalette(pal)
  2667. self.translators_tab_layout.addWidget(trans_scroll)
  2668. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2669. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2670. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2671. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2672. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2673. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2674. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2675. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2676. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2677. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2678. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2679. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2680. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2681. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2682. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2683. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2684. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2685. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2686. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2687. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2688. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2689. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2690. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2691. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2692. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2693. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2694. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2695. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2696. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2697. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2698. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2699. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2700. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2701. self.translator_grid_lay.setColumnStretch(0, 0)
  2702. self.translators_tab_layout.addStretch()
  2703. self.license_tab_layout.addWidget(lic_lbl_header)
  2704. self.license_tab_layout.addWidget(lic_lbl_body)
  2705. self.license_tab_layout.addStretch()
  2706. self.attributions_tab_layout.addWidget(attributions_label)
  2707. self.attributions_tab_layout.addStretch()
  2708. layout3.addStretch()
  2709. layout3.addWidget(closebtn)
  2710. closebtn.clicked.connect(self.accept)
  2711. AboutDialog(app=self, parent=self.ui).exec_()
  2712. def install_bookmarks(self, book_dict=None):
  2713. """
  2714. Install the bookmarks actions in the Help menu -> Bookmarks
  2715. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2716. :return: None
  2717. """
  2718. if book_dict is None:
  2719. self.defaults["global_bookmarks"].update(
  2720. {
  2721. '1': ['FlatCAM', "http://flatcam.org"],
  2722. '2': ['Backup Site', ""]
  2723. }
  2724. )
  2725. else:
  2726. self.defaults["global_bookmarks"].clear()
  2727. self.defaults["global_bookmarks"].update(book_dict)
  2728. # first try to disconnect if somehow they get connected from elsewhere
  2729. for act in self.ui.menuhelp_bookmarks.actions():
  2730. try:
  2731. act.triggered.disconnect()
  2732. except TypeError:
  2733. pass
  2734. # clear all actions except the last one who is the Bookmark manager
  2735. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2736. pass
  2737. else:
  2738. self.ui.menuhelp_bookmarks.removeAction(act)
  2739. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2740. if self.defaults["global_bookmarks"]:
  2741. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2742. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2743. # the JSON is first making the keys as strings (therefore I have to use strings too
  2744. # or do the conversion :(
  2745. # )
  2746. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2747. # the '10' entry jsut after '1' therefore ordering as strings
  2748. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2749. key=lambda x: int(x[0]))
  2750. for entry, bookmark in sorted_bookmarks:
  2751. title = bookmark[0]
  2752. weblink = bookmark[1]
  2753. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2754. act.setText(title)
  2755. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2756. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2757. if title == 'Backup Site' and weblink == "":
  2758. act.triggered.connect(self.on_backup_site)
  2759. else:
  2760. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2761. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2762. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2763. def on_bookmarks_manager(self):
  2764. """
  2765. Adds the bookmark manager in a Tab in Plot Area
  2766. :return:
  2767. """
  2768. for idx in range(self.ui.plot_tab_area.count()):
  2769. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2770. # there can be only one instance of Bookmark Manager at one time
  2771. return
  2772. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2773. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2774. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2775. # add the tab if it was closed
  2776. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2777. # delete the absolute and relative position and messages in the infobar
  2778. self.ui.position_label.setText("")
  2779. # self.ui.rel_position_label.setText("")
  2780. # Switch plot_area to preferences page
  2781. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2782. def on_backup_site(self):
  2783. msgbox = QtWidgets.QMessageBox()
  2784. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2785. "1. FlatCAM.org website is down\n"
  2786. "2. Someone forked FlatCAM project and wants to point\n"
  2787. "to his own website\n\n"
  2788. "If you can't get any informations about FlatCAM beta\n"
  2789. "use the YouTube channel link from the Help menu."))
  2790. msgbox.setWindowTitle(_("Alternative website"))
  2791. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2792. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2793. msgbox.setDefaultButton(bt_yes)
  2794. msgbox.exec_()
  2795. # response = msgbox.clickedButton()
  2796. def on_file_savedefaults(self):
  2797. """
  2798. Callback for menu item File->Save Defaults. Saves application default options
  2799. ``self.defaults`` to current_defaults.FlatConfig.
  2800. :return: None
  2801. """
  2802. self.preferencesUiManager.save_defaults()
  2803. def final_save(self):
  2804. """
  2805. Callback for doing a preferences save to file whenever the application is about to quit.
  2806. If the project has changes, it will ask the user to save the project.
  2807. :return: None
  2808. """
  2809. if self.save_in_progress:
  2810. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2811. return
  2812. if self.should_we_save and self.collection.get_list():
  2813. msgbox = QtWidgets.QMessageBox()
  2814. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2815. "\n"
  2816. "Do you want to Save the project?"))
  2817. msgbox.setWindowTitle(_("Save changes"))
  2818. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2819. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2820. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2821. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2822. msgbox.setDefaultButton(bt_yes)
  2823. msgbox.exec_()
  2824. response = msgbox.clickedButton()
  2825. if response == bt_yes:
  2826. try:
  2827. self.trayIcon.hide()
  2828. except Exception:
  2829. pass
  2830. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2831. elif response == bt_no:
  2832. try:
  2833. self.trayIcon.hide()
  2834. except Exception:
  2835. pass
  2836. self.quit_application()
  2837. elif response == bt_cancel:
  2838. return
  2839. else:
  2840. try:
  2841. self.trayIcon.hide()
  2842. except Exception:
  2843. pass
  2844. self.quit_application()
  2845. def quit_application(self):
  2846. """
  2847. Called (as a pyslot or not) when the application is quit.
  2848. :return: None
  2849. """
  2850. self.preferencesUiManager.save_defaults(silent=True)
  2851. log.debug("App.quit_application() --> App Defaults saved.")
  2852. if self.cmd_line_headless != 1:
  2853. # save app state to file
  2854. stgs = QSettings("Open Source", "FlatCAM")
  2855. stgs.setValue('saved_gui_state', self.ui.saveState())
  2856. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2857. stgs.setValue(
  2858. 'language',
  2859. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2860. )
  2861. stgs.setValue(
  2862. 'notebook_font_size',
  2863. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2864. )
  2865. stgs.setValue(
  2866. 'axis_font_size',
  2867. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2868. )
  2869. stgs.setValue(
  2870. 'textbox_font_size',
  2871. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2872. )
  2873. stgs.setValue(
  2874. 'hud_font_size',
  2875. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2876. )
  2877. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2878. stgs.setValue(
  2879. 'machinist',
  2880. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2881. )
  2882. # This will write the setting to the platform specific storage.
  2883. del stgs
  2884. log.debug("App.quit_application() --> App UI state saved.")
  2885. # try to quit the Socket opened by ArgsThread class
  2886. try:
  2887. self.new_launch.stop.emit()
  2888. except Exception as err:
  2889. log.debug("App.quit_application() --> %s" % str(err))
  2890. # try to quit the QThread that run ArgsThread class
  2891. try:
  2892. self.th.quit()
  2893. except Exception as e:
  2894. log.debug("App.quit_application() --> %s" % str(e))
  2895. # terminate workers
  2896. self.workers.__del__()
  2897. # quit app by signalling for self.kill_app() method
  2898. # self.close_app_signal.emit()
  2899. QtWidgets.qApp.quit()
  2900. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2901. # we use the following command
  2902. minor_v = sys.version_info.minor
  2903. if minor_v < 8:
  2904. sys.exit(0)
  2905. else:
  2906. os._exit(0) # fix to work with Python 3.8
  2907. @staticmethod
  2908. def kill_app():
  2909. QtWidgets.qApp.quit()
  2910. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2911. # we use the following command
  2912. sys.exit(0)
  2913. def on_portable_checked(self, state):
  2914. """
  2915. Callback called when the checkbox in Preferences GUI is checked.
  2916. It will set the application as portable by creating the preferences and recent files in the
  2917. 'config' folder found in the FlatCAM installation folder.
  2918. :param state: boolean, the state of the checkbox when clicked/checked
  2919. :return:
  2920. """
  2921. line_no = 0
  2922. data = None
  2923. if sys.platform != 'win32':
  2924. # this won't work in Linux or MacOS
  2925. return
  2926. # test if the app was frozen and choose the path for the configuration file
  2927. if getattr(sys, "frozen", False) is True:
  2928. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2929. else:
  2930. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2931. config_file = current_data_path + '\\configuration.txt'
  2932. try:
  2933. with open(config_file, 'r') as f:
  2934. try:
  2935. data = f.readlines()
  2936. except Exception as e:
  2937. log.debug('App.__init__() -->%s' % str(e))
  2938. return
  2939. except FileNotFoundError:
  2940. pass
  2941. for line in data:
  2942. line = line.strip('\n')
  2943. param = str(line).rpartition('=')
  2944. if param[0] == 'portable':
  2945. break
  2946. line_no += 1
  2947. if state:
  2948. data[line_no] = 'portable=True\n'
  2949. # create the new defauults files
  2950. # create current_defaults.FlatConfig file if there is none
  2951. try:
  2952. f = open(current_data_path + '/current_defaults.FlatConfig')
  2953. f.close()
  2954. except IOError:
  2955. App.log.debug('Creating empty current_defaults.FlatConfig')
  2956. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2957. json.dump({}, f)
  2958. f.close()
  2959. # create factory_defaults.FlatConfig file if there is none
  2960. try:
  2961. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2962. f.close()
  2963. except IOError:
  2964. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2965. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2966. json.dump({}, f)
  2967. f.close()
  2968. try:
  2969. f = open(current_data_path + '/recent.json')
  2970. f.close()
  2971. except IOError:
  2972. App.log.debug('Creating empty recent.json')
  2973. f = open(current_data_path + '/recent.json', 'w')
  2974. json.dump([], f)
  2975. f.close()
  2976. try:
  2977. fp = open(current_data_path + '/recent_projects.json')
  2978. fp.close()
  2979. except IOError:
  2980. App.log.debug('Creating empty recent_projects.json')
  2981. fp = open(current_data_path + '/recent_projects.json', 'w')
  2982. json.dump([], fp)
  2983. fp.close()
  2984. # save the current defaults to the new defaults file
  2985. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2986. else:
  2987. data[line_no] = 'portable=False\n'
  2988. with open(config_file, 'w') as f:
  2989. f.writelines(data)
  2990. def on_register_files(self, obj_type=None):
  2991. """
  2992. Called whenever there is a need to register file extensions with FlatCAM.
  2993. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2994. :param obj_type: the type of object to be register for.
  2995. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2996. :return: None
  2997. """
  2998. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2999. new_reg_path = 'Software\\Classes\\'
  3000. # find if the current user is admin
  3001. try:
  3002. is_admin = os.getuid() == 0
  3003. except AttributeError:
  3004. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3005. if is_admin is True:
  3006. root_path = winreg.HKEY_LOCAL_MACHINE
  3007. else:
  3008. root_path = winreg.HKEY_CURRENT_USER
  3009. # create the keys
  3010. def set_reg(name, root_pth, new_reg_path, value):
  3011. try:
  3012. winreg.CreateKey(root_pth, new_reg_path)
  3013. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3014. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3015. return True
  3016. except WindowsError:
  3017. return False
  3018. # delete key in registry
  3019. def delete_reg(root_pth, reg_path, key_to_del):
  3020. key_to_del_path = reg_path + key_to_del
  3021. try:
  3022. winreg.DeleteKey(root_pth, key_to_del_path)
  3023. return True
  3024. except WindowsError:
  3025. return False
  3026. if obj_type is None or obj_type == 'excellon':
  3027. exc_list = \
  3028. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3029. exc_list = [x for x in exc_list if x != '']
  3030. # register all keys in the Preferences window
  3031. for ext in exc_list:
  3032. new_k = new_reg_path + '.%s' % ext
  3033. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3034. # and unregister those that are no longer in the Preferences windows but are in the file
  3035. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3036. if ext not in exc_list:
  3037. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3038. # now write the updated extensions to the self.defaults
  3039. # new_ext = ''
  3040. # for ext in exc_list:
  3041. # new_ext = new_ext + ext + ', '
  3042. # self.defaults["fa_excellon"] = new_ext
  3043. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3044. if obj_type is None or obj_type == 'gcode':
  3045. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3046. gco_list = [x for x in gco_list if x != '']
  3047. # register all keys in the Preferences window
  3048. for ext in gco_list:
  3049. new_k = new_reg_path + '.%s' % ext
  3050. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3051. # and unregister those that are no longer in the Preferences windows but are in the file
  3052. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3053. if ext not in gco_list:
  3054. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3055. # now write the updated extensions to the self.defaults
  3056. # new_ext = ''
  3057. # for ext in gco_list:
  3058. # new_ext = new_ext + ext + ', '
  3059. # self.defaults["fa_gcode"] = new_ext
  3060. self.inform.emit('[success] %s' %
  3061. _("Selected GCode file extensions registered with FlatCAM."))
  3062. if obj_type is None or obj_type == 'gerber':
  3063. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3064. grb_list = [x for x in grb_list if x != '']
  3065. # register all keys in the Preferences window
  3066. for ext in grb_list:
  3067. new_k = new_reg_path + '.%s' % ext
  3068. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3069. # and unregister those that are no longer in the Preferences windows but are in the file
  3070. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3071. if ext not in grb_list:
  3072. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3073. # now write the updated extensions to the self.defaults
  3074. # new_ext = ''
  3075. # for ext in grb_list:
  3076. # new_ext = new_ext + ext + ', '
  3077. # self.defaults["fa_gerber"] = new_ext
  3078. self.inform.emit('[success] %s' %
  3079. _("Selected Gerber file extensions registered with FlatCAM."))
  3080. def add_extension(self, ext_type):
  3081. """
  3082. Add a file extension to the list for a specific object
  3083. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3084. :return:
  3085. """
  3086. if ext_type == 'excellon':
  3087. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3088. if new_ext == '':
  3089. return
  3090. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3091. if new_ext in old_val:
  3092. return
  3093. old_val.append(new_ext)
  3094. old_val.sort()
  3095. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3096. if ext_type == 'gcode':
  3097. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3098. if new_ext == '':
  3099. return
  3100. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3101. if new_ext in old_val:
  3102. return
  3103. old_val.append(new_ext)
  3104. old_val.sort()
  3105. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3106. if ext_type == 'gerber':
  3107. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3108. if new_ext == '':
  3109. return
  3110. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3111. if new_ext in old_val:
  3112. return
  3113. old_val.append(new_ext)
  3114. old_val.sort()
  3115. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3116. if ext_type == 'keyword':
  3117. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3118. if new_kw == '':
  3119. return
  3120. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3121. if new_kw in old_val:
  3122. return
  3123. old_val.append(new_kw)
  3124. old_val.sort()
  3125. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3126. # update the self.myKeywords so the model is updated
  3127. self.autocomplete_kw_list = \
  3128. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3129. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3130. self.shell._edit.set_model_data(self.myKeywords)
  3131. def del_extension(self, ext_type):
  3132. """
  3133. Remove a file extension from the list for a specific object
  3134. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3135. :return:
  3136. """
  3137. if ext_type == 'excellon':
  3138. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3139. if new_ext == '':
  3140. return
  3141. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3142. if new_ext not in old_val:
  3143. return
  3144. old_val.remove(new_ext)
  3145. old_val.sort()
  3146. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3147. if ext_type == 'gcode':
  3148. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3149. if new_ext == '':
  3150. return
  3151. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3152. if new_ext not in old_val:
  3153. return
  3154. old_val.remove(new_ext)
  3155. old_val.sort()
  3156. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3157. if ext_type == 'gerber':
  3158. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3159. if new_ext == '':
  3160. return
  3161. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3162. if new_ext not in old_val:
  3163. return
  3164. old_val.remove(new_ext)
  3165. old_val.sort()
  3166. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3167. if ext_type == 'keyword':
  3168. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3169. if new_kw == '':
  3170. return
  3171. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3172. if new_kw not in old_val:
  3173. return
  3174. old_val.remove(new_kw)
  3175. old_val.sort()
  3176. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3177. # update the self.myKeywords so the model is updated
  3178. self.autocomplete_kw_list = \
  3179. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3180. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3181. self.shell._edit.set_model_data(self.myKeywords)
  3182. def restore_extensions(self, ext_type):
  3183. """
  3184. Restore all file extensions associations with FlatCAM, for a specific object
  3185. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3186. :return:
  3187. """
  3188. if ext_type == 'excellon':
  3189. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3190. # for the ability to open Excellon files with .txt extension
  3191. new_exc_list = deepcopy(self.exc_list)
  3192. try:
  3193. new_exc_list.remove('txt')
  3194. except ValueError:
  3195. pass
  3196. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3197. if ext_type == 'gcode':
  3198. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3199. if ext_type == 'gerber':
  3200. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3201. if ext_type == 'keyword':
  3202. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3203. # update the self.myKeywords so the model is updated
  3204. self.autocomplete_kw_list = self.default_keywords
  3205. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3206. self.shell._edit.set_model_data(self.myKeywords)
  3207. def delete_all_extensions(self, ext_type):
  3208. """
  3209. Delete all file extensions associations with FlatCAM, for a specific object
  3210. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3211. :return:
  3212. """
  3213. if ext_type == 'excellon':
  3214. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3215. if ext_type == 'gcode':
  3216. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3217. if ext_type == 'gerber':
  3218. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3219. if ext_type == 'keyword':
  3220. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3221. # update the self.myKeywords so the model is updated
  3222. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3223. self.shell._edit.set_model_data(self.myKeywords)
  3224. def on_edit_join(self, name=None):
  3225. """
  3226. Callback for Edit->Join. Joins the selected geometry objects into
  3227. a new one.
  3228. :return: None
  3229. """
  3230. self.defaults.report_usage("on_edit_join()")
  3231. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3232. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3233. geo_type_set = set()
  3234. objs = self.collection.get_selected()
  3235. if len(objs) < 2:
  3236. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3237. (_("At least two objects are required for join. AppObjects currently selected"), len(objs)))
  3238. return 'fail'
  3239. for obj in objs:
  3240. geo_type_set.add(obj.multigeo)
  3241. # if len(geo_type_list) == 1 means that all list elements are the same
  3242. if len(geo_type_set) != 1:
  3243. self.inform.emit('[ERROR] %s' %
  3244. _("Failed join. The Geometry objects are of different types.\n"
  3245. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3246. "convert from one to another and retry joining \n"
  3247. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3248. "the result may not be what was expected. \n"
  3249. "Check the generated GCODE."))
  3250. return
  3251. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3252. if True in geo_type_set:
  3253. def initialize(geo_obj, app):
  3254. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3255. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3256. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3257. for v in geo_obj.tools.values():
  3258. v['data']['name'] = obj_name_multi
  3259. self.new_object("geometry", obj_name_multi, initialize)
  3260. else:
  3261. def initialize(geo_obj, app):
  3262. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3263. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3264. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3265. for v in geo_obj.tools.values():
  3266. v['data']['name'] = obj_name_single
  3267. self.new_object("geometry", obj_name_single, initialize)
  3268. self.should_we_save = True
  3269. def on_edit_join_exc(self):
  3270. """
  3271. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3272. a new Excellon.
  3273. :return: None
  3274. """
  3275. self.defaults.report_usage("on_edit_join_exc()")
  3276. objs = self.collection.get_selected()
  3277. for obj in objs:
  3278. if not isinstance(obj, ExcellonObject):
  3279. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3280. return
  3281. if len(objs) < 2:
  3282. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3283. (_("At least two objects are required for join. AppObjects currently selected"), len(objs)))
  3284. return 'fail'
  3285. def initialize(exc_obj, app):
  3286. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3287. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3288. self.new_object("excellon", 'Combo_Excellon', initialize)
  3289. self.should_we_save = True
  3290. def on_edit_join_grb(self):
  3291. """
  3292. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3293. a new Gerber object.
  3294. :return: None
  3295. """
  3296. self.defaults.report_usage("on_edit_join_grb()")
  3297. objs = self.collection.get_selected()
  3298. for obj in objs:
  3299. if not isinstance(obj, GerberObject):
  3300. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3301. return
  3302. if len(objs) < 2:
  3303. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3304. (_("At least two objects are required for join. AppObjects currently selected"), len(objs)))
  3305. return 'fail'
  3306. def initialize(grb_obj, app):
  3307. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3308. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3309. self.new_object("gerber", 'Combo_Gerber', initialize)
  3310. self.should_we_save = True
  3311. def on_convert_singlegeo_to_multigeo(self):
  3312. """
  3313. Called for converting a Geometry object from single-geo to multi-geo.
  3314. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3315. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3316. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3317. the solid-geometry of that tool.
  3318. :return: None
  3319. """
  3320. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3321. obj = self.collection.get_active()
  3322. if obj is None:
  3323. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3324. return
  3325. if not isinstance(obj, GeometryObject):
  3326. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3327. return
  3328. obj.multigeo = True
  3329. for tooluid, dict_value in obj.tools.items():
  3330. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3331. if not isinstance(obj.solid_geometry, list):
  3332. obj.solid_geometry = [obj.solid_geometry]
  3333. # obj.solid_geometry[:] = []
  3334. obj.plot()
  3335. self.should_we_save = True
  3336. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3337. def on_convert_multigeo_to_singlegeo(self):
  3338. """
  3339. Called for converting a Geometry object from multi-geo to single-geo.
  3340. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3341. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3342. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3343. the solid-geometry of that tool.
  3344. :return: None
  3345. """
  3346. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3347. obj = self.collection.get_active()
  3348. if obj is None:
  3349. self.inform.emit('[ERROR_NOTCL] %s' %
  3350. _("Failed. Select a Geometry Object and try again."))
  3351. return
  3352. if not isinstance(obj, GeometryObject):
  3353. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3354. (_("Expected a GeometryObject, got"), type(obj)))
  3355. return
  3356. obj.multigeo = False
  3357. total_solid_geometry = []
  3358. for tooluid, dict_value in obj.tools.items():
  3359. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3360. # clear the original geometry
  3361. dict_value['solid_geometry'][:] = []
  3362. obj.solid_geometry = deepcopy(total_solid_geometry)
  3363. obj.plot()
  3364. self.should_we_save = True
  3365. self.inform.emit('[success] %s' %
  3366. _("A Geometry object was converted to SingleGeo type."))
  3367. def on_defaults_dict_change(self, field):
  3368. """
  3369. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3370. Edit -> Preferences tab window.
  3371. :param field: the key of the self.defaults dictionary that was changed.
  3372. :return: None
  3373. """
  3374. self.preferencesUiManager.defaults_write_form_field(field=field)
  3375. if field == "units":
  3376. self.set_screen_units(self.defaults['units'])
  3377. def set_screen_units(self, units):
  3378. """
  3379. Set the FlatCAM units on the status bar.
  3380. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3381. :return: None
  3382. """
  3383. self.ui.units_label.setText("[" + units.lower() + "]")
  3384. def on_toggle_units_click(self):
  3385. try:
  3386. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3387. except (TypeError, AttributeError):
  3388. pass
  3389. if self.defaults["units"] == 'MM':
  3390. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3391. else:
  3392. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3393. self.on_toggle_units(no_pref=True)
  3394. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3395. lambda: self.on_toggle_units(no_pref=False))
  3396. def on_toggle_units(self, no_pref=False):
  3397. """
  3398. Callback for the Units radio-button change in the Preferences tab.
  3399. Changes the application's default units adn for the project too.
  3400. If changing the project's units, the change propagates to all of
  3401. the objects in the project.
  3402. :return: None
  3403. """
  3404. self.defaults.report_usage("on_toggle_units")
  3405. if self.toggle_units_ignore:
  3406. return
  3407. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3408. # If option is the same, then ignore
  3409. if new_units == self.defaults["units"].upper():
  3410. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3411. return
  3412. # Keys in self.defaults for which to scale their values
  3413. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3414. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3415. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3416. "gerber_editor_ma_high",
  3417. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3418. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3419. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3420. "excellon_feedrate_probe", "excellon_milling_dia",
  3421. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3422. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3423. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3424. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3425. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3426. "geometry_extracut_length", "geometry_z_pdepth",
  3427. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3428. 'cncjob_tooldia',
  3429. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3430. "tools_paintnewdia",
  3431. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3432. "tools_nccnewdia", "tools_ncc_offset_value",
  3433. "tools_2sided_drilldia",
  3434. "tools_film_boundary", "tools_film_scale_stroke",
  3435. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3436. "tools_cutout_depthperpass",
  3437. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3438. "tools_panelize_spacing_rows",
  3439. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3440. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3441. "tools_transform_buffer_dis",
  3442. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3443. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3444. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3445. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3446. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3447. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3448. "tools_cr_h2h_val", "tools_cr_dh_val",
  3449. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3450. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3451. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3452. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3453. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3454. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3455. "tools_copper_thieving_mask_clearance",
  3456. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3457. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3458. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3459. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3460. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3461. "tools_invert_margin",
  3462. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3463. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3464. def scale_defaults(sfactor):
  3465. for dim in dimensions:
  3466. if dim in [
  3467. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3468. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3469. 'tools_transform_mirror_point'
  3470. ]:
  3471. if self.defaults[dim] is None or self.defaults[dim] == '':
  3472. continue
  3473. try:
  3474. coordinates = self.defaults[dim].split(",")
  3475. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3476. coords_xy[0] *= sfactor
  3477. coords_xy[1] *= sfactor
  3478. self.defaults[dim] = "%.*f, %.*f" % (
  3479. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3480. except Exception as e:
  3481. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3482. elif dim in [
  3483. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3484. ]:
  3485. if self.defaults[dim] is None or self.defaults[dim] == '':
  3486. continue
  3487. try:
  3488. self.defaults[dim] = float(self.defaults[dim])
  3489. tools_diameters = [self.defaults[dim]]
  3490. except ValueError:
  3491. try:
  3492. tools_string = self.defaults[dim].split(",")
  3493. tools_diameters = [eval(a) for a in tools_string if a != '']
  3494. except Exception as e:
  3495. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3496. continue
  3497. self.defaults[dim] = ''
  3498. td_len = len(tools_diameters)
  3499. if td_len > 1:
  3500. for t in range(td_len):
  3501. tools_diameters[t] *= sfactor
  3502. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3503. else:
  3504. tools_diameters[0] *= sfactor
  3505. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3506. elif dim in ['global_gridx', 'global_gridy']:
  3507. # format the number of decimals to the one specified in self.decimals
  3508. try:
  3509. val = float(self.defaults[dim]) * sfactor
  3510. except Exception as e:
  3511. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3512. continue
  3513. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3514. else:
  3515. # the number of decimals for the rest is kept unchanged
  3516. if self.defaults[dim]:
  3517. try:
  3518. val = float(self.defaults[dim]) * sfactor
  3519. except Exception as e:
  3520. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3521. continue
  3522. self.defaults[dim] = val
  3523. # The scaling factor depending on choice of units.
  3524. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3525. # Changing project units. Warn user.
  3526. msgbox = QtWidgets.QMessageBox()
  3527. msgbox.setWindowTitle(_("Toggle Units"))
  3528. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3529. msgbox.setText(_("Changing the units of the project\n"
  3530. "will scale all objects.\n\n"
  3531. "Do you want to continue?"))
  3532. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3533. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3534. msgbox.setDefaultButton(bt_ok)
  3535. msgbox.exec_()
  3536. response = msgbox.clickedButton()
  3537. if response == bt_ok:
  3538. if no_pref is False:
  3539. self.preferencesUiManager.defaults_read_form()
  3540. scale_defaults(factor)
  3541. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3542. self.defaults["units"] = new_units
  3543. # update the defaults from form, some may assume that the conversion is enough and it's not
  3544. self.on_options_app2project()
  3545. # update the objects
  3546. for obj in self.collection.get_list():
  3547. obj.convert_units(new_units)
  3548. # make that the properties stored in the object are also updated
  3549. self.object_changed.emit(obj)
  3550. # rebuild the object UI
  3551. obj.build_ui()
  3552. # change this only if the workspace is active
  3553. if self.defaults['global_workspace'] is True:
  3554. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3555. # adjust the grid values on the main toolbar
  3556. val_x = float(self.defaults['global_gridx']) * factor
  3557. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3558. current = self.collection.get_active()
  3559. if current is not None:
  3560. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3561. if not isinstance(current, GeometryObject):
  3562. current.to_form()
  3563. # replot all objects
  3564. self.plot_all()
  3565. # set the status labels to reflect the current FlatCAM units
  3566. self.set_screen_units(new_units)
  3567. # signal to the app that we changed the object properties and it should save the project
  3568. self.should_we_save = True
  3569. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3570. else:
  3571. # Undo toggling
  3572. self.toggle_units_ignore = True
  3573. if self.defaults['units'].upper() == 'MM':
  3574. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3575. else:
  3576. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3577. self.toggle_units_ignore = False
  3578. # store the grid values so they are not changed in the next step
  3579. val_x = float(self.defaults['global_gridx'])
  3580. val_y = float(self.defaults['global_gridy'])
  3581. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3582. self.preferencesUiManager.defaults_read_form()
  3583. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3584. # in self.defaults from the GUI elements but
  3585. # I don't want it for the grid values, so I update them here
  3586. self.defaults['global_gridx'] = val_x
  3587. self.defaults['global_gridy'] = val_y
  3588. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3589. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3590. def on_toggle_axis(self):
  3591. self.defaults.report_usage("on_toggle_axis()")
  3592. if self.toggle_axis is False:
  3593. if self.is_legacy is False:
  3594. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3595. parent=self.plotcanvas.view.scene)
  3596. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3597. parent=self.plotcanvas.view.scene)
  3598. else:
  3599. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3600. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3601. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3602. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3603. self.plotcanvas.canvas.draw()
  3604. self.toggle_axis = True
  3605. else:
  3606. if self.is_legacy is False:
  3607. self.plotcanvas.v_line.parent = None
  3608. self.plotcanvas.h_line.parent = None
  3609. else:
  3610. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3611. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3612. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3613. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3614. self.plotcanvas.canvas.draw()
  3615. self.toggle_axis = False
  3616. def on_toggle_hud(self):
  3617. self.plotcanvas.on_toggle_hud(state=False if self.plotcanvas.hud_enabled else True)
  3618. def on_toggle_grid_lines(self):
  3619. self.defaults.report_usage("on_toggle_grd_lines()")
  3620. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3621. if tt_settings.contains("theme"):
  3622. theme = tt_settings.value('theme', type=str)
  3623. else:
  3624. theme = 'white'
  3625. if self.toggle_grid_lines is False:
  3626. if self.is_legacy is False:
  3627. if theme == 'white':
  3628. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3629. else:
  3630. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3631. else:
  3632. self.plotcanvas.axes.grid(True)
  3633. try:
  3634. self.plotcanvas.canvas.draw()
  3635. except IndexError:
  3636. pass
  3637. pass
  3638. self.toggle_grid_lines = True
  3639. else:
  3640. if self.is_legacy is False:
  3641. if theme == 'white':
  3642. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3643. else:
  3644. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3645. else:
  3646. self.plotcanvas.axes.grid(False)
  3647. try:
  3648. self.plotcanvas.canvas.draw()
  3649. except IndexError:
  3650. pass
  3651. self.toggle_grid_lines = False
  3652. if self.is_legacy is False:
  3653. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3654. # - perhaps is a bug in VisPy implementation
  3655. if self.grid_status():
  3656. self.app_cursor.enabled = False
  3657. self.app_cursor.enabled = True
  3658. else:
  3659. self.app_cursor.enabled = True
  3660. self.app_cursor.enabled = False
  3661. def on_update_exc_export(self, state):
  3662. """
  3663. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3664. if the update_excellon_cb checkbox is checked
  3665. :param state: state of the checkbox whose signals is tied to his slot
  3666. :return:
  3667. """
  3668. if state:
  3669. # first try to disconnect
  3670. try:
  3671. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3672. disconnect(self.on_excellon_format_changed)
  3673. except TypeError:
  3674. pass
  3675. try:
  3676. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3677. disconnect(self.on_excellon_format_changed)
  3678. except TypeError:
  3679. pass
  3680. try:
  3681. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3682. disconnect(self.on_excellon_format_changed)
  3683. except TypeError:
  3684. pass
  3685. try:
  3686. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3687. disconnect(self.on_excellon_format_changed)
  3688. except TypeError:
  3689. pass
  3690. try:
  3691. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3692. disconnect(self.on_excellon_zeros_changed)
  3693. except TypeError:
  3694. pass
  3695. try:
  3696. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3697. disconnect(self.on_excellon_zeros_changed)
  3698. except TypeError:
  3699. pass
  3700. # the connect them
  3701. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3702. self.on_excellon_format_changed)
  3703. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3704. self.on_excellon_format_changed)
  3705. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3706. self.on_excellon_format_changed)
  3707. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3708. self.on_excellon_format_changed)
  3709. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3710. self.on_excellon_zeros_changed)
  3711. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3712. self.on_excellon_units_changed)
  3713. else:
  3714. # disconnect the signals
  3715. try:
  3716. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3717. disconnect(self.on_excellon_format_changed)
  3718. except TypeError:
  3719. pass
  3720. try:
  3721. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3722. disconnect(self.on_excellon_format_changed)
  3723. except TypeError:
  3724. pass
  3725. try:
  3726. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3727. disconnect(self.on_excellon_format_changed)
  3728. except TypeError:
  3729. pass
  3730. try:
  3731. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3732. disconnect(self.on_excellon_format_changed)
  3733. except TypeError:
  3734. pass
  3735. try:
  3736. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3737. disconnect(self.on_excellon_zeros_changed)
  3738. except TypeError:
  3739. pass
  3740. try:
  3741. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3742. disconnect(self.on_excellon_zeros_changed)
  3743. except TypeError:
  3744. pass
  3745. def on_excellon_format_changed(self):
  3746. """
  3747. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3748. :return: None
  3749. """
  3750. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3751. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3752. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3753. )
  3754. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3755. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3756. )
  3757. else:
  3758. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3759. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3760. )
  3761. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3762. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3763. )
  3764. def on_excellon_zeros_changed(self):
  3765. """
  3766. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3767. :return: None
  3768. """
  3769. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3770. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3771. )
  3772. def on_excellon_units_changed(self):
  3773. """
  3774. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3775. :return: None
  3776. """
  3777. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3778. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3779. )
  3780. self.on_excellon_format_changed()
  3781. def on_film_color_entry(self):
  3782. self.defaults['tools_film_color'] = \
  3783. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3784. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3785. "background-color:%s;"
  3786. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3787. )
  3788. def on_film_color_button(self):
  3789. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3790. c_dialog = QtWidgets.QColorDialog()
  3791. film_color = c_dialog.getColor(initial=current_color)
  3792. if film_color.isValid() is False:
  3793. return
  3794. # if new color is different then mark that the Preferences are changed
  3795. if film_color != current_color:
  3796. self.preferencesUiManager.on_preferences_edited()
  3797. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3798. "background-color:%s;"
  3799. "border-color: dimgray" % str(film_color.name())
  3800. )
  3801. new_val_sel = str(film_color.name())
  3802. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3803. self.defaults['tools_film_color'] = new_val_sel
  3804. def on_qrcode_fill_color_entry(self):
  3805. self.defaults['tools_qrcode_fill_color'] = \
  3806. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3807. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3808. "background-color:%s;"
  3809. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3810. )
  3811. def on_qrcode_fill_color_button(self):
  3812. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3813. c_dialog = QtWidgets.QColorDialog()
  3814. fill_color = c_dialog.getColor(initial=current_color)
  3815. if fill_color.isValid() is False:
  3816. return
  3817. # if new color is different then mark that the Preferences are changed
  3818. if fill_color != current_color:
  3819. self.preferencesUiManager.on_preferences_edited()
  3820. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3821. "background-color:%s;"
  3822. "border-color: dimgray" % str(fill_color.name())
  3823. )
  3824. new_val_sel = str(fill_color.name())
  3825. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3826. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3827. def on_qrcode_back_color_entry(self):
  3828. self.defaults['tools_qrcode_back_color'] = \
  3829. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3830. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3831. "background-color:%s;"
  3832. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3833. )
  3834. def on_qrcode_back_color_button(self):
  3835. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3836. c_dialog = QtWidgets.QColorDialog()
  3837. back_color = c_dialog.getColor(initial=current_color)
  3838. if back_color.isValid() is False:
  3839. return
  3840. # if new color is different then mark that the Preferences are changed
  3841. if back_color != current_color:
  3842. self.preferencesUiManager.on_preferences_edited()
  3843. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3844. "background-color:%s;"
  3845. "border-color: dimgray" % str(back_color.name())
  3846. )
  3847. new_val_sel = str(back_color.name())
  3848. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3849. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3850. def on_tab_rmb_click(self, checked):
  3851. self.ui.notebook.set_detachable(val=checked)
  3852. self.defaults["global_tabs_detachable"] = checked
  3853. self.ui.plot_tab_area.set_detachable(val=checked)
  3854. self.defaults["global_tabs_detachable"] = checked
  3855. def on_tab_setup_context_menu(self):
  3856. initial_checked = self.defaults["global_tabs_detachable"]
  3857. action_name = str(_("Detachable Tabs"))
  3858. action = QtWidgets.QAction(self)
  3859. action.setCheckable(True)
  3860. action.setText(action_name)
  3861. action.setChecked(initial_checked)
  3862. self.ui.notebook.tabBar.addAction(action)
  3863. self.ui.plot_tab_area.tabBar.addAction(action)
  3864. try:
  3865. action.triggered.disconnect()
  3866. except TypeError:
  3867. pass
  3868. action.triggered.connect(self.on_tab_rmb_click)
  3869. def on_deselect_all(self):
  3870. self.collection.set_all_inactive()
  3871. self.delete_selection_shape()
  3872. def on_workspace_modified(self):
  3873. # self.save_defaults(silent=True)
  3874. self.plotcanvas.delete_workspace()
  3875. self.preferencesUiManager.defaults_read_form()
  3876. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3877. def on_workspace(self):
  3878. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3879. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3880. self.inform.emit(_("Workspace enabled."))
  3881. else:
  3882. self.plotcanvas.delete_workspace()
  3883. self.inform.emit(_("Workspace disabled."))
  3884. self.preferencesUiManager.defaults_read_form()
  3885. # self.save_defaults(silent=True)
  3886. def on_workspace_toggle(self):
  3887. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3888. try:
  3889. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3890. except TypeError:
  3891. pass
  3892. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3893. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3894. self.on_workspace()
  3895. def on_cursor_type(self, val):
  3896. """
  3897. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3898. :return: None
  3899. """
  3900. self.app_cursor.enabled = False
  3901. if val == 'small':
  3902. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3903. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3904. self.app_cursor = self.plotcanvas.new_cursor()
  3905. else:
  3906. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3907. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3908. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3909. if self.ui.grid_snap_btn.isChecked():
  3910. self.app_cursor.enabled = True
  3911. else:
  3912. self.app_cursor.enabled = False
  3913. def on_tool_add_keypress(self):
  3914. # ## Current application units in Upper Case
  3915. self.units = self.defaults['units'].upper()
  3916. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3917. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3918. if notebook_widget_name == 'selected_tab':
  3919. if self.collection.get_active().kind == 'geometry':
  3920. # Tool add works for Geometry only if Advanced is True in Preferences
  3921. if self.defaults["global_app_level"] == 'a':
  3922. tool_add_popup = FCInputDialog(title="New Tool ...",
  3923. text='Enter a Tool Diameter:',
  3924. min=0.0000, max=99.9999, decimals=4)
  3925. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3926. val, ok = tool_add_popup.get_value()
  3927. if ok:
  3928. if float(val) == 0:
  3929. self.inform.emit('[WARNING_NOTCL] %s' %
  3930. _("Please enter a tool diameter with non-zero value, in Float format."))
  3931. return
  3932. self.collection.get_active().on_tool_add(dia=float(val))
  3933. else:
  3934. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3935. else:
  3936. msgbox = QtWidgets.QMessageBox()
  3937. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3938. "Go to Preferences -> General - Show Advanced Options."))
  3939. msgbox.setWindowTitle("Tool adding ...")
  3940. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3941. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3942. msgbox.setDefaultButton(bt_ok)
  3943. msgbox.exec_()
  3944. # work only if the notebook tab on focus is the Tools_Tab
  3945. if notebook_widget_name == 'tool_tab':
  3946. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3947. # and only if the tool is NCC Tool
  3948. if tool_widget == self.ncclear_tool.toolName:
  3949. self.ncclear_tool.on_add_tool_by_key()
  3950. # and only if the tool is Paint Area Tool
  3951. elif tool_widget == self.paint_tool.toolName:
  3952. self.paint_tool.on_add_tool_by_key()
  3953. # and only if the tool is Solder Paste Dispensing Tool
  3954. elif tool_widget == self.paste_tool.toolName:
  3955. self.paste_tool.on_add_tool_by_key()
  3956. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3957. # See description below.
  3958. def on_delete_keypress(self):
  3959. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3960. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3961. if notebook_widget_name == 'selected_tab':
  3962. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3963. self.collection.get_active().on_tool_delete()
  3964. # work only if the notebook tab on focus is the Tools_Tab
  3965. elif notebook_widget_name == 'tool_tab':
  3966. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3967. # and only if the tool is NCC Tool
  3968. if tool_widget == self.ncclear_tool.toolName:
  3969. self.ncclear_tool.on_tool_delete()
  3970. # and only if the tool is Paint Tool
  3971. elif tool_widget == self.paint_tool.toolName:
  3972. self.paint_tool.on_tool_delete()
  3973. # and only if the tool is Solder Paste Dispensing Tool
  3974. elif tool_widget == self.paste_tool.toolName:
  3975. self.paste_tool.on_tool_delete()
  3976. else:
  3977. self.on_delete()
  3978. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3979. # some screens you have to be careful where you hover with your mouse.
  3980. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3981. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3982. # Complicated, I know :)
  3983. def on_delete(self, force_deletion=False):
  3984. """
  3985. Delete the currently selected FlatCAMObjs.
  3986. :param force_deletion: used by Tcl command
  3987. :return: None
  3988. """
  3989. self.defaults.report_usage("on_delete()")
  3990. response = None
  3991. bt_ok = None
  3992. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3993. # a geometry object before we update it.
  3994. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3995. and self.grb_editor.editor_active is False:
  3996. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3997. msgbox = QtWidgets.QMessageBox()
  3998. msgbox.setWindowTitle(_("Delete objects"))
  3999. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4000. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4001. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4002. "the selected objects?"))
  4003. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4004. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4005. msgbox.setDefaultButton(bt_ok)
  4006. msgbox.exec_()
  4007. response = msgbox.clickedButton()
  4008. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4009. response = bt_ok
  4010. if response == bt_ok:
  4011. if self.collection.get_active():
  4012. self.log.debug("App.on_delete()")
  4013. for obj_active in self.collection.get_selected():
  4014. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4015. if obj_active.kind == 'gerber':
  4016. for el in obj_active.mark_shapes:
  4017. obj_active.mark_shapes[el].clear(update=True)
  4018. obj_active.mark_shapes[el].enabled = False
  4019. # obj_active.mark_shapes[el] = None
  4020. del el
  4021. elif isinstance(obj_active, CNCJobObject):
  4022. try:
  4023. obj_active.text_col.enabled = False
  4024. del obj_active.text_col
  4025. obj_active.annotation.clear(update=True)
  4026. del obj_active.annotation
  4027. except AttributeError as e:
  4028. log.debug(
  4029. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4030. )
  4031. while self.collection.get_selected():
  4032. self.delete_first_selected()
  4033. self.inform.emit('%s...' % _("Object(s) deleted"))
  4034. # make sure that the selection shape is deleted, too
  4035. self.delete_selection_shape()
  4036. # if there are no longer objects delete also the exclusion areas shapes
  4037. if not self.collection.get_list():
  4038. self.exc_areas.clear_shapes()
  4039. else:
  4040. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4041. else:
  4042. self.inform.emit(_("Save the work in Editor and try again ..."))
  4043. def delete_first_selected(self):
  4044. # Keep this for later
  4045. try:
  4046. sel_obj = self.collection.get_active()
  4047. name = sel_obj.options["name"]
  4048. isPlotted = sel_obj.options["plot"]
  4049. except AttributeError:
  4050. self.log.debug("Nothing selected for deletion")
  4051. return
  4052. if self.is_legacy is True:
  4053. # Remove plot only if the object was plotted otherwise delaxes will fail
  4054. if isPlotted:
  4055. try:
  4056. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4057. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4058. except Exception as e:
  4059. log.debug("App.delete_first_selected() --> %s" % str(e))
  4060. self.plotcanvas.auto_adjust_axes()
  4061. # Remove from dictionary
  4062. self.collection.delete_active()
  4063. # Clear form
  4064. self.setup_component_editor()
  4065. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4066. def on_set_origin(self):
  4067. """
  4068. Set the origin to the left mouse click position
  4069. :return: None
  4070. """
  4071. # display the message for the user
  4072. # and ask him to click on the desired position
  4073. self.defaults.report_usage("on_set_origin()")
  4074. def origin_replot():
  4075. def worker_task():
  4076. with self.proc_container.new('%s...' % _("Plotting")):
  4077. for obj in self.collection.get_list():
  4078. obj.plot()
  4079. self.plotcanvas.fit_view()
  4080. if self.is_legacy:
  4081. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4082. else:
  4083. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4084. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4085. self.inform.emit(_('Click to set the origin ...'))
  4086. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4087. # first disconnect it as it may have been used by something else
  4088. try:
  4089. self.replot_signal.disconnect()
  4090. except TypeError:
  4091. pass
  4092. self.replot_signal[list].connect(origin_replot)
  4093. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4094. """
  4095. :param event:
  4096. :param location:
  4097. :param noplot:
  4098. :param use_thread:
  4099. :return:
  4100. """
  4101. noplot_sig = noplot
  4102. def worker_task():
  4103. with self.proc_container.new(_("Setting Origin...")):
  4104. obj_list = self.collection.get_list()
  4105. for obj in obj_list:
  4106. obj.offset((x, y))
  4107. self.object_changed.emit(obj)
  4108. # Update the object bounding box options
  4109. a, b, c, d = obj.bounds()
  4110. obj.options['xmin'] = a
  4111. obj.options['ymin'] = b
  4112. obj.options['xmax'] = c
  4113. obj.options['ymax'] = d
  4114. self.inform.emit('[success] %s...' % _('Origin set'))
  4115. for obj in obj_list:
  4116. out_name = obj.options["name"]
  4117. if obj.kind == 'gerber':
  4118. obj.source_file = self.export_gerber(
  4119. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4120. elif obj.kind == 'excellon':
  4121. obj.source_file = self.export_excellon(
  4122. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4123. if noplot_sig is False:
  4124. self.replot_signal.emit([])
  4125. if location is not None:
  4126. if len(location) != 2:
  4127. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4128. return 'fail'
  4129. x, y = location
  4130. if use_thread is True:
  4131. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4132. else:
  4133. worker_task()
  4134. self.should_we_save = True
  4135. return
  4136. if event is not None and event.button == 1:
  4137. if self.is_legacy is False:
  4138. event_pos = event.pos
  4139. else:
  4140. event_pos = (event.xdata, event.ydata)
  4141. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4142. if self.grid_status():
  4143. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4144. else:
  4145. pos = pos_canvas
  4146. x = 0 - pos[0]
  4147. y = 0 - pos[1]
  4148. if use_thread is True:
  4149. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4150. else:
  4151. worker_task()
  4152. self.should_we_save = True
  4153. def on_move2origin(self, use_thread=True):
  4154. """
  4155. Move selected objects to origin.
  4156. :param use_thread: Control if to use threaded operation. Boolean.
  4157. :return:
  4158. """
  4159. def worker_task():
  4160. with self.proc_container.new(_("Moving to Origin...")):
  4161. obj_list = self.collection.get_selected()
  4162. if not obj_list:
  4163. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4164. return
  4165. xminlist = []
  4166. yminlist = []
  4167. # first get a bounding box to fit all
  4168. for obj in obj_list:
  4169. xmin, ymin, xmax, ymax = obj.bounds()
  4170. xminlist.append(xmin)
  4171. yminlist.append(ymin)
  4172. # get the minimum x,y for all objects selected
  4173. x = min(xminlist)
  4174. y = min(yminlist)
  4175. for obj in obj_list:
  4176. obj.offset((-x, -y))
  4177. self.object_changed.emit(obj)
  4178. # Update the object bounding box options
  4179. a, b, c, d = obj.bounds()
  4180. obj.options['xmin'] = a
  4181. obj.options['ymin'] = b
  4182. obj.options['xmax'] = c
  4183. obj.options['ymax'] = d
  4184. for obj in obj_list:
  4185. obj.plot()
  4186. for obj in obj_list:
  4187. out_name = obj.options["name"]
  4188. if obj.kind == 'gerber':
  4189. obj.source_file = self.export_gerber(
  4190. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4191. elif obj.kind == 'excellon':
  4192. obj.source_file = self.export_excellon(
  4193. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4194. self.inform.emit('[success] %s...' % _('Origin set'))
  4195. if use_thread is True:
  4196. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4197. else:
  4198. worker_task()
  4199. self.should_we_save = True
  4200. def on_jump_to(self, custom_location=None, fit_center=True):
  4201. """
  4202. Jump to a location by setting the mouse cursor location.
  4203. :param custom_location: Jump to a specified point. (x, y) tuple.
  4204. :param fit_center: If to fit view. Boolean.
  4205. :return:
  4206. """
  4207. self.defaults.report_usage("on_jump_to()")
  4208. if not custom_location:
  4209. dia_box_location = None
  4210. try:
  4211. dia_box_location = eval(self.clipboard.text())
  4212. except Exception:
  4213. pass
  4214. if type(dia_box_location) == tuple:
  4215. dia_box_location = str(dia_box_location)
  4216. else:
  4217. dia_box_location = None
  4218. # dia_box = Dialog_box(title=_("Jump to ..."),
  4219. # label=_("Enter the coordinates in format X,Y:"),
  4220. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4221. # initial_text=dia_box_location)
  4222. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4223. label=_("Enter the coordinates in format X,Y:"),
  4224. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4225. initial_text=dia_box_location,
  4226. reference=self.defaults['global_jump_ref'])
  4227. if dia_box.ok is True:
  4228. try:
  4229. location = eval(dia_box.location)
  4230. if not isinstance(location, tuple):
  4231. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4232. return
  4233. if dia_box.reference == 'rel':
  4234. rel_x = self.mouse[0] + location[0]
  4235. rel_y = self.mouse[1] + location[1]
  4236. location = (rel_x, rel_y)
  4237. self.defaults['global_jump_ref'] = dia_box.reference
  4238. except Exception:
  4239. return
  4240. else:
  4241. return
  4242. else:
  4243. location = custom_location
  4244. self.jump_signal.emit(location)
  4245. if fit_center:
  4246. self.plotcanvas.fit_center(loc=location)
  4247. cursor = QtGui.QCursor()
  4248. if self.is_legacy is False:
  4249. # I don't know where those differences come from but they are constant for the current
  4250. # execution of the application and they are multiples of a value around 0.0263mm.
  4251. # In a random way sometimes they are more sometimes they are less
  4252. # if units == 'MM':
  4253. # cal_factor = 0.0263
  4254. # else:
  4255. # cal_factor = 0.0263 / 25.4
  4256. cal_location = (location[0], location[1])
  4257. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4258. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4259. j_pos = (
  4260. int(canvas_origin.x() + round(jump_loc[0])),
  4261. int(canvas_origin.y() + round(jump_loc[1]))
  4262. )
  4263. cursor.setPos(j_pos[0], j_pos[1])
  4264. else:
  4265. # find the canvas origin which is in the top left corner
  4266. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4267. # determine the coordinates for the lowest left point of the canvas
  4268. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4269. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4270. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4271. # canvas) and the point (width, height) is in the top-right location
  4272. loc = self.plotcanvas.axes.transData.transform_point(location)
  4273. j_pos = (
  4274. int(x0 + loc[0]),
  4275. int(y0 - loc[1])
  4276. )
  4277. cursor.setPos(j_pos[0], j_pos[1])
  4278. self.plotcanvas.mouse = [location[0], location[1]]
  4279. if self.defaults["global_cursor_color_enabled"] is True:
  4280. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4281. else:
  4282. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4283. if self.grid_status():
  4284. # Update cursor
  4285. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4286. symbol='++', edge_color=self.cursor_color_3D,
  4287. edge_width=self.defaults["global_cursor_width"],
  4288. size=self.defaults["global_cursor_size"])
  4289. # Set the relative position label
  4290. dx = location[0] - float(self.rel_point1[0])
  4291. dy = location[1] - float(self.rel_point1[1])
  4292. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4293. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4294. # # Set the position label
  4295. #
  4296. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4297. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4298. units = self.defaults["units"].lower()
  4299. self.plotcanvas.text_hud.text = \
  4300. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4301. dx, units, dy, units, location[0], units, location[1], units)
  4302. self.inform.emit('[success] %s' % _("Done."))
  4303. return location
  4304. def on_locate(self, obj, fit_center=True):
  4305. """
  4306. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4307. :param obj: The object on which to locate certain points
  4308. :param fit_center: If to fit view. Boolean.
  4309. :return: A point location. (x, y) tuple.
  4310. """
  4311. self.defaults.report_usage("on_locate()")
  4312. if obj is None:
  4313. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4314. return 'fail'
  4315. class DialogBoxChoice(QtWidgets.QDialog):
  4316. def __init__(self, title=None, icon=None, choice='bl'):
  4317. """
  4318. :param title: string with the window title
  4319. """
  4320. super(DialogBoxChoice, self).__init__()
  4321. self.ok = False
  4322. self.setWindowIcon(icon)
  4323. self.setWindowTitle(str(title))
  4324. self.form = QtWidgets.QFormLayout(self)
  4325. self.ref_radio = RadioSet([
  4326. {"label": _("Bottom-Left"), "value": "bl"},
  4327. {"label": _("Top-Left"), "value": "tl"},
  4328. {"label": _("Bottom-Right"), "value": "br"},
  4329. {"label": _("Top-Right"), "value": "tr"},
  4330. {"label": _("Center"), "value": "c"}
  4331. ], orientation='vertical', stretch=False)
  4332. self.ref_radio.set_value(choice)
  4333. self.form.addRow(self.ref_radio)
  4334. self.button_box = QtWidgets.QDialogButtonBox(
  4335. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4336. Qt.Horizontal, parent=self)
  4337. self.form.addRow(self.button_box)
  4338. self.button_box.accepted.connect(self.accept)
  4339. self.button_box.rejected.connect(self.reject)
  4340. if self.exec_() == QtWidgets.QDialog.Accepted:
  4341. self.ok = True
  4342. self.location_point = self.ref_radio.get_value()
  4343. else:
  4344. self.ok = False
  4345. self.location_point = None
  4346. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4347. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4348. choice=self.defaults['global_locate_pt'])
  4349. if dia_box.ok is True:
  4350. try:
  4351. location_point = dia_box.location_point
  4352. self.defaults['global_locate_pt'] = dia_box.location_point
  4353. except Exception:
  4354. return
  4355. else:
  4356. return
  4357. loc_b = obj.bounds()
  4358. if location_point == 'bl':
  4359. location = (loc_b[0], loc_b[1])
  4360. elif location_point == 'tl':
  4361. location = (loc_b[0], loc_b[3])
  4362. elif location_point == 'br':
  4363. location = (loc_b[2], loc_b[1])
  4364. elif location_point == 'tr':
  4365. location = (loc_b[2], loc_b[3])
  4366. else:
  4367. # center
  4368. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4369. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4370. location = (cx, cy)
  4371. self.locate_signal.emit(location, location_point)
  4372. if fit_center:
  4373. self.plotcanvas.fit_center(loc=location)
  4374. cursor = QtGui.QCursor()
  4375. if self.is_legacy is False:
  4376. # I don't know where those differences come from but they are constant for the current
  4377. # execution of the application and they are multiples of a value around 0.0263mm.
  4378. # In a random way sometimes they are more sometimes they are less
  4379. # if units == 'MM':
  4380. # cal_factor = 0.0263
  4381. # else:
  4382. # cal_factor = 0.0263 / 25.4
  4383. cal_location = (location[0], location[1])
  4384. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4385. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4386. j_pos = (
  4387. int(canvas_origin.x() + round(jump_loc[0])),
  4388. int(canvas_origin.y() + round(jump_loc[1]))
  4389. )
  4390. cursor.setPos(j_pos[0], j_pos[1])
  4391. else:
  4392. # find the canvas origin which is in the top left corner
  4393. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4394. # determine the coordinates for the lowest left point of the canvas
  4395. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4396. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4397. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4398. # canvas) and the point (width, height) is in the top-right location
  4399. loc = self.plotcanvas.axes.transData.transform_point(location)
  4400. j_pos = (
  4401. int(x0 + loc[0]),
  4402. int(y0 - loc[1])
  4403. )
  4404. cursor.setPos(j_pos[0], j_pos[1])
  4405. self.plotcanvas.mouse = [location[0], location[1]]
  4406. if self.defaults["global_cursor_color_enabled"] is True:
  4407. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4408. else:
  4409. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4410. if self.grid_status():
  4411. # Update cursor
  4412. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4413. symbol='++', edge_color=self.cursor_color_3D,
  4414. edge_width=self.defaults["global_cursor_width"],
  4415. size=self.defaults["global_cursor_size"])
  4416. # Set the relative position label
  4417. self.dx = location[0] - float(self.rel_point1[0])
  4418. self.dy = location[1] - float(self.rel_point1[1])
  4419. # Set the position label
  4420. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4421. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4422. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4423. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4424. units = self.defaults["units"].lower()
  4425. self.plotcanvas.text_hud.text = \
  4426. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4427. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4428. self.inform.emit('[success] %s' % _("Done."))
  4429. return location
  4430. def on_copy_command(self):
  4431. """
  4432. Will copy a selection of objects, creating new objects.
  4433. :return:
  4434. """
  4435. self.defaults.report_usage("on_copy_command()")
  4436. def initialize(obj_init, app):
  4437. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4438. try:
  4439. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4440. except AttributeError:
  4441. pass
  4442. try:
  4443. obj_init.apertures = deepcopy(obj.apertures)
  4444. except AttributeError:
  4445. pass
  4446. try:
  4447. if obj.tools:
  4448. obj_init.tools = deepcopy(obj.tools)
  4449. except Exception as err:
  4450. log.debug("App.on_copy_command() --> %s" % str(err))
  4451. try:
  4452. obj_init.source_file = deepcopy(obj.source_file)
  4453. except (AttributeError, TypeError):
  4454. pass
  4455. def initialize_excellon(obj_init, app):
  4456. obj_init.source_file = deepcopy(obj.source_file)
  4457. obj_init.tools = deepcopy(obj.tools)
  4458. # drills are offset, so they need to be deep copied
  4459. obj_init.drills = deepcopy(obj.drills)
  4460. # slots are offset, so they need to be deep copied
  4461. obj_init.slots = deepcopy(obj.slots)
  4462. obj_init.create_geometry()
  4463. def initialize_script(obj_init, app_obj):
  4464. obj_init.source_file = deepcopy(obj.source_file)
  4465. def initialize_document(obj_init, app_obj):
  4466. obj_init.source_file = deepcopy(obj.source_file)
  4467. for obj in self.collection.get_selected():
  4468. obj_name = obj.options["name"]
  4469. try:
  4470. if isinstance(obj, ExcellonObject):
  4471. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4472. elif isinstance(obj, GerberObject):
  4473. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4474. elif isinstance(obj, GeometryObject):
  4475. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4476. elif isinstance(obj, ScriptObject):
  4477. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4478. elif isinstance(obj, DocumentObject):
  4479. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4480. except Exception as e:
  4481. return "Operation failed: %s" % str(e)
  4482. def on_copy_object2(self, custom_name):
  4483. def initialize_geometry(obj_init, app):
  4484. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4485. try:
  4486. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4487. except AttributeError:
  4488. pass
  4489. try:
  4490. obj_init.apertures = deepcopy(obj.apertures)
  4491. except AttributeError:
  4492. pass
  4493. try:
  4494. if obj.tools:
  4495. obj_init.tools = deepcopy(obj.tools)
  4496. except Exception as ee:
  4497. log.debug("on_copy_object2() --> %s" % str(ee))
  4498. def initialize_gerber(obj_init, app):
  4499. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4500. obj_init.apertures = deepcopy(obj.apertures)
  4501. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4502. def initialize_excellon(obj_init, app):
  4503. obj_init.tools = deepcopy(obj.tools)
  4504. # drills are offset, so they need to be deep copied
  4505. obj_init.drills = deepcopy(obj.drills)
  4506. # slots are offset, so they need to be deep copied
  4507. obj_init.slots = deepcopy(obj.slots)
  4508. obj_init.create_geometry()
  4509. for obj in self.collection.get_selected():
  4510. obj_name = obj.options["name"]
  4511. try:
  4512. if isinstance(obj, ExcellonObject):
  4513. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4514. elif isinstance(obj, GerberObject):
  4515. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4516. elif isinstance(obj, GeometryObject):
  4517. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4518. except Exception as er:
  4519. return "Operation failed: %s" % str(er)
  4520. def on_rename_object(self, text):
  4521. """
  4522. Will rename an object.
  4523. :param text: New name for the object.
  4524. :return:
  4525. """
  4526. self.defaults.report_usage("on_rename_object()")
  4527. named_obj = self.collection.get_active()
  4528. for obj in named_obj:
  4529. if obj is list:
  4530. self.on_rename_object(text)
  4531. else:
  4532. try:
  4533. obj.options['name'] = text
  4534. except Exception as e:
  4535. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4536. def convert_any2geo(self):
  4537. """
  4538. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4539. :return:
  4540. """
  4541. self.defaults.report_usage("convert_any2geo()")
  4542. def initialize(obj_init, app):
  4543. obj_init.solid_geometry = obj.solid_geometry
  4544. try:
  4545. obj_init.follow_geometry = obj.follow_geometry
  4546. except AttributeError:
  4547. pass
  4548. try:
  4549. obj_init.apertures = obj.apertures
  4550. except AttributeError:
  4551. pass
  4552. try:
  4553. if obj.tools:
  4554. obj_init.tools = obj.tools
  4555. except AttributeError:
  4556. pass
  4557. def initialize_excellon(obj_init, app):
  4558. # objs = self.collection.get_selected()
  4559. # GeometryObject.merge(objs, obj)
  4560. solid_geo = []
  4561. for tool in obj.tools:
  4562. for geo in obj.tools[tool]['solid_geometry']:
  4563. solid_geo.append(geo)
  4564. obj_init.solid_geometry = deepcopy(solid_geo)
  4565. if not self.collection.get_selected():
  4566. log.warning("App.convert_any2geo --> No object selected")
  4567. self.inform.emit('[WARNING_NOTCL] %s' %
  4568. _("No object is selected. Select an object and try again."))
  4569. return
  4570. for obj in self.collection.get_selected():
  4571. obj_name = obj.options["name"]
  4572. try:
  4573. if isinstance(obj, ExcellonObject):
  4574. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4575. else:
  4576. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4577. except Exception as e:
  4578. return "Operation failed: %s" % str(e)
  4579. def convert_any2gerber(self):
  4580. """
  4581. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4582. :return:
  4583. """
  4584. self.defaults.report_usage("convert_any2gerber()")
  4585. def initialize_geometry(obj_init, app):
  4586. apertures = {}
  4587. apid = 0
  4588. apertures[str(apid)] = {}
  4589. apertures[str(apid)]['geometry'] = []
  4590. for obj_orig in obj.solid_geometry:
  4591. new_elem = {}
  4592. new_elem['solid'] = obj_orig
  4593. try:
  4594. new_elem['follow'] = obj_orig.exterior
  4595. except AttributeError:
  4596. pass
  4597. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4598. apertures[str(apid)]['size'] = 0.0
  4599. apertures[str(apid)]['type'] = 'C'
  4600. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4601. obj_init.apertures = deepcopy(apertures)
  4602. def initialize_excellon(obj_init, app):
  4603. apertures = {}
  4604. apid = 10
  4605. for tool in obj.tools:
  4606. apertures[str(apid)] = {}
  4607. apertures[str(apid)]['geometry'] = []
  4608. for geo in obj.tools[tool]['solid_geometry']:
  4609. new_el = {}
  4610. new_el['solid'] = geo
  4611. new_el['follow'] = geo.exterior
  4612. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4613. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4614. apertures[str(apid)]['type'] = 'C'
  4615. apid += 1
  4616. # create solid_geometry
  4617. solid_geometry = []
  4618. for apid in apertures:
  4619. for geo_el in apertures[apid]['geometry']:
  4620. solid_geometry.append(geo_el['solid'])
  4621. solid_geometry = MultiPolygon(solid_geometry)
  4622. solid_geometry = solid_geometry.buffer(0.0000001)
  4623. obj_init.solid_geometry = deepcopy(solid_geometry)
  4624. obj_init.apertures = deepcopy(apertures)
  4625. # clear the working objects (perhaps not necessary due of Python GC)
  4626. apertures.clear()
  4627. if not self.collection.get_selected():
  4628. log.warning("App.convert_any2gerber --> No object selected")
  4629. self.inform.emit('[WARNING_NOTCL] %s' %
  4630. _("No object is selected. Select an object and try again."))
  4631. return
  4632. for obj in self.collection.get_selected():
  4633. obj_name = obj.options["name"]
  4634. try:
  4635. if isinstance(obj, ExcellonObject):
  4636. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4637. elif isinstance(obj, GeometryObject):
  4638. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4639. else:
  4640. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4641. except Exception as e:
  4642. return "Operation failed: %s" % str(e)
  4643. def abort_all_tasks(self):
  4644. """
  4645. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4646. on the first possible occasion.
  4647. :return:
  4648. """
  4649. if self.abort_flag is False:
  4650. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4651. self.abort_flag = True
  4652. self.cleanup.emit()
  4653. def app_is_idle(self):
  4654. if self.abort_flag:
  4655. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4656. self.abort_flag = False
  4657. def on_selectall(self):
  4658. """
  4659. Will draw a selection box shape around the selected objects.
  4660. :return:
  4661. """
  4662. self.defaults.report_usage("on_selectall()")
  4663. # delete the possible selection box around a possible selected object
  4664. self.delete_selection_shape()
  4665. for name in self.collection.get_names():
  4666. self.collection.set_active(name)
  4667. curr_sel_obj = self.collection.get_by_name(name)
  4668. # create the selection box around the selected object
  4669. if self.defaults['global_selection_shape'] is True:
  4670. self.draw_selection_shape(curr_sel_obj)
  4671. def on_preferences(self):
  4672. """
  4673. Adds the Preferences in a Tab in Plot Area
  4674. :return:
  4675. """
  4676. # add the tab if it was closed
  4677. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4678. # delete the absolute and relative position and messages in the infobar
  4679. self.ui.position_label.setText("")
  4680. # self.ui.rel_position_label.setText("")
  4681. # Switch plot_area to preferences page
  4682. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4683. # self.ui.show()
  4684. # detect changes in the preferences
  4685. for idx in range(self.ui.pref_tab_area.count()):
  4686. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4687. try:
  4688. try:
  4689. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4690. except (TypeError, AttributeError):
  4691. pass
  4692. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4693. except AttributeError:
  4694. pass
  4695. try:
  4696. try:
  4697. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4698. except (TypeError, AttributeError):
  4699. pass
  4700. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4701. except AttributeError:
  4702. pass
  4703. try:
  4704. try:
  4705. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4706. except (TypeError, AttributeError):
  4707. pass
  4708. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4709. except AttributeError:
  4710. pass
  4711. try:
  4712. try:
  4713. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4714. except (TypeError, AttributeError):
  4715. pass
  4716. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4717. except AttributeError:
  4718. pass
  4719. try:
  4720. try:
  4721. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4722. except (TypeError, AttributeError):
  4723. pass
  4724. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4725. except AttributeError:
  4726. pass
  4727. def on_tools_database(self, source='app'):
  4728. """
  4729. Adds the Tools Database in a Tab in Plot Area.
  4730. :return:
  4731. """
  4732. for idx in range(self.ui.plot_tab_area.count()):
  4733. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4734. # there can be only one instance of Tools Database at one time
  4735. return
  4736. if source == 'app':
  4737. self.tools_db_tab = ToolsDB2(
  4738. app=self,
  4739. parent=self.ui,
  4740. callback_on_edited=self.on_tools_db_edited,
  4741. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4742. )
  4743. elif source == 'ncc':
  4744. self.tools_db_tab = ToolsDB2(
  4745. app=self,
  4746. parent=self.ui,
  4747. callback_on_edited=self.on_tools_db_edited,
  4748. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4749. )
  4750. elif source == 'paint':
  4751. self.tools_db_tab = ToolsDB2(
  4752. app=self,
  4753. parent=self.ui,
  4754. callback_on_edited=self.on_tools_db_edited,
  4755. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4756. )
  4757. # add the tab if it was closed
  4758. try:
  4759. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4760. self.tools_db_tab.setObjectName("database_tab")
  4761. except Exception as e:
  4762. log.debug("App.on_tools_database() --> %s" % str(e))
  4763. return
  4764. # delete the absolute and relative position and messages in the infobar
  4765. self.ui.position_label.setText("")
  4766. # self.ui.rel_position_label.setText("")
  4767. # Switch plot_area to preferences page
  4768. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4769. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4770. self.tools_db_tab.ui_connect()
  4771. def on_tools_db_edited(self):
  4772. """
  4773. Executed whenever a tool is edited in Tools Database.
  4774. Will color the text of the Tools Database tab to Red color.
  4775. :return:
  4776. """
  4777. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4778. for idx in range(self.ui.plot_tab_area.count()):
  4779. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4780. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4781. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4782. self.tools_db_changed_flag = True
  4783. def on_geometry_tool_add_from_db_executed(self, tool):
  4784. """
  4785. Here add the tool from DB in the selected geometry object.
  4786. :return:
  4787. """
  4788. tool_from_db = deepcopy(tool)
  4789. obj = self.collection.get_active()
  4790. if isinstance(obj, GeometryObject):
  4791. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4792. # close the tab and delete it
  4793. for idx in range(self.ui.plot_tab_area.count()):
  4794. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4795. wdg = self.ui.plot_tab_area.widget(idx)
  4796. wdg.deleteLater()
  4797. self.ui.plot_tab_area.removeTab(idx)
  4798. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4799. else:
  4800. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4801. def on_plot_area_tab_closed(self, tab_obj_name):
  4802. """
  4803. Executed whenever a QTab is closed in the Plot Area.
  4804. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4805. :return:
  4806. """
  4807. if tab_obj_name == "preferences_tab":
  4808. self.preferencesUiManager.on_close_preferences_tab()
  4809. elif tab_obj_name == "database_tab":
  4810. # disconnect the signals from the table widget in tab
  4811. self.tools_db_tab.ui_disconnect()
  4812. if self.tools_db_changed_flag is True:
  4813. msgbox = QtWidgets.QMessageBox()
  4814. msgbox.setText(_("One or more Tools are edited.\n"
  4815. "Do you want to update the Tools Database?"))
  4816. msgbox.setWindowTitle(_("Save Tools Database"))
  4817. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4818. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4819. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4820. msgbox.setDefaultButton(bt_yes)
  4821. msgbox.exec_()
  4822. response = msgbox.clickedButton()
  4823. if response == bt_yes:
  4824. self.tools_db_tab.on_save_tools_db()
  4825. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4826. else:
  4827. self.tools_db_changed_flag = False
  4828. self.inform.emit('')
  4829. return
  4830. self.tools_db_tab.deleteLater()
  4831. elif tab_obj_name == "text_editor_tab":
  4832. self.toggle_codeeditor = False
  4833. elif tab_obj_name == "bookmarks_tab":
  4834. self.book_dialog_tab.rebuild_actions()
  4835. self.book_dialog_tab.deleteLater()
  4836. else:
  4837. return
  4838. # def on_plotarea_tab_closed(self, tab_idx):
  4839. # """
  4840. #
  4841. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4842. # :return:
  4843. # """
  4844. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4845. #
  4846. # if widget is not None:
  4847. # widget.deleteLater()
  4848. # self.ui.plot_tab_area.removeTab(tab_idx)
  4849. def on_flipy(self):
  4850. """
  4851. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4852. :return:
  4853. """
  4854. self.defaults.report_usage("on_flipy()")
  4855. obj_list = self.collection.get_selected()
  4856. xminlist = []
  4857. yminlist = []
  4858. xmaxlist = []
  4859. ymaxlist = []
  4860. if not obj_list:
  4861. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4862. else:
  4863. try:
  4864. # first get a bounding box to fit all
  4865. for obj in obj_list:
  4866. xmin, ymin, xmax, ymax = obj.bounds()
  4867. xminlist.append(xmin)
  4868. yminlist.append(ymin)
  4869. xmaxlist.append(xmax)
  4870. ymaxlist.append(ymax)
  4871. # get the minimum x,y and maximum x,y for all objects selected
  4872. xminimal = min(xminlist)
  4873. yminimal = min(yminlist)
  4874. xmaximal = max(xmaxlist)
  4875. ymaximal = max(ymaxlist)
  4876. px = 0.5 * (xminimal + xmaximal)
  4877. py = 0.5 * (yminimal + ymaximal)
  4878. # execute mirroring
  4879. for obj in obj_list:
  4880. obj.mirror('X', [px, py])
  4881. obj.plot()
  4882. self.object_changed.emit(obj)
  4883. self.inform.emit('[success] %s' %
  4884. _("Flip on Y axis done."))
  4885. except Exception as e:
  4886. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4887. return
  4888. def on_flipx(self):
  4889. """
  4890. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4891. :return:
  4892. """
  4893. self.defaults.report_usage("on_flipx()")
  4894. obj_list = self.collection.get_selected()
  4895. xminlist = []
  4896. yminlist = []
  4897. xmaxlist = []
  4898. ymaxlist = []
  4899. if not obj_list:
  4900. self.inform.emit('[WARNING_NOTCL] %s' %
  4901. _("No object selected to Flip on X axis."))
  4902. else:
  4903. try:
  4904. # first get a bounding box to fit all
  4905. for obj in obj_list:
  4906. xmin, ymin, xmax, ymax = obj.bounds()
  4907. xminlist.append(xmin)
  4908. yminlist.append(ymin)
  4909. xmaxlist.append(xmax)
  4910. ymaxlist.append(ymax)
  4911. # get the minimum x,y and maximum x,y for all objects selected
  4912. xminimal = min(xminlist)
  4913. yminimal = min(yminlist)
  4914. xmaximal = max(xmaxlist)
  4915. ymaximal = max(ymaxlist)
  4916. px = 0.5 * (xminimal + xmaximal)
  4917. py = 0.5 * (yminimal + ymaximal)
  4918. # execute mirroring
  4919. for obj in obj_list:
  4920. obj.mirror('Y', [px, py])
  4921. obj.plot()
  4922. self.object_changed.emit(obj)
  4923. self.inform.emit('[success] %s' %
  4924. _("Flip on X axis done."))
  4925. except Exception as e:
  4926. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4927. return
  4928. def on_rotate(self, silent=False, preset=None):
  4929. """
  4930. Executed when Options -> Rotate Selection menu entry is clicked.
  4931. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4932. :param preset: A value to be used as predefined angle for rotation.
  4933. :return:
  4934. """
  4935. self.defaults.report_usage("on_rotate()")
  4936. obj_list = self.collection.get_selected()
  4937. xminlist = []
  4938. yminlist = []
  4939. xmaxlist = []
  4940. ymaxlist = []
  4941. if not obj_list:
  4942. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4943. else:
  4944. if silent is False:
  4945. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4946. min=-360, max=360, decimals=4,
  4947. init_val=float(self.defaults['tools_transform_rotate']))
  4948. num, ok = rotatebox.get_value()
  4949. else:
  4950. num = preset
  4951. ok = True
  4952. if ok:
  4953. try:
  4954. # first get a bounding box to fit all
  4955. for obj in obj_list:
  4956. xmin, ymin, xmax, ymax = obj.bounds()
  4957. xminlist.append(xmin)
  4958. yminlist.append(ymin)
  4959. xmaxlist.append(xmax)
  4960. ymaxlist.append(ymax)
  4961. # get the minimum x,y and maximum x,y for all objects selected
  4962. xminimal = min(xminlist)
  4963. yminimal = min(yminlist)
  4964. xmaximal = max(xmaxlist)
  4965. ymaximal = max(ymaxlist)
  4966. px = 0.5 * (xminimal + xmaximal)
  4967. py = 0.5 * (yminimal + ymaximal)
  4968. for sel_obj in obj_list:
  4969. sel_obj.rotate(-float(num), point=(px, py))
  4970. sel_obj.plot()
  4971. self.object_changed.emit(sel_obj)
  4972. self.inform.emit('[success] %s' % _("Rotation done."))
  4973. except Exception as e:
  4974. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4975. return
  4976. def on_skewx(self):
  4977. """
  4978. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4979. :return:
  4980. """
  4981. self.defaults.report_usage("on_skewx()")
  4982. obj_list = self.collection.get_selected()
  4983. xminlist = []
  4984. yminlist = []
  4985. if not obj_list:
  4986. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4987. else:
  4988. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4989. min=-360, max=360, decimals=4,
  4990. init_val=float(self.defaults['tools_transform_skew_x']))
  4991. num, ok = skewxbox.get_value()
  4992. if ok:
  4993. # first get a bounding box to fit all
  4994. for obj in obj_list:
  4995. xmin, ymin, xmax, ymax = obj.bounds()
  4996. xminlist.append(xmin)
  4997. yminlist.append(ymin)
  4998. # get the minimum x,y and maximum x,y for all objects selected
  4999. xminimal = min(xminlist)
  5000. yminimal = min(yminlist)
  5001. for obj in obj_list:
  5002. obj.skew(num, 0, point=(xminimal, yminimal))
  5003. obj.plot()
  5004. self.object_changed.emit(obj)
  5005. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  5006. def on_skewy(self):
  5007. """
  5008. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5009. :return:
  5010. """
  5011. self.defaults.report_usage("on_skewy()")
  5012. obj_list = self.collection.get_selected()
  5013. xminlist = []
  5014. yminlist = []
  5015. if not obj_list:
  5016. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  5017. else:
  5018. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5019. min=-360, max=360, decimals=4,
  5020. init_val=float(self.defaults['tools_transform_skew_y']))
  5021. num, ok = skewybox.get_value()
  5022. if ok:
  5023. # first get a bounding box to fit all
  5024. for obj in obj_list:
  5025. xmin, ymin, xmax, ymax = obj.bounds()
  5026. xminlist.append(xmin)
  5027. yminlist.append(ymin)
  5028. # get the minimum x,y and maximum x,y for all objects selected
  5029. xminimal = min(xminlist)
  5030. yminimal = min(yminlist)
  5031. for obj in obj_list:
  5032. obj.skew(0, num, point=(xminimal, yminimal))
  5033. obj.plot()
  5034. self.object_changed.emit(obj)
  5035. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  5036. def on_plots_updated(self):
  5037. """
  5038. Callback used to report when the plots have changed.
  5039. Adjust axes and zooms to fit.
  5040. :return: None
  5041. """
  5042. if self.is_legacy is False:
  5043. self.plotcanvas.update()
  5044. else:
  5045. self.plotcanvas.auto_adjust_axes()
  5046. self.on_zoom_fit(None)
  5047. self.collection.update_view()
  5048. # self.inform.emit(_("Plots updated ..."))
  5049. def on_toolbar_replot(self):
  5050. """
  5051. Callback for toolbar button. Re-plots all objects.
  5052. :return: None
  5053. """
  5054. self.defaults.report_usage("on_toolbar_replot")
  5055. self.log.debug("on_toolbar_replot()")
  5056. try:
  5057. self.collection.get_active().read_form()
  5058. except AttributeError:
  5059. self.log.debug("on_toolbar_replot(): AttributeError")
  5060. pass
  5061. self.plot_all()
  5062. def grid_status(self):
  5063. return True if self.ui.grid_snap_btn.isChecked() else False
  5064. def populate_cmenu_grids(self):
  5065. units = self.defaults['units'].lower()
  5066. # for act in self.ui.cmenu_gridmenu.actions():
  5067. # act.triggered.disconnect()
  5068. self.ui.cmenu_gridmenu.clear()
  5069. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5070. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5071. _("Grid On/Off"))
  5072. grid_toggle.setCheckable(True)
  5073. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5074. self.ui.cmenu_gridmenu.addSeparator()
  5075. for grid in sorted_list:
  5076. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5077. "%s" % str(grid))
  5078. action.triggered.connect(self.set_grid)
  5079. self.ui.cmenu_gridmenu.addSeparator()
  5080. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5081. _("Add"))
  5082. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5083. _("Delete"))
  5084. grid_add.triggered.connect(self.on_grid_add)
  5085. grid_delete.triggered.connect(self.on_grid_delete)
  5086. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5087. def set_grid(self):
  5088. menu_action = self.sender()
  5089. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5090. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5091. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5092. def on_grid_add(self):
  5093. # ## Current application units in lower Case
  5094. units = self.defaults['units'].lower()
  5095. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5096. text=_('Enter a Grid Value:'),
  5097. min=0.0000, max=99.9999, decimals=4)
  5098. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5099. val, ok = grid_add_popup.get_value()
  5100. if ok:
  5101. if float(val) == 0:
  5102. self.inform.emit('[WARNING_NOTCL] %s' %
  5103. _("Please enter a grid value with non-zero value, in Float format."))
  5104. return
  5105. else:
  5106. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5107. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5108. self.inform.emit('[success] %s...' % _("New Grid added"))
  5109. else:
  5110. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  5111. else:
  5112. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  5113. def on_grid_delete(self):
  5114. # ## Current application units in lower Case
  5115. units = self.defaults['units'].lower()
  5116. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5117. text='Enter a Grid Value:',
  5118. min=0.0000, max=99.9999, decimals=4)
  5119. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5120. val, ok = grid_del_popup.get_value()
  5121. if ok:
  5122. if float(val) == 0:
  5123. self.inform.emit('[WARNING_NOTCL] %s' %
  5124. _("Please enter a grid value with non-zero value, in Float format."))
  5125. return
  5126. else:
  5127. try:
  5128. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5129. except ValueError:
  5130. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  5131. return
  5132. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5133. else:
  5134. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5135. def on_shortcut_list(self):
  5136. self.defaults.report_usage("on_shortcut_list()")
  5137. # add the tab if it was closed
  5138. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5139. # delete the absolute and relative position and messages in the infobar
  5140. self.ui.position_label.setText("")
  5141. # self.ui.rel_position_label.setText("")
  5142. # Switch plot_area to preferences page
  5143. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5144. # self.ui.show()
  5145. def on_select_tab(self, name):
  5146. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5147. if self.ui.splitter.sizes()[0] == 0:
  5148. self.ui.splitter.setSizes([1, 1])
  5149. else:
  5150. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5151. self.ui.splitter.setSizes([0, 1])
  5152. if name == 'project':
  5153. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5154. elif name == 'selected':
  5155. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5156. elif name == 'tool':
  5157. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5158. def on_copy_name(self):
  5159. self.defaults.report_usage("on_copy_name()")
  5160. obj = self.collection.get_active()
  5161. try:
  5162. name = obj.options["name"]
  5163. except AttributeError:
  5164. log.debug("on_copy_name() --> No object selected to copy it's name")
  5165. self.inform.emit('[WARNING_NOTCL]%s' %
  5166. _(" No object selected to copy it's name"))
  5167. return
  5168. self.clipboard.setText(name)
  5169. self.inform.emit(_("Name copied on clipboard ..."))
  5170. def on_mouse_click_over_plot(self, event):
  5171. """
  5172. Default actions are:
  5173. :param event: Contains information about the event, like which button
  5174. was clicked, the pixel coordinates and the axes coordinates.
  5175. :return: None
  5176. """
  5177. self.pos = []
  5178. if self.is_legacy is False:
  5179. event_pos = event.pos
  5180. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5181. # # Set the mouse button for panning
  5182. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5183. else:
  5184. event_pos = (event.xdata, event.ydata)
  5185. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5186. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5187. # So it can receive key presses
  5188. self.plotcanvas.native.setFocus()
  5189. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5190. if self.grid_status():
  5191. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5192. else:
  5193. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5194. try:
  5195. if event.button == 1:
  5196. # Reset here the relative coordinates so there is a new reference on the click position
  5197. if self.rel_point1 is None:
  5198. self.rel_point1 = self.pos
  5199. else:
  5200. self.rel_point2 = copy(self.rel_point1)
  5201. self.rel_point1 = self.pos
  5202. self.on_mouse_move_over_plot(event, origin_click=True)
  5203. except Exception as e:
  5204. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5205. def on_mouse_double_click_over_plot(self, event):
  5206. if event.button == 1:
  5207. self.doubleclick = True
  5208. def on_mouse_move_over_plot(self, event, origin_click=None):
  5209. """
  5210. Callback for the mouse motion event over the plot.
  5211. :param event: Contains information about the event.
  5212. :param origin_click
  5213. :return: None
  5214. """
  5215. if self.is_legacy is False:
  5216. event_pos = event.pos
  5217. if self.defaults["global_pan_button"] == '2':
  5218. pan_button = 2
  5219. else:
  5220. pan_button = 3
  5221. self.event_is_dragging = event.is_dragging
  5222. else:
  5223. event_pos = (event.xdata, event.ydata)
  5224. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5225. if self.defaults["global_pan_button"] == '2':
  5226. pan_button = 3
  5227. else:
  5228. pan_button = 2
  5229. self.event_is_dragging = self.plotcanvas.is_dragging
  5230. # So it can receive key presses but not when the Tcl Shell is active
  5231. if not self.ui.shell_dock.isVisible():
  5232. if not self.plotcanvas.native.hasFocus():
  5233. self.plotcanvas.native.setFocus()
  5234. self.pos_jump = event_pos
  5235. self.ui.popMenu.mouse_is_panning = False
  5236. if origin_click is None:
  5237. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5238. if event.button == pan_button and self.event_is_dragging == 1:
  5239. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5240. if self.ui.popMenu.popup_active:
  5241. self.ui.popMenu.popup_active = False
  5242. return
  5243. self.ui.popMenu.mouse_is_panning = True
  5244. return
  5245. if self.rel_point1 is not None:
  5246. try: # May fail in case mouse not within axes
  5247. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5248. if pos_canvas[0] is None or pos_canvas[1] is None:
  5249. return
  5250. if self.grid_status():
  5251. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5252. # Update cursor
  5253. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5254. symbol='++', edge_color=self.cursor_color_3D,
  5255. edge_width=self.defaults["global_cursor_width"],
  5256. size=self.defaults["global_cursor_size"])
  5257. else:
  5258. pos = (pos_canvas[0], pos_canvas[1])
  5259. self.dx = pos[0] - float(self.rel_point1[0])
  5260. self.dy = pos[1] - float(self.rel_point1[1])
  5261. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5262. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5263. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5264. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5265. units = self.defaults["units"].lower()
  5266. self.plotcanvas.text_hud.text = \
  5267. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5268. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5269. self.mouse = [pos[0], pos[1]]
  5270. # if the mouse is moved and the LMB is clicked then the action is a selection
  5271. if self.event_is_dragging == 1 and event.button == 1:
  5272. self.delete_selection_shape()
  5273. if self.dx < 0:
  5274. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5275. face_color=self.defaults['global_alt_sel_fill'])
  5276. self.selection_type = False
  5277. elif self.dx >= 0:
  5278. self.draw_moving_selection_shape(self.pos, pos)
  5279. self.selection_type = True
  5280. else:
  5281. self.selection_type = None
  5282. else:
  5283. self.selection_type = None
  5284. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  5285. if self.defaults['global_hover']:
  5286. for obj in self.collection.get_list():
  5287. try:
  5288. # select the object(s) only if it is enabled (plotted)
  5289. if obj.options['plot']:
  5290. if obj not in self.collection.get_selected():
  5291. poly_obj = Polygon(
  5292. [(obj.options['xmin'], obj.options['ymin']),
  5293. (obj.options['xmax'], obj.options['ymin']),
  5294. (obj.options['xmax'], obj.options['ymax']),
  5295. (obj.options['xmin'], obj.options['ymax'])]
  5296. )
  5297. if Point(pos).within(poly_obj):
  5298. if obj.isHovering is False:
  5299. obj.isHovering = True
  5300. obj.notHovering = True
  5301. # create the selection box around the selected object
  5302. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5303. else:
  5304. if obj.notHovering is True:
  5305. obj.notHovering = False
  5306. obj.isHovering = False
  5307. self.delete_hover_shape()
  5308. except Exception:
  5309. # the Exception here will happen if we try to select on screen and we have an
  5310. # newly (and empty) just created Geometry or Excellon object that do not have the
  5311. # xmin, xmax, ymin, ymax options.
  5312. # In this case poly_obj creation (see above) will fail
  5313. pass
  5314. except Exception as e:
  5315. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5316. self.ui.position_label.setText("")
  5317. # self.ui.rel_position_label.setText("")
  5318. self.mouse = None
  5319. def on_mouse_click_release_over_plot(self, event):
  5320. """
  5321. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5322. and has been registered in ''self.__init__()''.
  5323. :param event: contains information about the event.
  5324. :return:
  5325. """
  5326. if self.is_legacy is False:
  5327. event_pos = event.pos
  5328. right_button = 2
  5329. else:
  5330. event_pos = (event.xdata, event.ydata)
  5331. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5332. right_button = 3
  5333. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5334. if self.grid_status():
  5335. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5336. else:
  5337. pos = (pos_canvas[0], pos_canvas[1])
  5338. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5339. # canvas menu
  5340. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5341. self.ui.popMenu.mouse_is_panning = False
  5342. self.cursor = QtGui.QCursor()
  5343. self.populate_cmenu_grids()
  5344. self.ui.popMenu.popup(self.cursor.pos())
  5345. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5346. # selection and then select a type of selection ("enclosing" or "touching")
  5347. if event.button == 1: # left click
  5348. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5349. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5350. if modifiers == QtCore.Qt.ShiftModifier:
  5351. # do not auto open the Project Tab
  5352. self.click_noproject = True
  5353. self.clipboard.setText(
  5354. self.defaults["global_point_clipboard_format"] %
  5355. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5356. )
  5357. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5358. return
  5359. if self.doubleclick is True:
  5360. self.doubleclick = False
  5361. if self.collection.get_selected():
  5362. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5363. if self.ui.splitter.sizes()[0] == 0:
  5364. self.ui.splitter.setSizes([1, 1])
  5365. try:
  5366. # delete the selection shape(S) as it may be in the way
  5367. self.delete_selection_shape()
  5368. self.delete_hover_shape()
  5369. except Exception as e:
  5370. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5371. return
  5372. else:
  5373. # WORKAROUND for LEGACY MODE
  5374. if self.is_legacy is True:
  5375. # if there is no move on canvas then we have no dragging selection
  5376. if self.dx == 0 or self.dy == 0:
  5377. self.selection_type = None
  5378. if self.selection_type is not None:
  5379. try:
  5380. self.selection_area_handler(self.pos, pos, self.selection_type)
  5381. self.selection_type = None
  5382. except Exception as e:
  5383. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5384. return
  5385. else:
  5386. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5387. if key_modifier == QtCore.Qt.ShiftModifier:
  5388. mod_key = 'Shift'
  5389. elif key_modifier == QtCore.Qt.ControlModifier:
  5390. mod_key = 'Control'
  5391. else:
  5392. mod_key = None
  5393. try:
  5394. if self.command_active is None:
  5395. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5396. # deselect, and if it's not selected then it will be selected
  5397. # If there is no active command (self.command_active is None) then we check if we clicked
  5398. # on a object by checking the bounding limits against mouse click position
  5399. if mod_key == self.defaults["global_mselect_key"]:
  5400. self.select_objects(key='multisel')
  5401. else:
  5402. # If there is no active command (self.command_active is None) then we check if
  5403. # we clicked on a object by checking the bounding limits against mouse click position
  5404. self.select_objects()
  5405. self.delete_hover_shape()
  5406. except Exception as e:
  5407. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5408. return
  5409. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5410. """
  5411. :param start_pos: mouse position when the selection LMB click was done
  5412. :param end_pos: mouse position when the left mouse button is released
  5413. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5414. :return:
  5415. """
  5416. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5417. # delete previous selection shape
  5418. self.delete_selection_shape()
  5419. # make all objects inactive
  5420. self.collection.set_all_inactive()
  5421. for obj in self.collection.get_list():
  5422. try:
  5423. # select the object(s) only if it is enabled (plotted)
  5424. if obj.options['plot']:
  5425. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5426. (obj.options['xmax'], obj.options['ymin']),
  5427. (obj.options['xmax'], obj.options['ymax']),
  5428. (obj.options['xmin'], obj.options['ymax'])])
  5429. if sel_type is True:
  5430. if poly_obj.within(poly_selection):
  5431. # create the selection box around the selected object
  5432. if self.defaults['global_selection_shape'] is True:
  5433. self.draw_selection_shape(obj)
  5434. self.collection.set_active(obj.options['name'])
  5435. else:
  5436. if poly_selection.intersects(poly_obj):
  5437. # create the selection box around the selected object
  5438. if self.defaults['global_selection_shape'] is True:
  5439. self.draw_selection_shape(obj)
  5440. self.collection.set_active(obj.options['name'])
  5441. obj.selection_shape_drawn = True
  5442. except Exception as e:
  5443. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5444. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5445. # In this case poly_obj creation (see above) will fail
  5446. log.debug("App.selection_area_handler() --> %s" % str(e))
  5447. def select_objects(self, key=None):
  5448. """
  5449. Will select objects clicked on canvas
  5450. :param key: for future use in cumulative selection
  5451. :return:
  5452. """
  5453. # list where we store the overlapped objects under our mouse left click position
  5454. if key is None:
  5455. self.objects_under_the_click_list = []
  5456. # Populate the list with the overlapped objects on the click position
  5457. curr_x, curr_y = self.pos
  5458. for obj in self.all_objects_list:
  5459. # ScriptObject and DocumentObject objects can't be selected
  5460. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5461. continue
  5462. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5463. continue
  5464. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5465. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5466. if obj.options['name'] not in self.objects_under_the_click_list:
  5467. if obj.options['plot']:
  5468. # add objects to the objects_under_the_click list only if the object is plotted
  5469. # (active and not disabled)
  5470. self.objects_under_the_click_list.append(obj.options['name'])
  5471. try:
  5472. if self.objects_under_the_click_list:
  5473. curr_sel_obj = self.collection.get_active()
  5474. # case when there is only an object under the click and we toggle it
  5475. if len(self.objects_under_the_click_list) == 1:
  5476. if curr_sel_obj is None:
  5477. self.collection.set_active(self.objects_under_the_click_list[0])
  5478. curr_sel_obj = self.collection.get_active()
  5479. # create the selection box around the selected object
  5480. if self.defaults['global_selection_shape'] is True:
  5481. self.draw_selection_shape(curr_sel_obj)
  5482. curr_sel_obj.selection_shape_drawn = True
  5483. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5484. self.collection.on_objects_selection(False)
  5485. self.delete_selection_shape()
  5486. curr_sel_obj.selection_shape_drawn = False
  5487. self.collection.set_active(self.objects_under_the_click_list[0])
  5488. curr_sel_obj = self.collection.get_active()
  5489. # create the selection box around the selected object
  5490. if self.defaults['global_selection_shape'] is True:
  5491. self.draw_selection_shape(curr_sel_obj)
  5492. curr_sel_obj.selection_shape_drawn = True
  5493. self.selected_message(curr_sel_obj=curr_sel_obj)
  5494. elif curr_sel_obj.selection_shape_drawn is False:
  5495. if self.defaults['global_selection_shape'] is True:
  5496. self.draw_selection_shape(curr_sel_obj)
  5497. curr_sel_obj.selection_shape_drawn = True
  5498. else:
  5499. self.collection.on_objects_selection(False)
  5500. self.delete_selection_shape()
  5501. if self.call_source != 'app':
  5502. self.call_source = 'app'
  5503. self.selected_message(curr_sel_obj=curr_sel_obj)
  5504. else:
  5505. # If there is no selected object
  5506. # make active the first element of the overlapped objects list
  5507. if self.collection.get_active() is None:
  5508. self.collection.set_active(self.objects_under_the_click_list[0])
  5509. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5510. name_sel_obj = self.collection.get_active().options['name']
  5511. # In case that there is a selected object but it is not in the overlapped object list
  5512. # make that object inactive and activate the first element in the overlapped object list
  5513. if name_sel_obj not in self.objects_under_the_click_list:
  5514. self.collection.set_inactive(name_sel_obj)
  5515. name_sel_obj = self.objects_under_the_click_list[0]
  5516. self.collection.set_active(name_sel_obj)
  5517. else:
  5518. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5519. self.collection.set_all_inactive()
  5520. self.collection.set_active(
  5521. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5522. curr_sel_obj = self.collection.get_active()
  5523. # delete the possible selection box around a possible selected object
  5524. self.delete_selection_shape()
  5525. curr_sel_obj.selection_shape_drawn = False
  5526. # create the selection box around the selected object
  5527. if self.defaults['global_selection_shape'] is True:
  5528. self.draw_selection_shape(curr_sel_obj)
  5529. curr_sel_obj.selection_shape_drawn = True
  5530. self.selected_message(curr_sel_obj=curr_sel_obj)
  5531. else:
  5532. # deselect everything
  5533. self.collection.on_objects_selection(False)
  5534. # delete the possible selection box around a possible selected object
  5535. self.delete_selection_shape()
  5536. for o in self.collection.get_list():
  5537. o.selection_shape_drawn = False
  5538. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5539. # only when working on App
  5540. if self.call_source == 'app':
  5541. if self.click_noproject is False:
  5542. # if the Tool Tab is in focus don't change focus to Project Tab
  5543. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5544. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5545. else:
  5546. # restore auto open the Project Tab
  5547. self.click_noproject = False
  5548. # delete any text in the status bar, implicitly the last object name that was selected
  5549. # self.inform.emit("")
  5550. else:
  5551. self.call_source = 'app'
  5552. except Exception as e:
  5553. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5554. def selected_message(self, curr_sel_obj):
  5555. if curr_sel_obj:
  5556. if curr_sel_obj.kind == 'gerber':
  5557. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5558. color='green',
  5559. name=str(curr_sel_obj.options['name']),
  5560. tx=_("selected"))
  5561. )
  5562. elif curr_sel_obj.kind == 'excellon':
  5563. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5564. color='brown',
  5565. name=str(curr_sel_obj.options['name']),
  5566. tx=_("selected"))
  5567. )
  5568. elif curr_sel_obj.kind == 'cncjob':
  5569. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5570. color='blue',
  5571. name=str(curr_sel_obj.options['name']),
  5572. tx=_("selected"))
  5573. )
  5574. elif curr_sel_obj.kind == 'geometry':
  5575. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5576. color='red',
  5577. name=str(curr_sel_obj.options['name']),
  5578. tx=_("selected"))
  5579. )
  5580. def delete_hover_shape(self):
  5581. self.hover_shapes.clear()
  5582. self.hover_shapes.redraw()
  5583. def draw_hover_shape(self, sel_obj, color=None):
  5584. """
  5585. :param sel_obj: The object for which the hover shape must be drawn
  5586. :param color: The color of the hover shape
  5587. :return: None
  5588. """
  5589. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5590. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5591. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5592. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5593. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5594. if self.defaults['units'].upper() == 'MM':
  5595. hover_rect = hover_rect.buffer(-0.1)
  5596. hover_rect = hover_rect.buffer(0.2)
  5597. else:
  5598. hover_rect = hover_rect.buffer(-0.00393)
  5599. hover_rect = hover_rect.buffer(0.00787)
  5600. # if color:
  5601. # face = Color(color)
  5602. # face.alpha = 0.2
  5603. # outline = Color(color, alpha=0.8)
  5604. # else:
  5605. # face = Color(self.defaults['global_sel_fill'])
  5606. # face.alpha = 0.2
  5607. # outline = self.defaults['global_sel_line']
  5608. if color:
  5609. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5610. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5611. else:
  5612. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5613. outline = self.defaults['global_sel_line']
  5614. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5615. if self.is_legacy is True:
  5616. self.hover_shapes.redraw()
  5617. def delete_selection_shape(self):
  5618. self.move_tool.sel_shapes.clear()
  5619. self.move_tool.sel_shapes.redraw()
  5620. def draw_selection_shape(self, sel_obj, color=None):
  5621. """
  5622. Will draw a selection shape around the selected object.
  5623. :param sel_obj: The object for which the selection shape must be drawn
  5624. :param color: The color for the selection shape.
  5625. :return: None
  5626. """
  5627. if sel_obj is None:
  5628. return
  5629. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5630. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5631. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5632. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5633. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5634. if self.defaults['units'].upper() == 'MM':
  5635. sel_rect = sel_rect.buffer(-0.1)
  5636. sel_rect = sel_rect.buffer(0.2)
  5637. else:
  5638. sel_rect = sel_rect.buffer(-0.00393)
  5639. sel_rect = sel_rect.buffer(0.00787)
  5640. if color:
  5641. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5642. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5643. else:
  5644. if self.is_legacy is False:
  5645. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5646. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5647. else:
  5648. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5649. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5650. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5651. color=outline,
  5652. face_color=face,
  5653. update=True,
  5654. layer=0,
  5655. tolerance=None))
  5656. if self.is_legacy is True:
  5657. self.move_tool.sel_shapes.redraw()
  5658. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5659. """
  5660. Will draw a selection shape when dragging mouse on canvas.
  5661. :param old_coords: Old coordinates
  5662. :param coords: New coordinates
  5663. :param kwargs: Keyword arguments
  5664. :return:
  5665. """
  5666. if 'color' in kwargs:
  5667. color = kwargs['color']
  5668. else:
  5669. color = self.defaults['global_sel_line']
  5670. if 'face_color' in kwargs:
  5671. face_color = kwargs['face_color']
  5672. else:
  5673. face_color = self.defaults['global_sel_fill']
  5674. if 'face_alpha' in kwargs:
  5675. face_alpha = kwargs['face_alpha']
  5676. else:
  5677. face_alpha = 0.3
  5678. x0, y0 = old_coords
  5679. x1, y1 = coords
  5680. pt1 = (x0, y0)
  5681. pt2 = (x1, y0)
  5682. pt3 = (x1, y1)
  5683. pt4 = (x0, y1)
  5684. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5685. # color_t = Color(face_color)
  5686. # color_t.alpha = face_alpha
  5687. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5688. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5689. layer=0, tolerance=None)
  5690. if self.is_legacy is True:
  5691. self.move_tool.sel_shapes.redraw()
  5692. def on_file_new_click(self):
  5693. """
  5694. Callback for menu item File -> New.
  5695. Executed on clicking the Menu -> File -> New Project
  5696. :return:
  5697. """
  5698. if self.collection.get_list() and self.should_we_save:
  5699. msgbox = QtWidgets.QMessageBox()
  5700. # msgbox.setText("<B>Save changes ...</B>")
  5701. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5702. "Creating a New project will delete them.\n"
  5703. "Do you want to Save the project?"))
  5704. msgbox.setWindowTitle(_("Save changes"))
  5705. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5706. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5707. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5708. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5709. msgbox.setDefaultButton(bt_yes)
  5710. msgbox.exec_()
  5711. response = msgbox.clickedButton()
  5712. if response == bt_yes:
  5713. self.on_file_saveprojectas()
  5714. elif response == bt_cancel:
  5715. return
  5716. elif response == bt_no:
  5717. self.on_file_new()
  5718. else:
  5719. self.on_file_new()
  5720. self.inform.emit('[success] %s...' % _("New Project created"))
  5721. def on_file_new(self, cli=None):
  5722. """
  5723. Returns the application to its startup state. This method is thread-safe.
  5724. :param cli: Boolean. If True this method was run from command line
  5725. :return: None
  5726. """
  5727. self.defaults.report_usage("on_file_new")
  5728. # Remove everything from memory
  5729. App.log.debug("on_file_new()")
  5730. # close any editor that might be open
  5731. if self.call_source != 'app':
  5732. self.editor2object(cleanup=True)
  5733. # ## EDITOR section
  5734. self.geo_editor = FlatCAMGeoEditor(self)
  5735. self.exc_editor = FlatCAMExcEditor(self)
  5736. self.grb_editor = FlatCAMGrbEditor(self)
  5737. # Clear pool
  5738. self.clear_pool()
  5739. for obj in self.collection.get_list():
  5740. # delete shapes left drawn from mark shape_collections, if any
  5741. if isinstance(obj, GerberObject):
  5742. try:
  5743. for el in obj.mark_shapes:
  5744. obj.mark_shapes[el].clear(update=True)
  5745. obj.mark_shapes[el].enabled = False
  5746. del el
  5747. except AttributeError:
  5748. pass
  5749. # also delete annotation shapes, if any
  5750. elif isinstance(obj, CNCJobObject):
  5751. try:
  5752. obj.text_col.enabled = False
  5753. del obj.text_col
  5754. obj.annotation.clear(update=True)
  5755. del obj.annotation
  5756. except AttributeError:
  5757. pass
  5758. # delete the exclusion areas
  5759. self.exc_areas.clear_shapes()
  5760. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5761. self.shell.init_tcl()
  5762. # delete any selection shape on canvas
  5763. self.delete_selection_shape()
  5764. # delete all FlatCAM objects
  5765. self.collection.delete_all()
  5766. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5767. self.setup_component_editor()
  5768. # Clear project filename
  5769. self.project_filename = None
  5770. # Load the application defaults
  5771. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5772. # Re-fresh project options
  5773. self.on_options_app2project()
  5774. # Init FlatCAMTools
  5775. self.init_tools()
  5776. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5777. if cli is None:
  5778. # we need to go in reverse because once we remove a tab then the index changes
  5779. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5780. # and so on. Therefore the deletion should be done in reverse
  5781. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5782. for index in range(wdg_count, -1, -1):
  5783. try:
  5784. self.ui.plot_tab_area.closeTab(index)
  5785. except Exception as e:
  5786. log.debug("App.on_file_new() --> %s" % str(e))
  5787. # # And then add again the Plot Area
  5788. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5789. self.ui.plot_tab_area.protectTab(0)
  5790. # take the focus of the Notebook on Project Tab.
  5791. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5792. self.set_ui_title(name=_("New Project - Not saved"))
  5793. def obj_properties(self):
  5794. """
  5795. Will launch the object Properties Tool
  5796. :return:
  5797. """
  5798. self.defaults.report_usage("obj_properties()")
  5799. self.properties_tool.run(toggle=False)
  5800. def on_project_context_save(self):
  5801. """
  5802. Wrapper, will save the object function of it's type
  5803. :return:
  5804. """
  5805. obj = self.collection.get_active()
  5806. if type(obj) == GeometryObject:
  5807. self.on_file_exportdxf()
  5808. elif type(obj) == ExcellonObject:
  5809. self.on_file_saveexcellon()
  5810. elif type(obj) == CNCJobObject:
  5811. obj.on_exportgcode_button_click()
  5812. elif type(obj) == GerberObject:
  5813. self.on_file_savegerber()
  5814. elif type(obj) == ScriptObject:
  5815. self.on_file_savescript()
  5816. elif type(obj) == DocumentObject:
  5817. self.on_file_savedocument()
  5818. def obj_move(self):
  5819. """
  5820. Callback for the Move menu entry in various Context Menu's.
  5821. :return:
  5822. """
  5823. self.defaults.report_usage("obj_move()")
  5824. self.move_tool.run(toggle=False)
  5825. def on_fileopengerber(self, signal, name=None):
  5826. """
  5827. File menu callback for opening a Gerber.
  5828. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5829. :param name:
  5830. :return: None
  5831. """
  5832. self.defaults.report_usage("on_fileopengerber")
  5833. App.log.debug("on_fileopengerber()")
  5834. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5835. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5836. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5837. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5838. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5839. "*.mil);;" \
  5840. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5841. "Allegro Files (*.art);;" \
  5842. "Mentor Files (*.pho *.gdo);;" \
  5843. "All Files (*.*)"
  5844. if name is None:
  5845. try:
  5846. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5847. directory=self.get_last_folder(),
  5848. filter=_filter_)
  5849. except TypeError:
  5850. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5851. filenames = [str(filename) for filename in filenames]
  5852. else:
  5853. filenames = [name]
  5854. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5855. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5856. _("Opening Gerber file.")),
  5857. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5858. color=QtGui.QColor("gray"))
  5859. if len(filenames) == 0:
  5860. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5861. else:
  5862. for filename in filenames:
  5863. if filename != '':
  5864. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5865. def on_fileopenexcellon(self, signal, name=None):
  5866. """
  5867. File menu callback for opening an Excellon file.
  5868. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5869. :param name:
  5870. :return: None
  5871. """
  5872. self.defaults.report_usage("on_fileopenexcellon")
  5873. App.log.debug("on_fileopenexcellon()")
  5874. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5875. "All Files (*.*)"
  5876. if name is None:
  5877. try:
  5878. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5879. directory=self.get_last_folder(),
  5880. filter=_filter_)
  5881. except TypeError:
  5882. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5883. filenames = [str(filename) for filename in filenames]
  5884. else:
  5885. filenames = [str(name)]
  5886. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5887. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5888. _("Opening Excellon file.")),
  5889. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5890. color=QtGui.QColor("gray"))
  5891. if len(filenames) == 0:
  5892. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5893. else:
  5894. for filename in filenames:
  5895. if filename != '':
  5896. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5897. def on_fileopengcode(self, signal, name=None):
  5898. """
  5899. File menu call back for opening gcode.
  5900. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5901. :param name:
  5902. :return:
  5903. """
  5904. self.defaults.report_usage("on_fileopengcode")
  5905. App.log.debug("on_fileopengcode()")
  5906. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5907. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5908. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5909. "All Files (*.*)"
  5910. if name is None:
  5911. try:
  5912. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5913. directory=self.get_last_folder(),
  5914. filter=_filter_)
  5915. except TypeError:
  5916. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5917. filenames = [str(filename) for filename in filenames]
  5918. else:
  5919. filenames = [name]
  5920. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5921. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5922. _("Opening G-Code file.")),
  5923. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5924. color=QtGui.QColor("gray"))
  5925. if len(filenames) == 0:
  5926. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5927. else:
  5928. for filename in filenames:
  5929. if filename != '':
  5930. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5931. def on_file_openproject(self, signal):
  5932. """
  5933. File menu callback for opening a project.
  5934. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5935. :return: None
  5936. """
  5937. self.defaults.report_usage("on_file_openproject")
  5938. App.log.debug("on_file_openproject()")
  5939. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5940. try:
  5941. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5942. directory=self.get_last_folder(), filter=_filter_)
  5943. except TypeError:
  5944. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5945. # The Qt methods above will return a QString which can cause problems later.
  5946. # So far json.dump() will fail to serialize it.
  5947. # TODO: Improve the serialization methods and remove this fix.
  5948. filename = str(filename)
  5949. if filename == "":
  5950. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5951. else:
  5952. # self.worker_task.emit({'fcn': self.open_project,
  5953. # 'params': [filename]})
  5954. # The above was failing because open_project() is not
  5955. # thread safe. The new_project()
  5956. self.open_project(filename)
  5957. def on_fileopenhpgl2(self, signal, name=None):
  5958. """
  5959. File menu callback for opening a HPGL2.
  5960. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5961. :param name:
  5962. :return: None
  5963. """
  5964. self.defaults.report_usage("on_fileopenhpgl2")
  5965. App.log.debug("on_fileopenhpgl2()")
  5966. _filter_ = "HPGL2 Files (*.plt);;" \
  5967. "All Files (*.*)"
  5968. if name is None:
  5969. try:
  5970. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5971. directory=self.get_last_folder(),
  5972. filter=_filter_)
  5973. except TypeError:
  5974. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5975. filenames = [str(filename) for filename in filenames]
  5976. else:
  5977. filenames = [name]
  5978. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5979. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5980. _("Opening HPGL2 file.")),
  5981. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5982. color=QtGui.QColor("gray"))
  5983. if len(filenames) == 0:
  5984. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5985. else:
  5986. for filename in filenames:
  5987. if filename != '':
  5988. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5989. def on_file_openconfig(self, signal):
  5990. """
  5991. File menu callback for opening a config file.
  5992. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5993. :return: None
  5994. """
  5995. self.defaults.report_usage("on_file_openconfig")
  5996. App.log.debug("on_file_openconfig()")
  5997. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5998. try:
  5999. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6000. directory=self.data_path, filter=_filter_)
  6001. except TypeError:
  6002. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6003. filter=_filter_)
  6004. if filename == "":
  6005. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6006. else:
  6007. self.open_config_file(filename)
  6008. def on_file_exportsvg(self):
  6009. """
  6010. Callback for menu item File->Export SVG.
  6011. :return: None
  6012. """
  6013. self.defaults.report_usage("on_file_exportsvg")
  6014. App.log.debug("on_file_exportsvg()")
  6015. obj = self.collection.get_active()
  6016. if obj is None:
  6017. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6018. msg = _("Please Select a Geometry object to export")
  6019. msgbox = QtWidgets.QMessageBox()
  6020. msgbox.setInformativeText(msg)
  6021. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6022. msgbox.setDefaultButton(bt_ok)
  6023. msgbox.exec_()
  6024. return
  6025. # Check for more compatible types and add as required
  6026. if (not isinstance(obj, GeometryObject)
  6027. and not isinstance(obj, GerberObject)
  6028. and not isinstance(obj, CNCJobObject)
  6029. and not isinstance(obj, ExcellonObject)):
  6030. msg = '[ERROR_NOTCL] %s' % \
  6031. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6032. msgbox = QtWidgets.QMessageBox()
  6033. msgbox.setInformativeText(msg)
  6034. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6035. msgbox.setDefaultButton(bt_ok)
  6036. msgbox.exec_()
  6037. return
  6038. name = obj.options["name"]
  6039. _filter = "SVG File (*.svg);;All Files (*.*)"
  6040. try:
  6041. filename, _f = FCFileSaveDialog.get_saved_filename(
  6042. caption=_("Export SVG"),
  6043. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6044. filter=_filter)
  6045. except TypeError:
  6046. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6047. filename = str(filename)
  6048. if filename == "":
  6049. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6050. return
  6051. else:
  6052. self.export_svg(name, filename)
  6053. if self.defaults["global_open_style"] is False:
  6054. self.file_opened.emit("SVG", filename)
  6055. self.file_saved.emit("SVG", filename)
  6056. def on_file_exportpng(self):
  6057. self.defaults.report_usage("on_file_exportpng")
  6058. App.log.debug("on_file_exportpng()")
  6059. self.date = str(datetime.today()).rpartition('.')[0]
  6060. self.date = ''.join(c for c in self.date if c not in ':-')
  6061. self.date = self.date.replace(' ', '_')
  6062. if self.is_legacy is False:
  6063. image = _screenshot()
  6064. data = np.asarray(image)
  6065. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6066. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6067. return
  6068. filter_ = "PNG File (*.png);;All Files (*.*)"
  6069. try:
  6070. filename, _f = FCFileSaveDialog.get_saved_filename(
  6071. caption=_("Export PNG Image"),
  6072. directory=self.get_last_save_folder() + '/png_' + self.date,
  6073. filter=filter_)
  6074. except TypeError:
  6075. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6076. filename = str(filename)
  6077. if filename == "":
  6078. self.inform.emit(_("Cancelled."))
  6079. return
  6080. else:
  6081. if self.is_legacy is False:
  6082. write_png(filename, data)
  6083. else:
  6084. self.plotcanvas.figure.savefig(filename)
  6085. if self.defaults["global_open_style"] is False:
  6086. self.file_opened.emit("png", filename)
  6087. self.file_saved.emit("png", filename)
  6088. def on_file_savegerber(self):
  6089. """
  6090. Callback for menu item in Project context menu.
  6091. :return: None
  6092. """
  6093. self.defaults.report_usage("on_file_savegerber")
  6094. App.log.debug("on_file_savegerber()")
  6095. obj = self.collection.get_active()
  6096. if obj is None:
  6097. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6098. return
  6099. # Check for more compatible types and add as required
  6100. if not isinstance(obj, GerberObject):
  6101. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6102. return
  6103. name = self.collection.get_active().options["name"]
  6104. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6105. try:
  6106. filename, _f = FCFileSaveDialog.get_saved_filename(
  6107. caption="Save Gerber source file",
  6108. directory=self.get_last_save_folder() + '/' + name,
  6109. filter=_filter)
  6110. except TypeError:
  6111. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6112. filename = str(filename)
  6113. if filename == "":
  6114. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6115. return
  6116. else:
  6117. self.save_source_file(name, filename)
  6118. if self.defaults["global_open_style"] is False:
  6119. self.file_opened.emit("Gerber", filename)
  6120. self.file_saved.emit("Gerber", filename)
  6121. def on_file_savescript(self):
  6122. """
  6123. Callback for menu item in Project context menu.
  6124. :return: None
  6125. """
  6126. self.defaults.report_usage("on_file_savescript")
  6127. App.log.debug("on_file_savescript()")
  6128. obj = self.collection.get_active()
  6129. if obj is None:
  6130. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6131. return
  6132. # Check for more compatible types and add as required
  6133. if not isinstance(obj, ScriptObject):
  6134. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6135. return
  6136. name = self.collection.get_active().options["name"]
  6137. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6138. try:
  6139. filename, _f = FCFileSaveDialog.get_saved_filename(
  6140. caption="Save Script source file",
  6141. directory=self.get_last_save_folder() + '/' + name,
  6142. filter=_filter)
  6143. except TypeError:
  6144. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6145. filename = str(filename)
  6146. if filename == "":
  6147. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6148. return
  6149. else:
  6150. self.save_source_file(name, filename)
  6151. if self.defaults["global_open_style"] is False:
  6152. self.file_opened.emit("Script", filename)
  6153. self.file_saved.emit("Script", filename)
  6154. def on_file_savedocument(self):
  6155. """
  6156. Callback for menu item in Project context menu.
  6157. :return: None
  6158. """
  6159. self.defaults.report_usage("on_file_savedocument")
  6160. App.log.debug("on_file_savedocument()")
  6161. obj = self.collection.get_active()
  6162. if obj is None:
  6163. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6164. return
  6165. # Check for more compatible types and add as required
  6166. if not isinstance(obj, ScriptObject):
  6167. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6168. return
  6169. name = self.collection.get_active().options["name"]
  6170. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6171. try:
  6172. filename, _f = FCFileSaveDialog.get_saved_filename(
  6173. caption="Save Document source file",
  6174. directory=self.get_last_save_folder() + '/' + name,
  6175. filter=_filter)
  6176. except TypeError:
  6177. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6178. filename = str(filename)
  6179. if filename == "":
  6180. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6181. return
  6182. else:
  6183. self.save_source_file(name, filename)
  6184. if self.defaults["global_open_style"] is False:
  6185. self.file_opened.emit("Document", filename)
  6186. self.file_saved.emit("Document", filename)
  6187. def on_file_saveexcellon(self):
  6188. """
  6189. Callback for menu item in project context menu.
  6190. :return: None
  6191. """
  6192. self.defaults.report_usage("on_file_saveexcellon")
  6193. App.log.debug("on_file_saveexcellon()")
  6194. obj = self.collection.get_active()
  6195. if obj is None:
  6196. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6197. return
  6198. # Check for more compatible types and add as required
  6199. if not isinstance(obj, ExcellonObject):
  6200. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6201. return
  6202. name = self.collection.get_active().options["name"]
  6203. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6204. try:
  6205. filename, _f = FCFileSaveDialog.get_saved_filename(
  6206. caption=_("Save Excellon source file"),
  6207. directory=self.get_last_save_folder() + '/' + name,
  6208. filter=_filter)
  6209. except TypeError:
  6210. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6211. filename = str(filename)
  6212. if filename == "":
  6213. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6214. return
  6215. else:
  6216. self.save_source_file(name, filename)
  6217. if self.defaults["global_open_style"] is False:
  6218. self.file_opened.emit("Excellon", filename)
  6219. self.file_saved.emit("Excellon", filename)
  6220. def on_file_exportexcellon(self):
  6221. """
  6222. Callback for menu item File->Export->Excellon.
  6223. :return: None
  6224. """
  6225. self.defaults.report_usage("on_file_exportexcellon")
  6226. App.log.debug("on_file_exportexcellon()")
  6227. obj = self.collection.get_active()
  6228. if obj is None:
  6229. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6230. return
  6231. # Check for more compatible types and add as required
  6232. if not isinstance(obj, ExcellonObject):
  6233. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6234. return
  6235. name = self.collection.get_active().options["name"]
  6236. _filter = self.defaults["excellon_save_filters"]
  6237. try:
  6238. filename, _f = FCFileSaveDialog.get_saved_filename(
  6239. caption=_("Export Excellon"),
  6240. directory=self.get_last_save_folder() + '/' + name,
  6241. filter=_filter)
  6242. except TypeError:
  6243. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6244. filename = str(filename)
  6245. if filename == "":
  6246. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6247. return
  6248. else:
  6249. used_extension = filename.rpartition('.')[2]
  6250. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6251. self.export_excellon(name, filename)
  6252. if self.defaults["global_open_style"] is False:
  6253. self.file_opened.emit("Excellon", filename)
  6254. self.file_saved.emit("Excellon", filename)
  6255. def on_file_exportgerber(self):
  6256. """
  6257. Callback for menu item File->Export->Gerber.
  6258. :return: None
  6259. """
  6260. self.defaults.report_usage("on_file_exportgerber")
  6261. App.log.debug("on_file_exportgerber()")
  6262. obj = self.collection.get_active()
  6263. if obj is None:
  6264. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6265. return
  6266. # Check for more compatible types and add as required
  6267. if not isinstance(obj, GerberObject):
  6268. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6269. return
  6270. name = self.collection.get_active().options["name"]
  6271. _filter_ = self.defaults['gerber_save_filters']
  6272. try:
  6273. filename, _f = FCFileSaveDialog.get_saved_filename(
  6274. caption=_("Export Gerber"),
  6275. directory=self.get_last_save_folder() + '/' + name,
  6276. filter=_filter_)
  6277. except TypeError:
  6278. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6279. filename = str(filename)
  6280. if filename == "":
  6281. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6282. return
  6283. else:
  6284. used_extension = filename.rpartition('.')[2]
  6285. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6286. self.export_gerber(name, filename)
  6287. if self.defaults["global_open_style"] is False:
  6288. self.file_opened.emit("Gerber", filename)
  6289. self.file_saved.emit("Gerber", filename)
  6290. def on_file_exportdxf(self):
  6291. """
  6292. Callback for menu item File->Export DXF.
  6293. :return: None
  6294. """
  6295. self.defaults.report_usage("on_file_exportdxf")
  6296. App.log.debug("on_file_exportdxf()")
  6297. obj = self.collection.get_active()
  6298. if obj is None:
  6299. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6300. msg = _("Please Select a Geometry object to export")
  6301. msgbox = QtWidgets.QMessageBox()
  6302. msgbox.setInformativeText(msg)
  6303. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6304. msgbox.setDefaultButton(bt_ok)
  6305. msgbox.exec_()
  6306. return
  6307. # Check for more compatible types and add as required
  6308. if not isinstance(obj, GeometryObject):
  6309. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6310. msgbox = QtWidgets.QMessageBox()
  6311. msgbox.setInformativeText(msg)
  6312. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6313. msgbox.setDefaultButton(bt_ok)
  6314. msgbox.exec_()
  6315. return
  6316. name = self.collection.get_active().options["name"]
  6317. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6318. try:
  6319. filename, _f = FCFileSaveDialog.get_saved_filename(
  6320. caption=_("Export DXF"),
  6321. directory=self.get_last_save_folder() + '/' + name,
  6322. filter=_filter_)
  6323. except TypeError:
  6324. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6325. filename = str(filename)
  6326. if filename == "":
  6327. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6328. return
  6329. else:
  6330. self.export_dxf(name, filename)
  6331. if self.defaults["global_open_style"] is False:
  6332. self.file_opened.emit("DXF", filename)
  6333. self.file_saved.emit("DXF", filename)
  6334. def on_file_importsvg(self, type_of_obj):
  6335. """
  6336. Callback for menu item File->Import SVG.
  6337. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6338. :type type_of_obj: str
  6339. :return: None
  6340. """
  6341. self.defaults.report_usage("on_file_importsvg")
  6342. App.log.debug("on_file_importsvg()")
  6343. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6344. try:
  6345. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6346. directory=self.get_last_folder(), filter=_filter_)
  6347. except TypeError:
  6348. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6349. filter=_filter_)
  6350. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6351. type_of_obj = "geometry"
  6352. filenames = [str(filename) for filename in filenames]
  6353. if len(filenames) == 0:
  6354. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6355. else:
  6356. for filename in filenames:
  6357. if filename != '':
  6358. self.worker_task.emit({'fcn': self.import_svg,
  6359. 'params': [filename, type_of_obj]})
  6360. def on_file_importdxf(self, type_of_obj):
  6361. """
  6362. Callback for menu item File->Import DXF.
  6363. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6364. :type type_of_obj: str
  6365. :return: None
  6366. """
  6367. self.defaults.report_usage("on_file_importdxf")
  6368. App.log.debug("on_file_importdxf()")
  6369. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6370. try:
  6371. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6372. directory=self.get_last_folder(),
  6373. filter=_filter_)
  6374. except TypeError:
  6375. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6376. filter=_filter_)
  6377. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6378. type_of_obj = "geometry"
  6379. filenames = [str(filename) for filename in filenames]
  6380. if len(filenames) == 0:
  6381. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6382. else:
  6383. for filename in filenames:
  6384. if filename != '':
  6385. self.worker_task.emit({'fcn': self.import_dxf,
  6386. 'params': [filename, type_of_obj]})
  6387. # ###############################################################################################################
  6388. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6389. # ###############################################################################################################
  6390. def init_code_editor(self, name):
  6391. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6392. # add the tab if it was closed
  6393. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6394. self.text_editor_tab.setObjectName('text_editor_tab')
  6395. # delete the absolute and relative position and messages in the infobar
  6396. self.ui.position_label.setText("")
  6397. # self.ui.rel_position_label.setText("")
  6398. # first clear previous text in text editor (if any)
  6399. self.text_editor_tab.code_editor.clear()
  6400. self.text_editor_tab.code_editor.setReadOnly(False)
  6401. self.toggle_codeeditor = True
  6402. self.text_editor_tab.code_editor.completer_enable = False
  6403. self.text_editor_tab.buttonRun.hide()
  6404. # make sure to keep a reference to the code editor
  6405. self.reference_code_editor = self.text_editor_tab.code_editor
  6406. # Switch plot_area to CNCJob tab
  6407. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6408. def on_view_source(self):
  6409. """
  6410. Called when the user wants to see the source file of the selected object
  6411. :return:
  6412. """
  6413. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6414. self.proc_container.view.set_busy(_("Loading..."))
  6415. try:
  6416. obj = self.collection.get_active()
  6417. except Exception as e:
  6418. log.debug("App.on_view_source() --> %s" % str(e))
  6419. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6420. return 'fail'
  6421. if obj is None:
  6422. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6423. return 'fail'
  6424. flt = "All Files (*.*)"
  6425. if obj.kind == 'gerber':
  6426. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6427. elif obj.kind == 'excellon':
  6428. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6429. elif obj.kind == 'cncjob':
  6430. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6431. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6432. # add the tab if it was closed
  6433. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6434. self.source_editor_tab.setObjectName('source_editor_tab')
  6435. # delete the absolute and relative position and messages in the infobar
  6436. self.ui.position_label.setText("")
  6437. # self.ui.rel_position_label.setText("")
  6438. # first clear previous text in text editor (if any)
  6439. self.source_editor_tab.code_editor.clear()
  6440. self.source_editor_tab.code_editor.setReadOnly(False)
  6441. self.source_editor_tab.code_editor.completer_enable = False
  6442. self.source_editor_tab.buttonRun.hide()
  6443. # Switch plot_area to CNCJob tab
  6444. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6445. try:
  6446. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6447. except TypeError:
  6448. pass
  6449. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6450. try:
  6451. self.source_editor_tab.buttonSave.clicked.disconnect()
  6452. except TypeError:
  6453. pass
  6454. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6455. # then append the text from GCode to the text editor
  6456. if obj.kind == 'cncjob':
  6457. try:
  6458. file = obj.export_gcode(
  6459. preamble=self.defaults["cncjob_prepend"],
  6460. postamble=self.defaults["cncjob_append"],
  6461. to_file=True)
  6462. if file == 'fail':
  6463. return 'fail'
  6464. except AttributeError:
  6465. self.inform.emit('[WARNING_NOTCL] %s' %
  6466. _("There is no selected object for which to see it's source file code."))
  6467. return 'fail'
  6468. else:
  6469. try:
  6470. file = StringIO(obj.source_file)
  6471. except (AttributeError, TypeError):
  6472. self.inform.emit('[WARNING_NOTCL] %s' %
  6473. _("There is no selected object for which to see it's source file code."))
  6474. return 'fail'
  6475. self.source_editor_tab.t_frame.hide()
  6476. try:
  6477. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6478. # for line in file:
  6479. # QtWidgets.QApplication.processEvents()
  6480. # proc_line = str(line).strip('\n')
  6481. # self.source_editor_tab.code_editor.append(proc_line)
  6482. except Exception as e:
  6483. log.debug('App.on_view_source() -->%s' % str(e))
  6484. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6485. return
  6486. self.source_editor_tab.handleTextChanged()
  6487. self.source_editor_tab.t_frame.show()
  6488. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6489. self.proc_container.view.set_idle()
  6490. # self.ui.show()
  6491. def on_toggle_code_editor(self):
  6492. self.defaults.report_usage("on_toggle_code_editor()")
  6493. if self.toggle_codeeditor is False:
  6494. self.init_code_editor(name=_("Code Editor"))
  6495. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6496. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6497. self.text_editor_tab.buttonSave.clicked.disconnect()
  6498. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6499. else:
  6500. for idx in range(self.ui.plot_tab_area.count()):
  6501. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6502. self.ui.plot_tab_area.closeTab(idx)
  6503. break
  6504. self.toggle_codeeditor = False
  6505. def on_code_editor_close(self):
  6506. self.toggle_codeeditor = False
  6507. def goto_text_line(self):
  6508. """
  6509. Will scroll a text to the specified text line.
  6510. :return: None
  6511. """
  6512. dia_box = Dialog_box(title=_("Go to Line ..."),
  6513. label=_("Line:"),
  6514. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6515. initial_text='')
  6516. try:
  6517. line = int(dia_box.location) - 1
  6518. except (ValueError, TypeError):
  6519. line = 0
  6520. if dia_box.ok:
  6521. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6522. # at the top of the window
  6523. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6524. # get the document() of the TextEditor
  6525. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6526. # create a Text Cursor based on the searched line
  6527. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6528. # set cursor of the code editor with the cursor at the searcehd line
  6529. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6530. def on_filenewscript(self, silent=False):
  6531. """
  6532. Will create a new script file and open it in the Code Editor
  6533. :param silent: if True will not display status messages
  6534. :param name: if specified will be the name of the new script
  6535. :param text: pass a source file to the newly created script to be loaded in it
  6536. :return: None
  6537. """
  6538. if silent is False:
  6539. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6540. # delete the absolute and relative position and messages in the infobar
  6541. self.ui.position_label.setText("")
  6542. # self.ui.rel_position_label.setText("")
  6543. self.new_script_object()
  6544. # script_text = script_obj.source_file
  6545. #
  6546. # self.proc_container.view.set_busy(_("Loading..."))
  6547. # script_obj.script_editor_tab.t_frame.hide()
  6548. #
  6549. # script_obj.script_editor_tab.t_frame.show()
  6550. # self.proc_container.view.set_idle()
  6551. def on_fileopenscript(self, name=None, silent=False):
  6552. """
  6553. Will open a Tcl script file into the Code Editor
  6554. :param silent: if True will not display status messages
  6555. :param name: name of a Tcl script file to open
  6556. :return: None
  6557. """
  6558. self.defaults.report_usage("on_fileopenscript")
  6559. App.log.debug("on_fileopenscript()")
  6560. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6561. "All Files (*.*)"
  6562. if name:
  6563. filenames = [name]
  6564. else:
  6565. try:
  6566. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6567. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6568. except TypeError:
  6569. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6570. if len(filenames) == 0:
  6571. if silent is False:
  6572. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6573. else:
  6574. for filename in filenames:
  6575. if filename != '':
  6576. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6577. def on_fileopenscript_example(self, name=None, silent=False):
  6578. """
  6579. Will open a Tcl script file into the Code Editor
  6580. :param silent: if True will not display status messages
  6581. :param name: name of a Tcl script file to open
  6582. :return:
  6583. """
  6584. self.defaults.report_usage("on_fileopenscript_example")
  6585. log.debug("on_fileopenscript_example()")
  6586. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6587. "All Files (*.*)"
  6588. # test if the app was frozen and choose the path for the configuration file
  6589. if getattr(sys, "frozen", False) is True:
  6590. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6591. else:
  6592. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6593. if name:
  6594. filenames = [name]
  6595. else:
  6596. try:
  6597. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6598. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6599. except TypeError:
  6600. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6601. if len(filenames) == 0:
  6602. if silent is False:
  6603. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6604. else:
  6605. for filename in filenames:
  6606. if filename != '':
  6607. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6608. def on_filerunscript(self, name=None, silent=False):
  6609. """
  6610. File menu callback for loading and running a TCL script.
  6611. :param silent: if True will not display status messages
  6612. :param name: name of a Tcl script file to be run by FlatCAM
  6613. :return: None
  6614. """
  6615. self.defaults.report_usage("on_filerunscript")
  6616. App.log.debug("on_file_runscript()")
  6617. if name:
  6618. filename = name
  6619. if self.cmd_line_headless != 1:
  6620. self.splash.showMessage('%s: %ssec\n%s' %
  6621. (_("Canvas initialization started.\n"
  6622. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6623. _("Executing ScriptObject file.")
  6624. ),
  6625. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6626. color=QtGui.QColor("gray"))
  6627. else:
  6628. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6629. "All Files (*.*)"
  6630. try:
  6631. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6632. directory=self.get_last_folder(), filter=_filter_)
  6633. except TypeError:
  6634. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6635. # The Qt methods above will return a QString which can cause problems later.
  6636. # So far json.dump() will fail to serialize it.
  6637. filename = str(filename)
  6638. if filename == "":
  6639. if silent is False:
  6640. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6641. else:
  6642. if self.cmd_line_headless != 1:
  6643. if self.ui.shell_dock.isHidden():
  6644. self.ui.shell_dock.show()
  6645. try:
  6646. with open(filename, "r") as tcl_script:
  6647. cmd_line_shellfile_content = tcl_script.read()
  6648. if self.cmd_line_headless != 1:
  6649. self.shell.exec_command(cmd_line_shellfile_content)
  6650. else:
  6651. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6652. if silent is False:
  6653. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6654. except Exception as e:
  6655. log.debug("App.on_filerunscript() -> %s" % str(e))
  6656. sys.exit(2)
  6657. def on_file_saveproject(self, silent=False):
  6658. """
  6659. Callback for menu item File->Save Project. Saves the project to
  6660. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6661. if set to None. The project is saved by calling ``self.save_project()``.
  6662. :param silent: if True will not display status messages
  6663. :return: None
  6664. """
  6665. self.defaults.report_usage("on_file_saveproject")
  6666. if self.project_filename is None:
  6667. self.on_file_saveprojectas()
  6668. else:
  6669. self.worker_task.emit({'fcn': self.save_project,
  6670. 'params': [self.project_filename, silent]})
  6671. if self.defaults["global_open_style"] is False:
  6672. self.file_opened.emit("project", self.project_filename)
  6673. self.file_saved.emit("project", self.project_filename)
  6674. self.set_ui_title(name=self.project_filename)
  6675. self.should_we_save = False
  6676. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6677. """
  6678. Callback for menu item File->Save Project As... Opens a file
  6679. chooser and saves the project to the given file via
  6680. ``self.save_project()``.
  6681. :param make_copy if to be create a copy of the project; boolean
  6682. :param use_thread: if to be run in a separate thread; boolean
  6683. :param quit_action: if to be followed by quiting the application; boolean
  6684. :return: None
  6685. """
  6686. self.defaults.report_usage("on_file_saveprojectas")
  6687. self.date = str(datetime.today()).rpartition('.')[0]
  6688. self.date = ''.join(c for c in self.date if c not in ':-')
  6689. self.date = self.date.replace(' ', '_')
  6690. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6691. try:
  6692. filename, _f = FCFileSaveDialog.get_saved_filename(
  6693. caption=_("Save Project As ..."),
  6694. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6695. proj=_("Project")),
  6696. filter=filter_
  6697. )
  6698. except TypeError:
  6699. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6700. filename = str(filename)
  6701. if filename == '':
  6702. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6703. return
  6704. if use_thread is True:
  6705. self.worker_task.emit({'fcn': self.save_project,
  6706. 'params': [filename, quit_action]})
  6707. else:
  6708. self.save_project(filename, quit_action)
  6709. # self.save_project(filename)
  6710. if self.defaults["global_open_style"] is False:
  6711. self.file_opened.emit("project", filename)
  6712. self.file_saved.emit("project", filename)
  6713. if not make_copy:
  6714. self.project_filename = filename
  6715. self.set_ui_title(name=self.project_filename)
  6716. self.should_we_save = False
  6717. def on_file_save_objects_pdf(self, use_thread=True):
  6718. self.date = str(datetime.today()).rpartition('.')[0]
  6719. self.date = ''.join(c for c in self.date if c not in ':-')
  6720. self.date = self.date.replace(' ', '_')
  6721. try:
  6722. obj_selection = self.collection.get_selected()
  6723. if len(obj_selection) == 1:
  6724. obj_name = str(obj_selection[0].options['name'])
  6725. else:
  6726. obj_name = _("FlatCAM objects print")
  6727. except AttributeError as err:
  6728. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6729. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6730. return
  6731. if not obj_selection:
  6732. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6733. return
  6734. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6735. try:
  6736. filename, _f = FCFileSaveDialog.get_saved_filename(
  6737. caption=_("Save Object as PDF ..."),
  6738. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6739. obj_name=obj_name,
  6740. date=self.date),
  6741. filter=filter_
  6742. )
  6743. except TypeError:
  6744. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  6745. filename = str(filename)
  6746. if filename == '':
  6747. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6748. return
  6749. if use_thread is True:
  6750. self.proc_container.new(_("Printing PDF ... Please wait."))
  6751. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6752. else:
  6753. self.save_pdf(filename, obj_selection)
  6754. # self.save_project(filename)
  6755. if self.defaults["global_open_style"] is False:
  6756. self.file_opened.emit("pdf", filename)
  6757. self.file_saved.emit("pdf", filename)
  6758. def save_pdf(self, file_name, obj_selection):
  6759. p_size = self.defaults['global_workspaceT']
  6760. orientation = self.defaults['global_workspace_orientation']
  6761. color = 'black'
  6762. transparency_level = 1.0
  6763. self.pagesize = {}
  6764. self.pagesize.update(
  6765. {
  6766. 'Bounds': None,
  6767. 'A0': (841 * mm, 1189 * mm),
  6768. 'A1': (594 * mm, 841 * mm),
  6769. 'A2': (420 * mm, 594 * mm),
  6770. 'A3': (297 * mm, 420 * mm),
  6771. 'A4': (210 * mm, 297 * mm),
  6772. 'A5': (148 * mm, 210 * mm),
  6773. 'A6': (105 * mm, 148 * mm),
  6774. 'A7': (74 * mm, 105 * mm),
  6775. 'A8': (52 * mm, 74 * mm),
  6776. 'A9': (37 * mm, 52 * mm),
  6777. 'A10': (26 * mm, 37 * mm),
  6778. 'B0': (1000 * mm, 1414 * mm),
  6779. 'B1': (707 * mm, 1000 * mm),
  6780. 'B2': (500 * mm, 707 * mm),
  6781. 'B3': (353 * mm, 500 * mm),
  6782. 'B4': (250 * mm, 353 * mm),
  6783. 'B5': (176 * mm, 250 * mm),
  6784. 'B6': (125 * mm, 176 * mm),
  6785. 'B7': (88 * mm, 125 * mm),
  6786. 'B8': (62 * mm, 88 * mm),
  6787. 'B9': (44 * mm, 62 * mm),
  6788. 'B10': (31 * mm, 44 * mm),
  6789. 'C0': (917 * mm, 1297 * mm),
  6790. 'C1': (648 * mm, 917 * mm),
  6791. 'C2': (458 * mm, 648 * mm),
  6792. 'C3': (324 * mm, 458 * mm),
  6793. 'C4': (229 * mm, 324 * mm),
  6794. 'C5': (162 * mm, 229 * mm),
  6795. 'C6': (114 * mm, 162 * mm),
  6796. 'C7': (81 * mm, 114 * mm),
  6797. 'C8': (57 * mm, 81 * mm),
  6798. 'C9': (40 * mm, 57 * mm),
  6799. 'C10': (28 * mm, 40 * mm),
  6800. # American paper sizes
  6801. 'LETTER': (8.5 * inch, 11 * inch),
  6802. 'LEGAL': (8.5 * inch, 14 * inch),
  6803. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6804. # From https://en.wikipedia.org/wiki/Paper_size
  6805. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6806. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6807. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6808. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6809. 'LEDGER': (17 * inch, 11 * inch),
  6810. }
  6811. )
  6812. exported_svg = []
  6813. for obj in obj_selection:
  6814. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6815. scale_factor_x=None, scale_factor_y=None,
  6816. skew_factor_x=None, skew_factor_y=None,
  6817. mirror=None)
  6818. if obj.kind.lower() == 'gerber':
  6819. # color = self.defaults["gerber_plot_fill"][:-2]
  6820. color = obj.fill_color[:-2]
  6821. elif obj.kind.lower() == 'excellon':
  6822. color = '#C40000'
  6823. elif obj.kind.lower() == 'geometry':
  6824. color = self.defaults["global_draw_color"]
  6825. # Change the attributes of the exported SVG
  6826. # We don't need stroke-width
  6827. # We set opacity to maximum
  6828. # We set the colour to WHITE
  6829. root = ET.fromstring(svg_obj)
  6830. for child in root:
  6831. child.set('fill', str(color))
  6832. child.set('opacity', str(transparency_level))
  6833. child.set('stroke', str(color))
  6834. exported_svg.append(ET.tostring(root))
  6835. xmin = Inf
  6836. ymin = Inf
  6837. xmax = -Inf
  6838. ymax = -Inf
  6839. for obj in obj_selection:
  6840. try:
  6841. gxmin, gymin, gxmax, gymax = obj.bounds()
  6842. xmin = min([xmin, gxmin])
  6843. ymin = min([ymin, gymin])
  6844. xmax = max([xmax, gxmax])
  6845. ymax = max([ymax, gymax])
  6846. except Exception as e:
  6847. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6848. # Determine bounding area for svg export
  6849. bounds = [xmin, ymin, xmax, ymax]
  6850. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6851. # This contain the measure units
  6852. uom = obj_selection[0].units.lower()
  6853. # Define a boundary around SVG of about 1.0mm (~39mils)
  6854. if uom in "mm":
  6855. boundary = 1.0
  6856. else:
  6857. boundary = 0.0393701
  6858. # Convert everything to strings for use in the xml doc
  6859. svgwidth = str(size[0] + (2 * boundary))
  6860. svgheight = str(size[1] + (2 * boundary))
  6861. minx = str(bounds[0] - boundary)
  6862. miny = str(bounds[1] + boundary + size[1])
  6863. # Add a SVG Header and footer to the svg output from shapely
  6864. # The transform flips the Y Axis so that everything renders
  6865. # properly within svg apps such as inkscape
  6866. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6867. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6868. svg_header += 'width="' + svgwidth + uom + '" '
  6869. svg_header += 'height="' + svgheight + uom + '" '
  6870. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6871. svg_header += '>'
  6872. svg_header += '<g transform="scale(1,-1)">'
  6873. svg_footer = '</g> </svg>'
  6874. svg_elem = str(svg_header)
  6875. for svg_item in exported_svg:
  6876. svg_elem += str(svg_item)
  6877. svg_elem += str(svg_footer)
  6878. # Parse the xml through a xml parser just to add line feeds
  6879. # and to make it look more pretty for the output
  6880. doc = parse_xml_string(svg_elem)
  6881. doc_final = doc.toprettyxml()
  6882. try:
  6883. if self.defaults['units'].upper() == 'IN':
  6884. unit = inch
  6885. else:
  6886. unit = mm
  6887. doc_final = StringIO(doc_final)
  6888. drawing = svg2rlg(doc_final)
  6889. if p_size == 'Bounds':
  6890. renderPDF.drawToFile(drawing, file_name)
  6891. else:
  6892. if orientation == 'p':
  6893. page_size = portrait(self.pagesize[p_size])
  6894. else:
  6895. page_size = landscape(self.pagesize[p_size])
  6896. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6897. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6898. renderPDF.draw(drawing, my_canvas, 0, 0)
  6899. my_canvas.save()
  6900. except Exception as e:
  6901. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6902. return 'fail'
  6903. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6904. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6905. """
  6906. Exports a Geometry Object to an SVG file.
  6907. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6908. :param filename: Path to the SVG file to save to.
  6909. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6910. :return:
  6911. """
  6912. self.defaults.report_usage("export_svg()")
  6913. if filename is None:
  6914. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6915. is not None else self.defaults["global_last_folder"]
  6916. self.log.debug("export_svg()")
  6917. try:
  6918. obj = self.collection.get_by_name(str(obj_name))
  6919. except Exception:
  6920. # TODO: The return behavior has not been established... should raise exception?
  6921. return "Could not retrieve object: %s" % obj_name
  6922. with self.proc_container.new(_("Exporting SVG")) as proc:
  6923. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6924. # Determine bounding area for svg export
  6925. bounds = obj.bounds()
  6926. size = obj.size()
  6927. # Convert everything to strings for use in the xml doc
  6928. svgwidth = str(size[0])
  6929. svgheight = str(size[1])
  6930. minx = str(bounds[0])
  6931. miny = str(bounds[1] - size[1])
  6932. uom = obj.units.lower()
  6933. # Add a SVG Header and footer to the svg output from shapely
  6934. # The transform flips the Y Axis so that everything renders
  6935. # properly within svg apps such as inkscape
  6936. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6937. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6938. svg_header += 'width="' + svgwidth + uom + '" '
  6939. svg_header += 'height="' + svgheight + uom + '" '
  6940. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6941. svg_header += '<g transform="scale(1,-1)">'
  6942. svg_footer = '</g> </svg>'
  6943. svg_elem = svg_header + exported_svg + svg_footer
  6944. # Parse the xml through a xml parser just to add line feeds
  6945. # and to make it look more pretty for the output
  6946. svgcode = parse_xml_string(svg_elem)
  6947. svgcode = svgcode.toprettyxml()
  6948. try:
  6949. with open(filename, 'w') as fp:
  6950. fp.write(svgcode)
  6951. except PermissionError:
  6952. self.inform.emit('[WARNING] %s' %
  6953. _("Permission denied, saving not possible.\n"
  6954. "Most likely another app is holding the file open and not accessible."))
  6955. return 'fail'
  6956. if self.defaults["global_open_style"] is False:
  6957. self.file_opened.emit("SVG", filename)
  6958. self.file_saved.emit("SVG", filename)
  6959. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6960. def save_source_file(self, obj_name, filename, use_thread=True):
  6961. """
  6962. Exports a FlatCAM Object to an Gerber/Excellon file.
  6963. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6964. :param filename: Path to the Gerber file to save to.
  6965. :param use_thread: if to be run in a separate thread
  6966. :return:
  6967. """
  6968. self.defaults.report_usage("save source file()")
  6969. if filename is None:
  6970. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6971. is not None else self.defaults["global_last_folder"]
  6972. self.log.debug("save source file()")
  6973. obj = self.collection.get_by_name(obj_name)
  6974. file_string = StringIO(obj.source_file)
  6975. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6976. if file_string.getvalue() == '':
  6977. self.inform.emit('[ERROR_NOTCL] %s' %
  6978. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6979. return 'fail'
  6980. try:
  6981. with open(filename, 'w') as file:
  6982. file.writelines('G04*\n')
  6983. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6984. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6985. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6986. file.writelines('G04 Created on : %s*\n' % time_string)
  6987. for line in file_string:
  6988. file.writelines(line)
  6989. except PermissionError:
  6990. self.inform.emit('[WARNING] %s' %
  6991. _("Permission denied, saving not possible.\n"
  6992. "Most likely another app is holding the file open and not accessible."))
  6993. return 'fail'
  6994. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6995. """
  6996. Exports a Excellon Object to an Excellon file.
  6997. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6998. :param filename: Path to the Excellon file to save to.
  6999. :param local_use:
  7000. :param use_thread: if to be run in a separate thread
  7001. :return:
  7002. """
  7003. self.defaults.report_usage("export_excellon()")
  7004. if filename is None:
  7005. if self.defaults["global_last_save_folder"]:
  7006. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7007. else:
  7008. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7009. self.log.debug("export_excellon()")
  7010. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7011. self.defaults["excellon_exp_decimals"]
  7012. )
  7013. if local_use is None:
  7014. try:
  7015. obj = self.collection.get_by_name(str(obj_name))
  7016. except Exception:
  7017. return "Could not retrieve object: %s" % obj_name
  7018. else:
  7019. obj = local_use
  7020. if not isinstance(obj, ExcellonObject):
  7021. self.inform.emit('[ERROR_NOTCL] %s' %
  7022. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7023. return
  7024. # updated units
  7025. eunits = self.defaults["excellon_exp_units"]
  7026. ewhole = self.defaults["excellon_exp_integer"]
  7027. efract = self.defaults["excellon_exp_decimals"]
  7028. ezeros = self.defaults["excellon_exp_zeros"]
  7029. eformat = self.defaults["excellon_exp_format"]
  7030. slot_type = self.defaults["excellon_exp_slot_type"]
  7031. fc_units = self.defaults['units'].upper()
  7032. if fc_units == 'MM':
  7033. factor = 1 if eunits == 'METRIC' else 0.03937
  7034. else:
  7035. factor = 25.4 if eunits == 'METRIC' else 1
  7036. def make_excellon():
  7037. try:
  7038. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7039. header = 'M48\n'
  7040. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7041. (str(self.version), str(self.version_date))
  7042. header += ';Filename: %s' % str(obj_name) + '\n'
  7043. header += ';Created on : %s' % time_str + '\n'
  7044. if eformat == 'dec':
  7045. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7046. header += eunits + '\n'
  7047. for tool in obj.tools:
  7048. if eunits == 'METRIC':
  7049. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7050. tool=str(tool),
  7051. dec=2)
  7052. else:
  7053. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7054. tool=str(tool),
  7055. dec=4)
  7056. else:
  7057. if ezeros == 'LZ':
  7058. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7059. form='ndec', e_zeros='LZ', factor=factor,
  7060. slot_type=slot_type)
  7061. header += '%s,%s\n' % (eunits, 'LZ')
  7062. header += format_exc
  7063. for tool in obj.tools:
  7064. if eunits == 'METRIC':
  7065. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7066. tool=str(tool),
  7067. dec=2)
  7068. else:
  7069. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7070. tool=str(tool),
  7071. dec=4)
  7072. else:
  7073. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7074. form='ndec', e_zeros='TZ', factor=factor,
  7075. slot_type=slot_type)
  7076. header += '%s,%s\n' % (eunits, 'TZ')
  7077. header += format_exc
  7078. for tool in obj.tools:
  7079. if eunits == 'METRIC':
  7080. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7081. tool=str(tool),
  7082. dec=2)
  7083. else:
  7084. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7085. tool=str(tool),
  7086. dec=4)
  7087. header += '%\n'
  7088. footer = 'M30\n'
  7089. exported_excellon = header
  7090. exported_excellon += excellon_code
  7091. exported_excellon += footer
  7092. if local_use is None:
  7093. try:
  7094. with open(filename, 'w') as fp:
  7095. fp.write(exported_excellon)
  7096. except PermissionError:
  7097. self.inform.emit('[WARNING] %s' %
  7098. _("Permission denied, saving not possible.\n"
  7099. "Most likely another app is holding the file open and not accessible."))
  7100. return 'fail'
  7101. if self.defaults["global_open_style"] is False:
  7102. self.file_opened.emit("Excellon", filename)
  7103. self.file_saved.emit("Excellon", filename)
  7104. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7105. else:
  7106. return exported_excellon
  7107. except Exception as e:
  7108. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7109. return 'fail'
  7110. if use_thread is True:
  7111. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7112. def job_thread_exc(app_obj):
  7113. ret = make_excellon()
  7114. if ret == 'fail':
  7115. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7116. return
  7117. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7118. else:
  7119. eret = make_excellon()
  7120. if eret == 'fail':
  7121. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7122. return 'fail'
  7123. if local_use is not None:
  7124. return eret
  7125. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7126. """
  7127. Exports a Gerber Object to an Gerber file.
  7128. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7129. :param filename: Path to the Gerber file to save to.
  7130. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7131. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7132. :param use_thread: if to be run in a separate thread
  7133. :return:
  7134. """
  7135. self.defaults.report_usage("export_gerber()")
  7136. if filename is None:
  7137. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7138. is not None else self.defaults["global_last_folder"]
  7139. self.log.debug("export_gerber()")
  7140. if local_use is None:
  7141. try:
  7142. obj = self.collection.get_by_name(str(obj_name))
  7143. except Exception:
  7144. return "Could not retrieve object: %s" % obj_name
  7145. else:
  7146. obj = local_use
  7147. # updated units
  7148. gunits = self.defaults["gerber_exp_units"]
  7149. gwhole = self.defaults["gerber_exp_integer"]
  7150. gfract = self.defaults["gerber_exp_decimals"]
  7151. gzeros = self.defaults["gerber_exp_zeros"]
  7152. fc_units = self.defaults['units'].upper()
  7153. if fc_units == 'MM':
  7154. factor = 1 if gunits == 'MM' else 0.03937
  7155. else:
  7156. factor = 25.4 if gunits == 'MM' else 1
  7157. def make_gerber():
  7158. try:
  7159. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7160. header = 'G04*\n'
  7161. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7162. (str(self.version), str(self.version_date))
  7163. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7164. header += 'G04 Created on : %s*' % time_str + '\n'
  7165. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7166. header += "%MO{units}*%\n".format(units=gunits)
  7167. for apid in obj.apertures:
  7168. if obj.apertures[apid]['type'] == 'C':
  7169. header += "%ADD{apid}{type},{size}*%\n".format(
  7170. apid=str(apid),
  7171. type='C',
  7172. size=(factor * obj.apertures[apid]['size'])
  7173. )
  7174. elif obj.apertures[apid]['type'] == 'R':
  7175. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7176. apid=str(apid),
  7177. type='R',
  7178. width=(factor * obj.apertures[apid]['width']),
  7179. height=(factor * obj.apertures[apid]['height'])
  7180. )
  7181. elif obj.apertures[apid]['type'] == 'O':
  7182. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7183. apid=str(apid),
  7184. type='O',
  7185. width=(factor * obj.apertures[apid]['width']),
  7186. height=(factor * obj.apertures[apid]['height'])
  7187. )
  7188. header += '\n'
  7189. # obsolete units but some software may need it
  7190. if gunits == 'IN':
  7191. header += 'G70*\n'
  7192. else:
  7193. header += 'G71*\n'
  7194. # Absolute Mode
  7195. header += 'G90*\n'
  7196. header += 'G01*\n'
  7197. # positive polarity
  7198. header += '%LPD*%\n'
  7199. footer = 'M02*\n'
  7200. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7201. exported_gerber = header
  7202. exported_gerber += gerber_code
  7203. exported_gerber += footer
  7204. if local_use is None:
  7205. try:
  7206. with open(filename, 'w') as fp:
  7207. fp.write(exported_gerber)
  7208. except PermissionError:
  7209. self.inform.emit('[WARNING] %s' %
  7210. _("Permission denied, saving not possible.\n"
  7211. "Most likely another app is holding the file open and not accessible."))
  7212. return 'fail'
  7213. if self.defaults["global_open_style"] is False:
  7214. self.file_opened.emit("Gerber", filename)
  7215. self.file_saved.emit("Gerber", filename)
  7216. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7217. else:
  7218. return exported_gerber
  7219. except Exception as e:
  7220. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7221. return 'fail'
  7222. if use_thread is True:
  7223. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7224. def job_thread_grb(app_obj):
  7225. ret = make_gerber()
  7226. if ret == 'fail':
  7227. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7228. return
  7229. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7230. else:
  7231. gret = make_gerber()
  7232. if gret == 'fail':
  7233. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7234. return 'fail'
  7235. if local_use is not None:
  7236. return gret
  7237. def export_dxf(self, obj_name, filename, use_thread=True):
  7238. """
  7239. Exports a Geometry Object to an DXF file.
  7240. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7241. :param filename: Path to the DXF file to save to.
  7242. :param use_thread: if to be run in a separate thread
  7243. :return:
  7244. """
  7245. self.defaults.report_usage("export_dxf()")
  7246. if filename is None:
  7247. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7248. is not None else self.defaults["global_last_folder"]
  7249. self.log.debug("export_dxf()")
  7250. try:
  7251. obj = self.collection.get_by_name(str(obj_name))
  7252. except Exception:
  7253. # TODO: The return behavior has not been established... should raise exception?
  7254. return "Could not retrieve object: %s" % obj_name
  7255. def make_dxf():
  7256. try:
  7257. dxf_code = obj.export_dxf()
  7258. dxf_code.saveas(filename)
  7259. if self.defaults["global_open_style"] is False:
  7260. self.file_opened.emit("DXF", filename)
  7261. self.file_saved.emit("DXF", filename)
  7262. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7263. except Exception:
  7264. return 'fail'
  7265. if use_thread is True:
  7266. with self.proc_container.new(_("Exporting DXF")) as proc:
  7267. def job_thread_exc(app_obj):
  7268. ret_dxf_val = make_dxf()
  7269. if ret_dxf_val == 'fail':
  7270. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7271. return
  7272. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7273. else:
  7274. ret = make_dxf()
  7275. if ret == 'fail':
  7276. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7277. return
  7278. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7279. """
  7280. Adds a new Geometry Object to the projects and populates
  7281. it with shapes extracted from the SVG file.
  7282. :param plot: If True then the resulting object will be plotted on canvas
  7283. :param filename: Path to the SVG file.
  7284. :param geo_type: Type of FlatCAM object that will be created from SVG
  7285. :param outname: The name given to the resulting FlatCAM object
  7286. :return:
  7287. """
  7288. self.defaults.report_usage("import_svg()")
  7289. log.debug("App.import_svg()")
  7290. obj_type = ""
  7291. if geo_type is None or geo_type == "geometry":
  7292. obj_type = "geometry"
  7293. elif geo_type == "gerber":
  7294. obj_type = "gerber"
  7295. else:
  7296. self.inform.emit('[ERROR_NOTCL] %s' %
  7297. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7298. return
  7299. units = self.defaults['units'].upper()
  7300. def obj_init(geo_obj, app_obj):
  7301. geo_obj.import_svg(filename, obj_type, units=units)
  7302. geo_obj.multigeo = False
  7303. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7304. with self.proc_container.new(_("Importing SVG")) as proc:
  7305. # Object name
  7306. name = outname or filename.split('/')[-1].split('\\')[-1]
  7307. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7308. if ret == 'fail':
  7309. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7310. return 'fail'
  7311. # Register recent file
  7312. self.file_opened.emit("svg", filename)
  7313. # AppGUI feedback
  7314. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7315. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7316. """
  7317. Adds a new Geometry Object to the projects and populates
  7318. it with shapes extracted from the DXF file.
  7319. :param filename: Path to the DXF file.
  7320. :param geo_type: Type of FlatCAM object that will be created from DXF
  7321. :param outname: Name for the imported Geometry
  7322. :param plot: If True then the resulting object will be plotted on canvas
  7323. :return:
  7324. """
  7325. self.defaults.report_usage("import_dxf()")
  7326. obj_type = ""
  7327. if geo_type is None or geo_type == "geometry":
  7328. obj_type = "geometry"
  7329. elif geo_type == "gerber":
  7330. obj_type = geo_type
  7331. else:
  7332. self.inform.emit('[ERROR_NOTCL] %s' %
  7333. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7334. return
  7335. units = self.defaults['units'].upper()
  7336. def obj_init(geo_obj, app_obj):
  7337. geo_obj.import_dxf(filename, obj_type, units=units)
  7338. geo_obj.multigeo = False
  7339. with self.proc_container.new(_("Importing DXF")):
  7340. # Object name
  7341. name = outname or filename.split('/')[-1].split('\\')[-1]
  7342. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7343. if ret == 'fail':
  7344. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7345. return 'fail'
  7346. # Register recent file
  7347. self.file_opened.emit("dxf", filename)
  7348. # AppGUI feedback
  7349. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7350. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7351. """
  7352. Opens a Gerber file, parses it and creates a new object for
  7353. it in the program. Thread-safe.
  7354. :param outname: Name of the resulting object. None causes the
  7355. name to be that of the file. Str.
  7356. :param filename: Gerber file filename
  7357. :type filename: str
  7358. :param plot: boolean, to plot or not the resulting object
  7359. :param from_tcl: True if run from Tcl Shell
  7360. :return: None
  7361. """
  7362. # How the object should be initialized
  7363. def obj_init(gerber_obj, app_obj):
  7364. assert isinstance(gerber_obj, GerberObject), \
  7365. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7366. # Opening the file happens here
  7367. try:
  7368. gerber_obj.parse_file(filename)
  7369. except IOError:
  7370. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7371. return "fail"
  7372. except ParseError as err:
  7373. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7374. app_obj.log.error(str(err))
  7375. return "fail"
  7376. except Exception as e:
  7377. log.debug("App.open_gerber() --> %s" % str(e))
  7378. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7379. msg += traceback.format_exc()
  7380. app_obj.inform.emit(msg)
  7381. return "fail"
  7382. if gerber_obj.is_empty():
  7383. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7384. _("Object is not Gerber file or empty. Aborting object creation."))
  7385. return "fail"
  7386. App.log.debug("open_gerber()")
  7387. with self.proc_container.new(_("Opening Gerber")):
  7388. # Object name
  7389. name = outname or filename.split('/')[-1].split('\\')[-1]
  7390. # # ## Object creation # ##
  7391. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7392. if ret_val == 'fail':
  7393. if from_tcl:
  7394. filename = self.defaults['global_tcl_path'] + '/' + name
  7395. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7396. if ret_val == 'fail':
  7397. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7398. return 'fail'
  7399. # Register recent file
  7400. self.file_opened.emit("gerber", filename)
  7401. # AppGUI feedback
  7402. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7403. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7404. """
  7405. Opens an Excellon file, parses it and creates a new object for
  7406. it in the program. Thread-safe.
  7407. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7408. :param filename: Excellon file filename
  7409. :type filename: str
  7410. :param plot: boolean, to plot or not the resulting object
  7411. :param from_tcl: True if run from Tcl Shell
  7412. :return: None
  7413. """
  7414. App.log.debug("open_excellon()")
  7415. # How the object should be initialized
  7416. def obj_init(excellon_obj, app_obj):
  7417. try:
  7418. ret = excellon_obj.parse_file(filename=filename)
  7419. if ret == "fail":
  7420. log.debug("Excellon parsing failed.")
  7421. self.inform.emit('[ERROR_NOTCL] %s' %
  7422. _("This is not Excellon file."))
  7423. return "fail"
  7424. except IOError:
  7425. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7426. (_("Cannot open file"), filename))
  7427. log.debug("Could not open Excellon object.")
  7428. return "fail"
  7429. except Exception:
  7430. msg = '[ERROR_NOTCL] %s' % \
  7431. _("An internal error has occurred. See shell.\n")
  7432. msg += traceback.format_exc()
  7433. app_obj.inform.emit(msg)
  7434. return "fail"
  7435. ret = excellon_obj.create_geometry()
  7436. if ret == 'fail':
  7437. log.debug("Could not create geometry for Excellon object.")
  7438. return "fail"
  7439. for tool in excellon_obj.tools:
  7440. if excellon_obj.tools[tool]['solid_geometry']:
  7441. return
  7442. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7443. return "fail"
  7444. with self.proc_container.new(_("Opening Excellon.")):
  7445. # Object name
  7446. name = outname or filename.split('/')[-1].split('\\')[-1]
  7447. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7448. if ret_val == 'fail':
  7449. if from_tcl:
  7450. filename = self.defaults['global_tcl_path'] + '/' + name
  7451. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7452. if ret_val == 'fail':
  7453. self.inform.emit('[ERROR_NOTCL] %s' %
  7454. _('Open Excellon file failed. Probable not an Excellon file.'))
  7455. return
  7456. # Register recent file
  7457. self.file_opened.emit("excellon", filename)
  7458. # AppGUI feedback
  7459. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7460. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7461. """
  7462. Opens a G-gcode file, parses it and creates a new object for
  7463. it in the program. Thread-safe.
  7464. :param filename: G-code file filename
  7465. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7466. :param force_parsing:
  7467. :param plot: If True plot the object on canvas
  7468. :param from_tcl: True if run from Tcl Shell
  7469. :return: None
  7470. """
  7471. App.log.debug("open_gcode()")
  7472. # How the object should be initialized
  7473. def obj_init(job_obj, app_obj_):
  7474. """
  7475. :param job_obj: the resulting object
  7476. :type app_obj_: App
  7477. """
  7478. assert isinstance(app_obj_, App), \
  7479. "Initializer expected App, got %s" % type(app_obj_)
  7480. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7481. try:
  7482. f = open(filename)
  7483. gcode = f.read()
  7484. f.close()
  7485. except IOError:
  7486. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7487. return "fail"
  7488. job_obj.gcode = gcode
  7489. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7490. if gcode_ret == "fail":
  7491. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7492. return "fail"
  7493. job_obj.create_geometry()
  7494. with self.proc_container.new(_("Opening G-Code.")):
  7495. # Object name
  7496. name = outname or filename.split('/')[-1].split('\\')[-1]
  7497. # New object creation and file processing
  7498. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7499. if ret_val == 'fail':
  7500. if from_tcl:
  7501. filename = self.defaults['global_tcl_path'] + '/' + name
  7502. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7503. if ret_val == 'fail':
  7504. self.inform.emit('[ERROR_NOTCL] %s' %
  7505. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7506. "Try to load it from File menu.\n "
  7507. "Attempting to create a FlatCAM CNCJob Object from "
  7508. "G-Code file failed during processing"))
  7509. return "fail"
  7510. # Register recent file
  7511. self.file_opened.emit("cncjob", filename)
  7512. # AppGUI feedback
  7513. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7514. def open_hpgl2(self, filename, outname=None):
  7515. """
  7516. Opens a HPGL2 file, parses it and creates a new object for
  7517. it in the program. Thread-safe.
  7518. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7519. :param filename: HPGL2 file filename
  7520. :return: None
  7521. """
  7522. filename = filename
  7523. # How the object should be initialized
  7524. def obj_init(geo_obj, app_obj):
  7525. assert isinstance(geo_obj, GeometryObject), \
  7526. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7527. # Opening the file happens here
  7528. obj = HPGL2(self)
  7529. try:
  7530. HPGL2.parse_file(obj, filename)
  7531. except IOError:
  7532. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7533. return "fail"
  7534. except ParseError as err:
  7535. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7536. app_obj.log.error(str(err))
  7537. return "fail"
  7538. except Exception as e:
  7539. log.debug("App.open_hpgl2() --> %s" % str(e))
  7540. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7541. msg += traceback.format_exc()
  7542. app_obj.inform.emit(msg)
  7543. return "fail"
  7544. geo_obj.multigeo = True
  7545. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7546. geo_obj.tools = deepcopy(obj.tools)
  7547. geo_obj.source_file = deepcopy(obj.source_file)
  7548. del obj
  7549. if not geo_obj.solid_geometry:
  7550. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7551. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7552. return "fail"
  7553. App.log.debug("open_hpgl2()")
  7554. with self.proc_container.new(_("Opening HPGL2")):
  7555. # Object name
  7556. name = outname or filename.split('/')[-1].split('\\')[-1]
  7557. # # ## Object creation # ##
  7558. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7559. if ret == 'fail':
  7560. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7561. return 'fail'
  7562. # Register recent file
  7563. self.file_opened.emit("geometry", filename)
  7564. # AppGUI feedback
  7565. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7566. def open_script(self, filename, outname=None, silent=False):
  7567. """
  7568. Opens a Script file, parses it and creates a new object for
  7569. it in the program. Thread-safe.
  7570. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7571. :param filename: Script file filename
  7572. :param silent: If True there will be no messages printed to StatusBar
  7573. :return: None
  7574. """
  7575. def obj_init(script_obj, app_obj):
  7576. assert isinstance(script_obj, ScriptObject), \
  7577. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7578. if silent is False:
  7579. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7580. try:
  7581. script_obj.parse_file(filename)
  7582. except IOError:
  7583. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7584. return "fail"
  7585. except ParseError as err:
  7586. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7587. app_obj.log.error(str(err))
  7588. return "fail"
  7589. except Exception as e:
  7590. log.debug("App.open_script() -> %s" % str(e))
  7591. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7592. msg += traceback.format_exc()
  7593. app_obj.inform.emit(msg)
  7594. return "fail"
  7595. App.log.debug("open_script()")
  7596. with self.proc_container.new(_("Opening TCL Script...")):
  7597. # Object name
  7598. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7599. # Object creation
  7600. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7601. if ret_val == 'fail':
  7602. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7603. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7604. if ret_val == 'fail':
  7605. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7606. return 'fail'
  7607. # Register recent file
  7608. self.file_opened.emit("script", filename)
  7609. # AppGUI feedback
  7610. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7611. def open_config_file(self, filename, run_from_arg=None):
  7612. """
  7613. Loads a config file from the specified file.
  7614. :param filename: Name of the file from which to load.
  7615. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7616. :return: None
  7617. """
  7618. App.log.debug("Opening config file: " + filename)
  7619. if run_from_arg:
  7620. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7621. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7622. _("Opening FlatCAM Config file.")),
  7623. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7624. color=QtGui.QColor("gray"))
  7625. # # add the tab if it was closed
  7626. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7627. # # first clear previous text in text editor (if any)
  7628. # self.ui.text_editor_tab.code_editor.clear()
  7629. #
  7630. # # Switch plot_area to CNCJob tab
  7631. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7632. # close the Code editor if already open
  7633. if self.toggle_codeeditor:
  7634. self.on_toggle_code_editor()
  7635. self.on_toggle_code_editor()
  7636. try:
  7637. if filename:
  7638. f = QtCore.QFile(filename)
  7639. if f.open(QtCore.QIODevice.ReadOnly):
  7640. stream = QtCore.QTextStream(f)
  7641. code_edited = stream.readAll()
  7642. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7643. f.close()
  7644. except IOError:
  7645. App.log.error("Failed to open config file: %s" % filename)
  7646. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7647. (_("Failed to open config file"), filename))
  7648. return
  7649. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7650. """
  7651. Loads a project from the specified file.
  7652. 1) Loads and parses file
  7653. 2) Registers the file as recently opened.
  7654. 3) Calls on_file_new()
  7655. 4) Updates options
  7656. 5) Calls new_object() with the object's from_dict() as init method.
  7657. 6) Calls plot_all() if plot=True
  7658. :param filename: Name of the file from which to load.
  7659. :param run_from_arg: True if run for arguments
  7660. :param plot: If True plot all objects in the project
  7661. :param cli: Run from command line
  7662. :param from_tcl: True if run from Tcl Sehll
  7663. :return: None
  7664. """
  7665. App.log.debug("Opening project: " + filename)
  7666. # block autosaving while a project is loaded
  7667. self.block_autosave = True
  7668. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7669. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7670. if cli is None:
  7671. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7672. if run_from_arg:
  7673. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7674. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7675. _("Opening FlatCAM Project file.")),
  7676. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7677. color=QtGui.QColor("gray"))
  7678. # Open and parse an uncompressed Project file
  7679. try:
  7680. f = open(filename, 'r')
  7681. except IOError:
  7682. if from_tcl:
  7683. name = filename.split('/')[-1].split('\\')[-1]
  7684. filename = self.defaults['global_tcl_path'] + '/' + name
  7685. try:
  7686. f = open(filename, 'r')
  7687. except IOError:
  7688. log.error("Failed to open project file: %s" % filename)
  7689. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7690. return
  7691. else:
  7692. log.error("Failed to open project file: %s" % filename)
  7693. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7694. return
  7695. try:
  7696. d = json.load(f, object_hook=dict2obj)
  7697. except Exception as e:
  7698. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7699. (filename, str(e)))
  7700. f.close()
  7701. # Open and parse a compressed Project file
  7702. try:
  7703. with lzma.open(filename) as f:
  7704. file_content = f.read().decode('utf-8')
  7705. d = json.loads(file_content, object_hook=dict2obj)
  7706. except Exception as e:
  7707. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7708. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7709. return
  7710. # Clear the current project
  7711. # # NOT THREAD SAFE # ##
  7712. if run_from_arg is True:
  7713. pass
  7714. elif cli is True:
  7715. self.delete_selection_shape()
  7716. else:
  7717. self.on_file_new()
  7718. # Project options
  7719. self.options.update(d['options'])
  7720. self.project_filename = filename
  7721. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7722. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7723. if cli is None:
  7724. self.set_screen_units(self.options["units"])
  7725. # Re create objects
  7726. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7727. for obj in d['objs']:
  7728. try:
  7729. def obj_init(obj_inst, app_inst):
  7730. obj_inst.from_dict(obj)
  7731. App.log.debug("Recreating from opened project an %s object: %s" %
  7732. (obj['kind'].capitalize(), obj['options']['name']))
  7733. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7734. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7735. if cli is None:
  7736. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7737. obj['kind'].upper(),
  7738. obj['options']['name']
  7739. )
  7740. )
  7741. self.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7742. except Exception as e:
  7743. print('App.open_project() --> ' + str(e))
  7744. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7745. self.should_we_save = False
  7746. self.file_opened.emit("project", filename)
  7747. # restore autosaving after a project was loaded
  7748. self.block_autosave = False
  7749. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7750. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7751. if cli is None:
  7752. self.set_ui_title(name=self.project_filename)
  7753. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7754. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7755. """
  7756. Re-generates all plots from all objects.
  7757. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7758. :param muted: if True don't print messages
  7759. :param use_thread: if True will use threading for plotting the objects
  7760. :return: None
  7761. """
  7762. self.log.debug("Plot_all()")
  7763. if muted is not True:
  7764. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7765. for plot_obj in self.collection.get_list():
  7766. def worker_task(obj):
  7767. with self.proc_container.new("Plotting"):
  7768. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7769. if fit_view is True:
  7770. self.object_plotted.emit(obj)
  7771. if use_thread is True:
  7772. # Send to worker
  7773. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7774. else:
  7775. worker_task(plot_obj)
  7776. def register_folder(self, filename):
  7777. """
  7778. Register the last folder used by the app to open something
  7779. :param filename: the last folder is extracted from the filename
  7780. :return: None
  7781. """
  7782. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7783. def register_save_folder(self, filename):
  7784. """
  7785. Register the last folder used by the app to save something
  7786. :param filename: the last folder is extracted from the filename
  7787. :return: None
  7788. """
  7789. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7790. # def set_progress_bar(self, percentage, text=""):
  7791. # """
  7792. # Set a progress bar to a value (percentage)
  7793. #
  7794. # :param percentage: Value set to the progressbar
  7795. # :param text: Not used
  7796. # :return: None
  7797. # """
  7798. # self.ui.progress_bar.setValue(int(percentage))
  7799. def setup_recent_items(self):
  7800. """
  7801. Setup a dictionary with the recent files accessed, organized by type
  7802. :return:
  7803. """
  7804. icons = {
  7805. "gerber": self.resource_location + "/flatcam_icon16.png",
  7806. "excellon": self.resource_location + "/drill16.png",
  7807. 'geometry': self.resource_location + "/geometry16.png",
  7808. "cncjob": self.resource_location + "/cnc16.png",
  7809. "script": self.resource_location + "/script_new24.png",
  7810. "document": self.resource_location + "/notes16_1.png",
  7811. "project": self.resource_location + "/project16.png",
  7812. "svg": self.resource_location + "/geometry16.png",
  7813. "dxf": self.resource_location + "/dxf16.png",
  7814. "pdf": self.resource_location + "/pdf32.png",
  7815. "image": self.resource_location + "/image16.png"
  7816. }
  7817. try:
  7818. image_opener = self.image_tool.import_image
  7819. except AttributeError:
  7820. image_opener = None
  7821. openers = {
  7822. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7823. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7824. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7825. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7826. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7827. "document": None,
  7828. 'project': self.open_project,
  7829. 'svg': self.import_svg,
  7830. 'dxf': self.import_dxf,
  7831. 'image': image_opener,
  7832. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7833. }
  7834. # Open recent file for files
  7835. try:
  7836. f = open(self.data_path + '/recent.json')
  7837. except IOError:
  7838. App.log.error("Failed to load recent item list.")
  7839. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7840. return
  7841. try:
  7842. self.recent = json.load(f)
  7843. except json.errors.JSONDecodeError:
  7844. App.log.error("Failed to parse recent item list.")
  7845. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7846. f.close()
  7847. return
  7848. f.close()
  7849. # Open recent file for projects
  7850. try:
  7851. fp = open(self.data_path + '/recent_projects.json')
  7852. except IOError:
  7853. App.log.error("Failed to load recent project item list.")
  7854. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7855. return
  7856. try:
  7857. self.recent_projects = json.load(fp)
  7858. except json.errors.JSONDecodeError:
  7859. App.log.error("Failed to parse recent project item list.")
  7860. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7861. fp.close()
  7862. return
  7863. fp.close()
  7864. # Closure needed to create callbacks in a loop.
  7865. # Otherwise late binding occurs.
  7866. def make_callback(func, fname):
  7867. def opener():
  7868. func(fname)
  7869. return opener
  7870. def reset_recent_files():
  7871. # Reset menu
  7872. self.ui.recent.clear()
  7873. self.recent = []
  7874. try:
  7875. ff = open(self.data_path + '/recent.json', 'w')
  7876. except IOError:
  7877. App.log.error("Failed to open recent items file for writing.")
  7878. return
  7879. json.dump(self.recent, ff)
  7880. def reset_recent_projects():
  7881. # Reset menu
  7882. self.ui.recent_projects.clear()
  7883. self.recent_projects = []
  7884. try:
  7885. frp = open(self.data_path + '/recent_projects.json', 'w')
  7886. except IOError:
  7887. App.log.error("Failed to open recent projects items file for writing.")
  7888. return
  7889. json.dump(self.recent, frp)
  7890. # Reset menu
  7891. self.ui.recent.clear()
  7892. self.ui.recent_projects.clear()
  7893. # Create menu items for projects
  7894. for recent in self.recent_projects:
  7895. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7896. if recent['kind'] == 'project':
  7897. try:
  7898. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7899. # Attach callback
  7900. o = make_callback(openers[recent["kind"]], recent['filename'])
  7901. action.triggered.connect(o)
  7902. self.ui.recent_projects.addAction(action)
  7903. except KeyError:
  7904. App.log.error("Unsupported file type: %s" % recent["kind"])
  7905. # Last action in Recent Files menu is one that Clear the content
  7906. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7907. (_("Clear Recent projects")), self)
  7908. clear_action_proj.triggered.connect(reset_recent_projects)
  7909. self.ui.recent_projects.addSeparator()
  7910. self.ui.recent_projects.addAction(clear_action_proj)
  7911. # Create menu items for files
  7912. for recent in self.recent:
  7913. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7914. if recent['kind'] != 'project':
  7915. try:
  7916. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7917. # Attach callback
  7918. o = make_callback(openers[recent["kind"]], recent['filename'])
  7919. action.triggered.connect(o)
  7920. self.ui.recent.addAction(action)
  7921. except KeyError:
  7922. App.log.error("Unsupported file type: %s" % recent["kind"])
  7923. # Last action in Recent Files menu is one that Clear the content
  7924. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7925. (_("Clear Recent files")), self)
  7926. clear_action.triggered.connect(reset_recent_files)
  7927. self.ui.recent.addSeparator()
  7928. self.ui.recent.addAction(clear_action)
  7929. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7930. # self.ui.menufilerecent.set_submenu(recent_menu)
  7931. # recent_menu.show_all()
  7932. # self.ui.recent.show()
  7933. self.log.debug("Recent items list has been populated.")
  7934. def setup_component_editor(self):
  7935. """
  7936. Default text for the Selected tab when is not taken by the Object UI.
  7937. :return:
  7938. """
  7939. # label = QtWidgets.QLabel("Choose an item from Project")
  7940. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7941. sel_title = QtWidgets.QTextEdit(
  7942. _('<b>Shortcut Key List</b>'))
  7943. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7944. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7945. f_settings = QSettings("Open Source", "FlatCAM")
  7946. if f_settings.contains("notebook_font_size"):
  7947. fsize = f_settings.value('notebook_font_size', type=int)
  7948. else:
  7949. fsize = 12
  7950. tsize = fsize + int(fsize / 2)
  7951. # selected_text = (_('''
  7952. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7953. # </p>
  7954. #
  7955. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7956. # The normal flow when working in FlatCAM is the following:</span></p>
  7957. #
  7958. # <ol>
  7959. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7960. # file into
  7961. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7962. # even dragging and dropping the files on the AppGUI.<br />
  7963. # <br />
  7964. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7965. # drop of the
  7966. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  7967. # &nbsp;</li>
  7968. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7969. # and then
  7970. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7971. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7972. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7973. # <br />
  7974. # If the selection of the object is done on the canvas by single click instead, and the
  7975. # <strong>SELECTED TAB</strong>
  7976. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7977. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7978. # it even if it was out of focus.<br />
  7979. # <br />
  7980. # You can change the parameters in this screen and the flow direction is like this:<br />
  7981. # <br />
  7982. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7983. # <strong> Geometry Object
  7984. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7985. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7986. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7987. # </ol>
  7988. #
  7989. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7990. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7991. # <strong>F3</strong>.</span></p>
  7992. #
  7993. # ''').format(fsize=fsize, tsize=tsize))
  7994. selected_text = '''
  7995. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7996. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7997. {s1}</span></p>
  7998. <ol>
  7999. <li><span style="font-size:{fsize}px">{s2}<br />
  8000. <br />
  8001. {s3}</span><br />
  8002. &nbsp;</li>
  8003. <li><span style="font-size:{fsize}px">{s4}<br />
  8004. &nbsp;</li>
  8005. <br />
  8006. <li><span style="font-size:{fsize}px">{s5}<br />
  8007. &nbsp;</li>
  8008. <br />
  8009. <li><span style="font-size:{fsize}px">{s6}<br />
  8010. <br />
  8011. {s7}</span></li>
  8012. </ol>
  8013. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8014. '''.format(
  8015. title=_("Selected Tab - Choose an Item from Project Tab"),
  8016. subtitle=_("Details"),
  8017. s1=_("The normal flow when working in FlatCAM is the following:"),
  8018. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8019. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8020. "files on the AppGUI."),
  8021. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8022. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  8023. "actions offered within the app."),
  8024. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8025. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8026. "SELECTED TAB will be updated with the object properties according to its kind: "
  8027. "Gerber, Excellon, Geometry or CNCJob object."),
  8028. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8029. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8030. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8031. "the SELECTED TAB and populate it even if it was out of focus."),
  8032. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8033. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8034. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8035. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8036. "(again, done in SELECTED TAB) --> Save GCode."),
  8037. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8038. "or through its own key shortcut: <b>F3</b>."),
  8039. tsize=tsize,
  8040. fsize=fsize
  8041. )
  8042. sel_title.setText(selected_text)
  8043. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8044. self.ui.selected_scroll_area.setWidget(sel_title)
  8045. def setup_obj_classes(self):
  8046. """
  8047. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8048. class.
  8049. :return: None
  8050. """
  8051. FlatCAMObj.app = self
  8052. ObjectCollection.app = self
  8053. Gerber.app = self
  8054. Excellon.app = self
  8055. Geometry.app = self
  8056. CNCjob.app = self
  8057. FCProcess.app = self
  8058. FCProcessContainer.app = self
  8059. OptionsGroupUI.app = self
  8060. def version_check(self):
  8061. """
  8062. Checks for the latest version of the program. Alerts the
  8063. user if theirs is outdated. This method is meant to be run
  8064. in a separate thread.
  8065. :return: None
  8066. """
  8067. self.log.debug("version_check()")
  8068. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8069. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8070. App.version_url,
  8071. str(self.defaults['global_serial']),
  8072. str(self.version),
  8073. str(self.os),
  8074. urllib.parse.urlencode(self.defaults["global_stats"])
  8075. )
  8076. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8077. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8078. # urllib.parse.urlencode(self.defaults["global_stats"])
  8079. else:
  8080. # no_stats dict; just so it won't break things on website
  8081. no_ststs_dict = {}
  8082. no_ststs_dict["global_ststs"] = {}
  8083. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8084. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8085. App.log.debug("Checking for updates @ %s" % full_url)
  8086. # ## Get the data
  8087. try:
  8088. f = urllib.request.urlopen(full_url)
  8089. except Exception:
  8090. # App.log.warning("Failed checking for latest version. Could not connect.")
  8091. self.log.warning("Failed checking for latest version. Could not connect.")
  8092. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8093. return
  8094. try:
  8095. data = json.load(f)
  8096. except Exception as e:
  8097. App.log.error("Could not parse information about latest version.")
  8098. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8099. App.log.debug("json.load(): %s" % str(e))
  8100. f.close()
  8101. return
  8102. f.close()
  8103. # ## Latest version?
  8104. if self.version >= data["version"]:
  8105. App.log.debug("FlatCAM is up to date!")
  8106. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8107. return
  8108. App.log.debug("Newer version available.")
  8109. self.message.emit(
  8110. _("Newer Version Available"),
  8111. '%s<br><br>><b>%s</b><br>%s' % (
  8112. _("There is a newer version of FlatCAM available for download:"),
  8113. str(data["name"]),
  8114. str(data["message"])
  8115. ),
  8116. _("info")
  8117. )
  8118. def on_plotcanvas_setup(self, container=None):
  8119. """
  8120. This is doing the setup for the plot area (canvas).
  8121. :param container: QT Widget where to install the canvas
  8122. :return: None
  8123. """
  8124. if container:
  8125. plot_container = container
  8126. else:
  8127. plot_container = self.ui.right_layout
  8128. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8129. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8130. self.is_legacy = True
  8131. self.defaults["global_graphic_engine"] = "2D"
  8132. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8133. else:
  8134. try:
  8135. self.plotcanvas = PlotCanvas(plot_container, self)
  8136. except Exception as er:
  8137. msg_txt = traceback.format_exc()
  8138. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8139. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8140. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8141. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8142. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8143. msg += msg_txt
  8144. self.inform.emit(msg)
  8145. return 'fail'
  8146. # So it can receive key presses
  8147. self.plotcanvas.native.setFocus()
  8148. if self.is_legacy is False:
  8149. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8150. # Set the mouse button for panning
  8151. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8152. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8153. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8154. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8155. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8156. # Keys over plot enabled
  8157. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8158. if self.defaults['global_cursor_type'] == 'small':
  8159. self.app_cursor = self.plotcanvas.new_cursor()
  8160. else:
  8161. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8162. if self.ui.grid_snap_btn.isChecked():
  8163. self.app_cursor.enabled = True
  8164. else:
  8165. self.app_cursor.enabled = False
  8166. if self.is_legacy is False:
  8167. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8168. else:
  8169. # will use the default Matplotlib axes
  8170. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8171. def on_zoom_fit(self, event):
  8172. """
  8173. Callback for zoom-fit request. This can be either from the corresponding
  8174. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8175. with axes limits from the geometry bounds of all objects.
  8176. :param event: Ignored.
  8177. :return: None
  8178. """
  8179. if self.is_legacy is False:
  8180. self.plotcanvas.fit_view()
  8181. else:
  8182. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8183. width = xmax - xmin
  8184. height = ymax - ymin
  8185. xmin -= 0.05 * width
  8186. xmax += 0.05 * width
  8187. ymin -= 0.05 * height
  8188. ymax += 0.05 * height
  8189. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8190. def on_zoom_in(self):
  8191. """
  8192. Callback for zoom-in request.
  8193. :return:
  8194. """
  8195. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8196. def on_zoom_out(self):
  8197. """
  8198. Callback for zoom-out request.
  8199. :return:
  8200. """
  8201. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8202. def disable_all_plots(self):
  8203. self.defaults.report_usage("disable_all_plots()")
  8204. self.disable_plots(self.collection.get_list())
  8205. self.inform.emit('[success] %s' %
  8206. _("All plots disabled."))
  8207. def disable_other_plots(self):
  8208. self.defaults.report_usage("disable_other_plots()")
  8209. self.disable_plots(self.collection.get_non_selected())
  8210. self.inform.emit('[success] %s' %
  8211. _("All non selected plots disabled."))
  8212. def enable_all_plots(self):
  8213. self.defaults.report_usage("enable_all_plots()")
  8214. self.enable_plots(self.collection.get_list())
  8215. self.inform.emit('[success] %s' %
  8216. _("All plots enabled."))
  8217. def on_enable_sel_plots(self):
  8218. log.debug("App.on_enable_sel_plot()")
  8219. object_list = self.collection.get_selected()
  8220. self.enable_plots(objects=object_list)
  8221. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8222. def on_disable_sel_plots(self):
  8223. log.debug("App.on_disable_sel_plot()")
  8224. # self.inform.emit(_("Disabling plots ..."))
  8225. object_list = self.collection.get_selected()
  8226. self.disable_plots(objects=object_list)
  8227. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8228. def enable_plots(self, objects):
  8229. """
  8230. Enable plots
  8231. :param objects: list of AppObjects to be enabled
  8232. :return:
  8233. """
  8234. log.debug("Enabling plots ...")
  8235. # self.inform.emit(_("Working ..."))
  8236. for obj in objects:
  8237. if obj.options['plot'] is False:
  8238. obj.options.set_change_callback(lambda x: None)
  8239. obj.options['plot'] = True
  8240. try:
  8241. # only the Gerber obj has on_plot_cb_click() method
  8242. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8243. # disable this cb while disconnected,
  8244. # in case the operation takes time the user is not allowed to change it
  8245. obj.ui.plot_cb.setDisabled(True)
  8246. except AttributeError:
  8247. pass
  8248. obj.set_form_item("plot")
  8249. try:
  8250. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8251. obj.ui.plot_cb.setDisabled(False)
  8252. except AttributeError:
  8253. pass
  8254. obj.options.set_change_callback(obj.on_options_change)
  8255. def worker_task(objs):
  8256. with self.proc_container.new(_("Enabling plots ...")):
  8257. for plot_obj in objs:
  8258. # obj.options['plot'] = True
  8259. if isinstance(plot_obj, CNCJobObject):
  8260. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8261. else:
  8262. plot_obj.plot(visible=True)
  8263. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8264. # self.plots_updated.emit()
  8265. def disable_plots(self, objects):
  8266. """
  8267. Disables plots
  8268. :param objects: list of AppObjects to be disabled
  8269. :return:
  8270. """
  8271. # if no objects selected then do nothing
  8272. if not self.collection.get_selected():
  8273. return
  8274. log.debug("Disabling plots ...")
  8275. # self.inform.emit(_("Working ..."))
  8276. for obj in objects:
  8277. if obj.options['plot'] is True:
  8278. obj.options.set_change_callback(lambda x: None)
  8279. obj.options['plot'] = False
  8280. try:
  8281. # only the Gerber obj has on_plot_cb_click() method
  8282. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8283. obj.ui.plot_cb.setDisabled(True)
  8284. except AttributeError:
  8285. pass
  8286. obj.set_form_item("plot")
  8287. try:
  8288. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8289. obj.ui.plot_cb.setDisabled(False)
  8290. except AttributeError:
  8291. pass
  8292. obj.options.set_change_callback(obj.on_options_change)
  8293. try:
  8294. self.delete_selection_shape()
  8295. except Exception as e:
  8296. log.debug("App.disable_plots() --> %s" % str(e))
  8297. # self.plots_updated.emit()
  8298. def worker_task(objs):
  8299. with self.proc_container.new(_("Disabling plots ...")):
  8300. for plot_obj in objs:
  8301. # obj.options['plot'] = True
  8302. if isinstance(plot_obj, CNCJobObject):
  8303. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8304. else:
  8305. plot_obj.plot(visible=False)
  8306. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8307. def toggle_plots(self, objects):
  8308. """
  8309. Toggle plots visibility
  8310. :param objects: list of AppObjects for which to be toggled the visibility
  8311. :return: None
  8312. """
  8313. # if no objects selected then do nothing
  8314. if not self.collection.get_selected():
  8315. return
  8316. log.debug("Toggling plots ...")
  8317. self.inform.emit(_("Working ..."))
  8318. for obj in objects:
  8319. if obj.options['plot'] is False:
  8320. obj.options['plot'] = True
  8321. else:
  8322. obj.options['plot'] = False
  8323. self.plots_updated.emit()
  8324. def clear_plots(self):
  8325. """
  8326. Clear the plots
  8327. :return: None
  8328. """
  8329. objects = self.collection.get_list()
  8330. for obj in objects:
  8331. obj.clear(obj == objects[-1])
  8332. # Clear pool to free memory
  8333. self.clear_pool()
  8334. def on_set_color_action_triggered(self):
  8335. """
  8336. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8337. :return:
  8338. """
  8339. new_color = self.defaults['gerber_plot_fill']
  8340. clicked_action = self.sender()
  8341. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8342. act_name = clicked_action.text()
  8343. sel_obj_list = self.collection.get_selected()
  8344. if not sel_obj_list:
  8345. return
  8346. # a default value, I just chose this one
  8347. alpha_level = 'BF'
  8348. for sel_obj in sel_obj_list:
  8349. if sel_obj.kind == 'excellon':
  8350. alpha_level = str(hex(
  8351. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8352. elif sel_obj.kind == 'gerber':
  8353. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8354. elif sel_obj.kind == 'geometry':
  8355. alpha_level = 'FF'
  8356. else:
  8357. log.debug(
  8358. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8359. continue
  8360. sel_obj.alpha_level = alpha_level
  8361. if act_name == _('Red'):
  8362. new_color = '#FF0000' + alpha_level
  8363. if act_name == _('Blue'):
  8364. new_color = '#0000FF' + alpha_level
  8365. if act_name == _('Yellow'):
  8366. new_color = '#FFDF00' + alpha_level
  8367. if act_name == _('Green'):
  8368. new_color = '#00FF00' + alpha_level
  8369. if act_name == _('Purple'):
  8370. new_color = '#FF00FF' + alpha_level
  8371. if act_name == _('Brown'):
  8372. new_color = '#A52A2A' + alpha_level
  8373. if act_name == _('White'):
  8374. new_color = '#FFFFFF' + alpha_level
  8375. if act_name == _('Black'):
  8376. new_color = '#000000' + alpha_level
  8377. if act_name == _('Custom'):
  8378. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8379. c_dialog = QtWidgets.QColorDialog()
  8380. plot_fill_color = c_dialog.getColor(initial=new_color)
  8381. if plot_fill_color.isValid() is False:
  8382. return
  8383. new_color = str(plot_fill_color.name()) + alpha_level
  8384. if act_name == _("Default"):
  8385. for sel_obj in sel_obj_list:
  8386. if sel_obj.kind == 'excellon':
  8387. new_color = self.defaults['excellon_plot_fill']
  8388. new_line_color = self.defaults['excellon_plot_line']
  8389. elif sel_obj.kind == 'gerber':
  8390. new_color = self.defaults['gerber_plot_fill']
  8391. new_line_color = self.defaults['gerber_plot_line']
  8392. elif sel_obj.kind == 'geometry':
  8393. new_color = self.defaults['geometry_plot_line']
  8394. new_line_color = self.defaults['geometry_plot_line']
  8395. else:
  8396. log.debug(
  8397. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8398. continue
  8399. sel_obj.fill_color = new_color
  8400. sel_obj.outline_color = new_line_color
  8401. sel_obj.shapes.redraw(
  8402. update_colors=(new_color, new_line_color)
  8403. )
  8404. return
  8405. if act_name == _("Opacity"):
  8406. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8407. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8408. if ok_button:
  8409. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8410. for sel_obj in sel_obj_list:
  8411. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8412. sel_obj.shapes.redraw(
  8413. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8414. )
  8415. return
  8416. new_line_color = color_variant(new_color[:7], 0.7)
  8417. if act_name == _("White"):
  8418. new_line_color = color_variant("#dedede", 0.7)
  8419. for sel_obj in sel_obj_list:
  8420. sel_obj.fill_color = new_color
  8421. sel_obj.outline_color = new_line_color
  8422. sel_obj.shapes.redraw(
  8423. update_colors=(new_color, new_line_color)
  8424. )
  8425. def generate_cnc_job(self, objects):
  8426. """
  8427. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8428. :param objects: Selected objects in the Project Tab
  8429. :return:
  8430. """
  8431. self.defaults.report_usage("generate_cnc_job()")
  8432. # for obj in objects:
  8433. # obj.generatecncjob()
  8434. for obj in objects:
  8435. obj.on_generatecnc_button_click()
  8436. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8437. """
  8438. Saves the current project to the specified file.
  8439. :param filename: Name of the file in which to save.
  8440. :type filename: str
  8441. :param quit_action: if the project saving will be followed by an app quit; boolean
  8442. :param silent: if True will not display status messages
  8443. :param from_tcl True is run from Tcl Shell
  8444. :return: None
  8445. """
  8446. self.log.debug("save_project()")
  8447. self.save_in_progress = True
  8448. with self.proc_container.new(_("Saving FlatCAM Project")):
  8449. # Capture the latest changes
  8450. # Current object
  8451. try:
  8452. current_object = self.collection.get_active()
  8453. if current_object:
  8454. current_object.read_form()
  8455. except Exception as e:
  8456. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8457. pass
  8458. # Serialize the whole project
  8459. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8460. "options": self.options,
  8461. "version": self.version}
  8462. if self.defaults["global_save_compressed"] is True:
  8463. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8464. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8465. # # Write
  8466. f.write(g)
  8467. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8468. else:
  8469. # Open file
  8470. try:
  8471. f = open(filename, 'w')
  8472. except IOError:
  8473. App.log.error("Failed to open file for saving: %s", filename)
  8474. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8475. return
  8476. # Write
  8477. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8478. f.close()
  8479. # verification of the saved project
  8480. # Open and parse
  8481. try:
  8482. saved_f = open(filename, 'r')
  8483. except IOError:
  8484. if silent is False:
  8485. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8486. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8487. return
  8488. try:
  8489. saved_d = json.load(saved_f, object_hook=dict2obj)
  8490. except Exception:
  8491. if silent is False:
  8492. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8493. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8494. f.close()
  8495. return
  8496. saved_f.close()
  8497. if silent is False:
  8498. if 'version' in saved_d:
  8499. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8500. else:
  8501. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8502. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8503. tb_settings = QSettings("Open Source", "FlatCAM")
  8504. lock_state = self.ui.lock_action.isChecked()
  8505. tb_settings.setValue('toolbar_lock', lock_state)
  8506. # This will write the setting to the platform specific storage.
  8507. del tb_settings
  8508. # if quit:
  8509. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8510. # t.start()
  8511. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8512. def start_delayed_quit(self, delay, filename, should_quit=None):
  8513. """
  8514. :param delay: period of checking if project file size is more than zero; in seconds
  8515. :param filename: the name of the project file to be checked periodically for size more than zero
  8516. :param should_quit: if the task finished will be followed by an app quit; boolean
  8517. :return:
  8518. """
  8519. to_quit = should_quit
  8520. self.save_timer = QtCore.QTimer()
  8521. self.save_timer.setInterval(delay)
  8522. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8523. self.save_timer.start()
  8524. def check_project_file_size(self, filename, should_quit=None):
  8525. """
  8526. :param filename: the name of the project file to be checked periodically for size more than zero
  8527. :param should_quit: will quit the app if True; boolean
  8528. :return:
  8529. """
  8530. try:
  8531. if os.stat(filename).st_size > 0:
  8532. self.save_in_progress = False
  8533. self.save_timer.stop()
  8534. if should_quit:
  8535. self.app_quit.emit()
  8536. except Exception:
  8537. traceback.print_exc()
  8538. def save_project_auto(self):
  8539. """
  8540. Called periodically to save the project.
  8541. 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
  8542. # progress.
  8543. :return:
  8544. """
  8545. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8546. self.on_file_saveproject()
  8547. def save_project_auto_update(self):
  8548. """
  8549. Update the auto save time interval value.
  8550. :return:
  8551. """
  8552. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8553. try:
  8554. if self.autosave_timer.isActive():
  8555. self.autosave_timer.stop()
  8556. except Exception:
  8557. pass
  8558. if self.defaults['global_autosave'] is True:
  8559. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8560. self.autosave_timer.start()
  8561. def on_options_app2project(self):
  8562. """
  8563. Callback for Options->Transfer Options->App=>Project. Copies options
  8564. from application defaults to project defaults.
  8565. :return: None
  8566. """
  8567. self.defaults.report_usage("on_options_app2project")
  8568. self.preferencesUiManager.defaults_read_form()
  8569. self.options.update(self.defaults)
  8570. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8571. """
  8572. Shows a message on the FlatCAM Shell
  8573. :param msg: Message to display.
  8574. :param show: Opens the shell.
  8575. :param error: Shows the message as an error.
  8576. :param warning: Shows the message as an warning.
  8577. :param success: Shows the message as an success.
  8578. :param selected: Indicate that something was selected on canvas
  8579. :return: None
  8580. """
  8581. if show:
  8582. self.ui.shell_dock.show()
  8583. try:
  8584. if error:
  8585. self.shell.append_error(msg + "\n")
  8586. elif warning:
  8587. self.shell.append_warning(msg + "\n")
  8588. elif success:
  8589. self.shell.append_success(msg + "\n")
  8590. elif selected:
  8591. self.shell.append_selected(msg + "\n")
  8592. else:
  8593. self.shell.append_output(msg + "\n")
  8594. except AttributeError:
  8595. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8596. class ArgsThread(QtCore.QObject):
  8597. open_signal = pyqtSignal(list)
  8598. start = pyqtSignal()
  8599. stop = pyqtSignal()
  8600. if sys.platform == 'win32':
  8601. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8602. else:
  8603. address = ('/tmp/testipc', 'AF_UNIX')
  8604. def __init__(self):
  8605. super(ArgsThread, self).__init__()
  8606. self.listener = None
  8607. self.thread_exit = False
  8608. self.start.connect(self.run)
  8609. self.stop.connect(self.close_listener)
  8610. def my_loop(self, address):
  8611. try:
  8612. self.listener = Listener(*address)
  8613. while self.thread_exit is False:
  8614. conn = self.listener.accept()
  8615. self.serve(conn)
  8616. except socket.error:
  8617. try:
  8618. conn = Client(*address)
  8619. conn.send(sys.argv)
  8620. conn.send('close')
  8621. # close the current instance only if there are args
  8622. if len(sys.argv) > 1:
  8623. try:
  8624. self.listener.close()
  8625. except Exception:
  8626. pass
  8627. sys.exit()
  8628. except ConnectionRefusedError:
  8629. if sys.platform == 'win32':
  8630. pass
  8631. else:
  8632. os.system('rm /tmp/testipc')
  8633. self.listener = Listener(*address)
  8634. while True:
  8635. conn = self.listener.accept()
  8636. self.serve(conn)
  8637. def serve(self, conn):
  8638. while self.thread_exit is False:
  8639. msg = conn.recv()
  8640. if msg == 'close':
  8641. break
  8642. self.open_signal.emit(msg)
  8643. conn.close()
  8644. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8645. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8646. @pyqtSlot()
  8647. def run(self):
  8648. self.my_loop(self.address)
  8649. @pyqtSlot()
  8650. def close_listener(self):
  8651. self.thread_exit = True
  8652. self.listener.close()
  8653. # end of file