app_Main.py 471 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493
  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. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from shapely.ops import unary_union
  23. from io import StringIO
  24. from reportlab.graphics import renderPDF
  25. from reportlab.pdfgen import canvas
  26. from reportlab.lib.units import inch, mm
  27. from reportlab.lib.pagesizes import landscape, portrait
  28. from svglib.svglib import svg2rlg
  29. import gc
  30. from xml.dom.minidom import parseString as parse_xml_string
  31. from multiprocessing.connection import Listener, Client
  32. from multiprocessing import Pool
  33. import socket
  34. # ####################################################################################################################
  35. # ################################### Imports part of FlatCAM #############################################
  36. # ####################################################################################################################
  37. # Various
  38. from Common import LoudDict
  39. from Common import color_variant
  40. from Common import ExclusionAreas
  41. from Bookmark import BookmarkManager
  42. from appDatabase import ToolsDB2
  43. from vispy.gloo.util import _screenshot
  44. from vispy.io import write_png
  45. # FlatCAM defaults (preferences)
  46. from defaults import FlatCAMDefaults
  47. # FlatCAM Objects
  48. from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
  49. from appGUI.preferences.PreferencesUIManager import PreferencesUIManager
  50. from appObjects.ObjectCollection import *
  51. from appObjects.FlatCAMObj import FlatCAMObj
  52. from appObjects.AppObject import AppObject
  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.AppGeoEditor import AppGeoEditor
  66. from appEditors.AppExcEditor import AppExcEditor
  67. from appEditors.AppGerberEditor import AppGerberEditor
  68. from appEditors.AppTextEditor import AppTextEditor
  69. from appEditors.appGCodeEditor import AppGCodeEditor
  70. from appParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from appProcess import *
  73. from appWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from appTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import appTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI and all other classes used by the program.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = "Unstable Version"
  138. # version = 8.994
  139. version_date = "2020/07/05"
  140. beta = True
  141. engine = '3D'
  142. # current date now
  143. date = str(datetime.today()).rpartition('.')[0]
  144. date = ''.join(c for c in date if c not in ':-')
  145. date = date.replace(' ', '_')
  146. # ###############################################################################################################
  147. # ############################################ URLS's ###########################################################
  148. # ###############################################################################################################
  149. # URL for update checks and statistics
  150. version_url = "http://flatcam.org/version"
  151. # App URL
  152. app_url = "http://flatcam.org"
  153. # Manual URL
  154. manual_url = "http://flatcam.org/manual/index.html"
  155. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  156. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  157. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  158. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  159. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  160. # this variable will hold the project status
  161. # if True it will mean that the project was modified and not saved
  162. should_we_save = False
  163. # flag is True if saving action has been triggered
  164. save_in_progress = False
  165. # ###############################################################################################################
  166. # ####################################### APP Signals ######################################################
  167. # ###############################################################################################################
  168. # Inform the user
  169. # Handled by: App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal([str], [str, bool])
  171. # Handled by: App.info_shell() --> Print on the shell
  172. inform_shell = QtCore.pyqtSignal(str)
  173. app_quit = QtCore.pyqtSignal()
  174. # General purpose background task
  175. worker_task = QtCore.pyqtSignal(dict)
  176. # File opened
  177. # Handled by:
  178. # * register_folder()
  179. # * register_recent()
  180. # Note: Setting the parameters to unicode does not seem
  181. # to have an effect. Then are received as Qstring
  182. # anyway.
  183. # File type and filename
  184. file_opened = QtCore.pyqtSignal(str, str)
  185. # File type and filename
  186. file_saved = QtCore.pyqtSignal(str, str)
  187. # Percentage of progress
  188. progress = QtCore.pyqtSignal(int)
  189. # Emitted when a new object has been added or deleted from/to the collection
  190. object_status_changed = QtCore.pyqtSignal(object, str, str)
  191. message = QtCore.pyqtSignal(str, str, str)
  192. # Emmited when shell command is finished(one command only)
  193. shell_command_finished = QtCore.pyqtSignal(object)
  194. # Emitted when multiprocess pool has been recreated
  195. pool_recreated = QtCore.pyqtSignal(object)
  196. # Emitted when an unhandled exception happens
  197. # in the worker task.
  198. thread_exception = QtCore.pyqtSignal(object)
  199. # used to signal that there are arguments for the app
  200. args_at_startup = QtCore.pyqtSignal(list)
  201. # a reusable signal to replot a list of objects
  202. # should be disconnected after use so it can be reused
  203. replot_signal = pyqtSignal(list)
  204. # signal emitted when jumping
  205. jump_signal = pyqtSignal(tuple)
  206. # signal emitted when jumping
  207. locate_signal = pyqtSignal(tuple, str)
  208. # close app signal
  209. close_app_signal = pyqtSignal()
  210. # will perform the cleanup operation after a Graceful Exit
  211. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  212. # graphic residues behind
  213. cleanup = pyqtSignal()
  214. def __init__(self, user_defaults=True):
  215. """
  216. Starts the application.
  217. :return: app
  218. :rtype: App
  219. """
  220. super().__init__()
  221. App.log.info("FlatCAM Starting...")
  222. # ############################################################################################################
  223. # ################# Setup the listening thread for another instance launching with args ######################
  224. # ############################################################################################################
  225. if sys.platform == 'win32' or sys.platform == 'linux':
  226. # make sure the thread is stored by using a self. otherwise it's garbage collected
  227. self.listen_th = QtCore.QThread()
  228. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  229. self.new_launch = ArgsThread()
  230. self.new_launch.open_signal[list].connect(self.on_startup_args)
  231. self.new_launch.moveToThread(self.listen_th)
  232. self.new_launch.start.emit()
  233. # ############################################################################################################
  234. # ########################################## OS-specific #####################################################
  235. # ############################################################################################################
  236. portable = False
  237. # Folder for user settings.
  238. if sys.platform == 'win32':
  239. if platform.architecture()[0] == '32bit':
  240. App.log.debug("Win32!")
  241. else:
  242. App.log.debug("Win64!")
  243. # #######################################################################################################
  244. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  245. # #######################################################################################################
  246. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  247. try:
  248. with open(config_file, 'r'):
  249. pass
  250. except FileNotFoundError:
  251. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  252. try:
  253. with open(config_file, 'r') as f:
  254. try:
  255. for line in f:
  256. param = str(line).replace('\n', '').rpartition('=')
  257. if param[0] == 'portable':
  258. try:
  259. portable = eval(param[2])
  260. except NameError:
  261. portable = False
  262. if param[0] == 'headless':
  263. if param[2].lower() == 'true':
  264. self.cmd_line_headless = 1
  265. else:
  266. self.cmd_line_headless = None
  267. except Exception as e:
  268. log.debug('App.__init__() -->%s' % str(e))
  269. return
  270. except FileNotFoundError as e:
  271. log.debug(str(e))
  272. pass
  273. if portable is False:
  274. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  275. else:
  276. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  277. self.os = 'windows'
  278. else: # Linux/Unix/MacOS
  279. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  280. self.os = 'unix'
  281. # ############################################################################################################
  282. # ################################# Setup folders and files ##################################################
  283. # ############################################################################################################
  284. if not os.path.exists(self.data_path):
  285. os.makedirs(self.data_path)
  286. App.log.debug('Created data folder: ' + self.data_path)
  287. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  288. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  289. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  290. if not os.path.exists(self.preprocessorpaths):
  291. os.makedirs(self.preprocessorpaths)
  292. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  293. # create tools_db.FlatDB file if there is none
  294. try:
  295. f = open(self.data_path + '/tools_db.FlatDB')
  296. f.close()
  297. except IOError:
  298. App.log.debug('Creating empty tools_db.FlatDB')
  299. f = open(self.data_path + '/tools_db.FlatDB', 'w')
  300. json.dump({}, f)
  301. f.close()
  302. # create current_defaults.FlatConfig file if there is none
  303. try:
  304. f = open(self.data_path + '/current_defaults.FlatConfig')
  305. f.close()
  306. except IOError:
  307. App.log.debug('Creating empty current_defaults.FlatConfig')
  308. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  309. json.dump({}, f)
  310. f.close()
  311. # the factory defaults are written only once at the first launch of the application after installation
  312. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  313. # create a recent files json file if there is none
  314. try:
  315. f = open(self.data_path + '/recent.json')
  316. f.close()
  317. except IOError:
  318. App.log.debug('Creating empty recent.json')
  319. f = open(self.data_path + '/recent.json', 'w')
  320. json.dump([], f)
  321. f.close()
  322. # create a recent projects json file if there is none
  323. try:
  324. fp = open(self.data_path + '/recent_projects.json')
  325. fp.close()
  326. except IOError:
  327. App.log.debug('Creating empty recent_projects.json')
  328. fp = open(self.data_path + '/recent_projects.json', 'w')
  329. json.dump([], fp)
  330. fp.close()
  331. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  332. # This will fail under cx_freeze ...
  333. self.app_home = os.path.dirname(os.path.realpath(__file__))
  334. log.debug("Application path is " + self.app_home)
  335. log.debug("Started in " + os.getcwd())
  336. # cx_freeze workaround
  337. if os.path.isfile(self.app_home):
  338. self.app_home = os.path.dirname(self.app_home)
  339. os.chdir(self.app_home)
  340. # ############################################################################################################
  341. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  342. # ############################################################################################################
  343. self.defaults = FlatCAMDefaults(beta=self.beta, version=self.version)
  344. self.defaults["root_folder_path"] = self.app_home
  345. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  346. if user_defaults:
  347. self.defaults.load(filename=current_defaults_path)
  348. if self.defaults['units'] == 'MM':
  349. self.decimals = int(self.defaults['decimals_metric'])
  350. else:
  351. self.decimals = int(self.defaults['decimals_inch'])
  352. if self.defaults["global_gray_icons"] is False:
  353. self.resource_location = 'assets/resources'
  354. else:
  355. self.resource_location = 'assets/resources/dark_resources'
  356. self.current_units = self.defaults['units']
  357. # ###########################################################################################################
  358. # #################################### SETUP OBJECT CLASSES #################################################
  359. # ###########################################################################################################
  360. self.setup_obj_classes()
  361. # ###########################################################################################################
  362. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  363. # ###########################################################################################################
  364. self.pool = Pool()
  365. # ###########################################################################################################
  366. # ###################################### Clear GUI Settings - once at first start ###########################
  367. # ###########################################################################################################
  368. if self.defaults["first_run"] is True:
  369. # on first run clear the previous QSettings, therefore clearing the GUI settings
  370. qsettings = QSettings("Open Source", "FlatCAM")
  371. for key in qsettings.allKeys():
  372. qsettings.remove(key)
  373. # This will write the setting to the platform specific storage.
  374. del qsettings
  375. # ###########################################################################################################
  376. # ###################################### Setting the Splash Screen ##########################################
  377. # ###########################################################################################################
  378. splash_settings = QSettings("Open Source", "FlatCAM")
  379. if splash_settings.contains("splash_screen"):
  380. show_splash = splash_settings.value("splash_screen")
  381. else:
  382. splash_settings.setValue('splash_screen', 1)
  383. # This will write the setting to the platform specific storage.
  384. del splash_settings
  385. show_splash = 1
  386. if show_splash and self.cmd_line_headless != 1:
  387. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  388. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  389. # self.splash.setMask(splash_pix.mask())
  390. # move splashscreen to the current monitor
  391. desktop = QtWidgets.QApplication.desktop()
  392. screen = desktop.screenNumber(QtGui.QCursor.pos())
  393. current_screen_center = desktop.availableGeometry(screen).center()
  394. self.splash.move(current_screen_center - self.splash.rect().center())
  395. self.splash.show()
  396. self.splash.showMessage(_("FlatCAM is initializing ..."),
  397. alignment=Qt.AlignBottom | Qt.AlignLeft,
  398. color=QtGui.QColor("gray"))
  399. else:
  400. show_splash = 0
  401. # ###########################################################################################################
  402. # ######################################### Initialize GUI ##################################################
  403. # ###########################################################################################################
  404. # FlatCAM colors used in plotting
  405. self.FC_light_green = '#BBF268BF'
  406. self.FC_dark_green = '#006E20BF'
  407. self.FC_light_blue = '#a5a5ffbf'
  408. self.FC_dark_blue = '#0000ffbf'
  409. 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 = MainGUI(self)
  424. # set FlatCAM units in the Status bar
  425. self.set_screen_units(self.defaults['units'])
  426. # ###########################################################################################################
  427. # ########################################### AUTOSAVE SETUP ################################################
  428. # ###########################################################################################################
  429. self.block_autosave = False
  430. self.autosave_timer = QtCore.QTimer(self)
  431. self.save_project_auto_update()
  432. self.autosave_timer.timeout.connect(self.save_project_auto)
  433. # ###########################################################################################################
  434. # #################################### LOAD PREPROCESSORS ###################################################
  435. # ###########################################################################################################
  436. # ----------------------------------------- WARNING --------------------------------------------------------
  437. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  438. # That's because the number of preprocessors can vary and here the comboboxes are populated
  439. # -----------------------------------------------------------------------------------------------------------
  440. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  441. # the preprocessor file
  442. self.preprocessors = load_preprocessors(self)
  443. # make sure that always the 'default' preprocessor is the first item in the dictionary
  444. if 'default' in self.preprocessors.keys():
  445. new_ppp_dict = {}
  446. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  447. default_pp = self.preprocessors.pop('default')
  448. new_ppp_dict['default'] = default_pp
  449. # then add the rest of the keys
  450. for name, val_class in self.preprocessors.items():
  451. new_ppp_dict[name] = val_class
  452. # and now put back the ordered dict with 'default' key first
  453. self.preprocessors = new_ppp_dict
  454. # populate the Preprocessor ComboBoxes in the PREFERENCES
  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.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  465. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  466. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  467. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  468. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  469. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  470. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  471. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  472. QtCore.Qt.ToolTipRole)
  473. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  474. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  475. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  476. QtCore.Qt.ToolTipRole)
  477. # ###########################################################################################################
  478. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  479. # ###########################################################################################################
  480. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  481. inform=self.inform)
  482. self.preferencesUiManager.defaults_write_form()
  483. # When the self.defaults dictionary changes will update the Preferences GUI forms
  484. self.defaults.set_change_callback(self.on_defaults_dict_change)
  485. # ###########################################################################################################
  486. # ##################################### FIRST RUN SECTION ###################################################
  487. # ################################ It's done only once after install #####################################
  488. # ###########################################################################################################
  489. if self.defaults["first_run"] is True:
  490. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  491. initial_lay = 'minimal'
  492. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  493. # Set the combobox in Preferences to the current layout
  494. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  495. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  496. # after the first run, this object should be False
  497. self.defaults["first_run"] = False
  498. self.preferencesUiManager.save_defaults(silent=True)
  499. # ###########################################################################################################
  500. # ############################################ Data #########################################################
  501. # ###########################################################################################################
  502. self.recent = []
  503. self.recent_projects = []
  504. self.clipboard = QtWidgets.QApplication.clipboard()
  505. self.project_filename = None
  506. self.toggle_units_ignore = False
  507. self.main_thread = QtWidgets.QApplication.instance().thread()
  508. # ###########################################################################################################
  509. # ########################################## LOAD LANGUAGES ################################################
  510. # ###########################################################################################################
  511. self.languages = fcTranslate.load_languages()
  512. for name in sorted(self.languages.values()):
  513. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  514. # ###########################################################################################################
  515. # ####################################### APPLY APP LANGUAGE ################################################
  516. # ###########################################################################################################
  517. ret_val = fcTranslate.apply_language('strings')
  518. if ret_val == "no language":
  519. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  520. log.debug("Could not find the Language files. The App strings are missing.")
  521. else:
  522. # make the current language the current selection on the language combobox
  523. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  524. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  525. # ###########################################################################################################
  526. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  527. # ###########################################################################################################
  528. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  529. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  530. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  531. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  532. self.defaults.propagate_defaults()
  533. # ###########################################################################################################
  534. # ######################################## UPDATE THE OPTIONS ###############################################
  535. # ###########################################################################################################
  536. self.options = LoudDict()
  537. # -----------------------------------------------------------------------------------------------------------
  538. # Update the self.options from the self.defaults
  539. # The self.defaults holds the application defaults while the self.options holds the object defaults
  540. # -----------------------------------------------------------------------------------------------------------
  541. # Copy app defaults to project options
  542. for def_key, def_val in self.defaults.items():
  543. self.options[def_key] = deepcopy(def_val)
  544. self.preferencesUiManager.show_preferences_gui()
  545. # ### End of Data ####
  546. # ###########################################################################################################
  547. # #################################### SETUP OBJECT COLLECTION ##############################################
  548. # ###########################################################################################################
  549. self.collection = ObjectCollection(app=self)
  550. self.ui.project_tab_layout.addWidget(self.collection.view)
  551. self.app_obj = AppObject(app=self)
  552. # ### Adjust tabs width ## ##
  553. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  554. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  555. self.collection.view.setMinimumWidth(290)
  556. self.log.debug("Finished creating Object Collection.")
  557. # ###########################################################################################################
  558. # ######################################## SETUP Plot Area ##################################################
  559. # ###########################################################################################################
  560. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  561. if self.defaults["global_graphic_engine"] == '3D':
  562. self.is_legacy = False
  563. else:
  564. self.is_legacy = True
  565. # Event signals disconnect id holders
  566. self.mp = None
  567. self.mm = None
  568. self.mr = None
  569. self.mdc = None
  570. self.mp_zc = None
  571. self.kp = None
  572. # Matplotlib axis
  573. self.axes = None
  574. if show_splash:
  575. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  576. "Canvas initialization started."),
  577. alignment=Qt.AlignBottom | Qt.AlignLeft,
  578. color=QtGui.QColor("gray"))
  579. start_plot_time = time.time() # debug
  580. self.plotcanvas = None
  581. self.app_cursor = None
  582. self.hover_shapes = None
  583. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  584. # setup the PlotCanvas
  585. self.on_plotcanvas_setup()
  586. end_plot_time = time.time()
  587. self.used_time = end_plot_time - start_plot_time
  588. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  589. if show_splash:
  590. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  591. "Canvas initialization started.\n"
  592. "Canvas initialization finished in"), '%.2f' % self.used_time),
  593. alignment=Qt.AlignBottom | Qt.AlignLeft,
  594. color=QtGui.QColor("gray"))
  595. self.ui.splitter.setStretchFactor(1, 2)
  596. # ###########################################################################################################
  597. # ############################################### SYS TRAY ##################################################
  598. # ###########################################################################################################
  599. if self.defaults["global_systray_icon"]:
  600. self.parent_w = QtWidgets.QWidget()
  601. if self.cmd_line_headless == 1:
  602. self.trayIcon = FlatCAMSystemTray(app=self,
  603. icon=QtGui.QIcon(self.resource_location +
  604. '/flatcam_icon32_green.png'),
  605. headless=True,
  606. parent=self.parent_w)
  607. else:
  608. self.trayIcon = FlatCAMSystemTray(app=self,
  609. icon=QtGui.QIcon(self.resource_location +
  610. '/flatcam_icon32_green.png'),
  611. parent=self.parent_w)
  612. # ###########################################################################################################
  613. # ############################################### Worker SETUP ##############################################
  614. # ###########################################################################################################
  615. if self.defaults["global_worker_number"]:
  616. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  617. else:
  618. self.workers = WorkerStack(workers_number=2)
  619. self.worker_task.connect(self.workers.add_task)
  620. self.log.debug("Finished creating Workers crew.")
  621. # ###########################################################################################################
  622. # ############################################# Activity Monitor ###########################################
  623. # ###########################################################################################################
  624. # self.activity_view = FlatCAMActivityView(app=self)
  625. # self.ui.infobar.addWidget(self.activity_view)
  626. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  627. # ###########################################################################################################
  628. # ############################################# Signal handling #############################################
  629. # ###########################################################################################################
  630. # ########################################## Custom signals ################################################
  631. # signal for displaying messages in status bar
  632. self.inform[str].connect(self.info)
  633. self.inform[str, bool].connect(self.info)
  634. # signal for displaying messages in the shell
  635. self.inform_shell.connect(self.info_shell)
  636. # signal to be called when the app is quiting
  637. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  638. self.message.connect(lambda: message_dialog(parent=self.ui))
  639. # self.progress.connect(self.set_progress_bar)
  640. # signals emitted when file state change
  641. self.file_opened.connect(self.register_recent)
  642. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  643. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  644. # ########################################## Standard signals ###############################################
  645. # ### Menu
  646. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  647. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  648. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  649. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  650. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  651. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  652. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  653. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  654. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  655. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  656. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  657. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  658. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  659. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  660. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  661. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  662. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  663. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  664. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  665. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  666. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  667. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  668. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  669. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  670. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  671. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  672. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  673. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  674. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  675. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  676. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  677. self.ui.menufile_exit.triggered.connect(self.final_save)
  678. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  679. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  680. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  681. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  682. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  683. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  684. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  685. self.ui.menueditdelete.triggered.connect(self.on_delete)
  686. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  687. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  688. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  689. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  690. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  691. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  692. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  693. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  694. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  695. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  696. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  697. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  698. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  699. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  700. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  701. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  702. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  703. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  704. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  705. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  706. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  707. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  708. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  709. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  710. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  711. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  712. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  713. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  714. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  715. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  716. self.ui.menuview_replot.triggered.connect(self.plot_all)
  717. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  718. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  719. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  720. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  721. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  722. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  723. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  724. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  725. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  726. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  727. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  728. self.ui.menuhelp_about.triggered.connect(self.on_about)
  729. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  730. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  731. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  732. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  733. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  734. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  735. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  736. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  737. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  738. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  739. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  740. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  741. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  742. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  743. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  744. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  745. # ToolBar signals
  746. self.connect_toolbar_signals(ui=self.ui)
  747. # Context Menu
  748. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  749. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  750. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  751. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  752. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  753. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  754. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  755. self.ui.clearplot.triggered.connect(self.clear_plots)
  756. self.ui.replot.triggered.connect(self.plot_all)
  757. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  758. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  759. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  760. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  761. self.ui.popmenu_move.triggered.connect(self.obj_move)
  762. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  763. # Project Context Menu -> Color Setting
  764. for act in self.ui.menuprojectcolor.actions():
  765. act.triggered.connect(self.on_set_color_action_triggered)
  766. # ###########################################################################################################
  767. # #################################### GUI PREFERENCES SIGNALS ##############################################
  768. # ###########################################################################################################
  769. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  770. lambda: self.on_toggle_units(no_pref=False))
  771. # ##################################### Workspace Setting Signals ###########################################
  772. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  773. self.on_workspace_modified)
  774. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  775. self.on_workspace_modified
  776. )
  777. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  778. # ###########################################################################################################
  779. # ######################################## GUI SETTINGS SIGNALS #############################################
  780. # ###########################################################################################################
  781. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  782. # ######################################## Tools related signals ############################################
  783. # portability changed signal
  784. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  785. # Object list
  786. self.object_status_changed.connect(self.collection.on_collection_updated)
  787. # when there are arguments at application startup this get launched
  788. self.args_at_startup[list].connect(self.on_startup_args)
  789. # ###########################################################################################################
  790. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  791. # ###########################################################################################################
  792. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  793. lambda: self.restore_extensions(ext_type='excellon'))
  794. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  795. lambda: self.restore_extensions(ext_type='gcode'))
  796. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  797. lambda: self.restore_extensions(ext_type='gerber'))
  798. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  799. lambda: self.delete_all_extensions(ext_type='excellon'))
  800. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  801. lambda: self.delete_all_extensions(ext_type='gcode'))
  802. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  803. lambda: self.delete_all_extensions(ext_type='gerber'))
  804. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  805. lambda: self.add_extension(ext_type='excellon'))
  806. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  807. lambda: self.add_extension(ext_type='gcode'))
  808. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  809. lambda: self.add_extension(ext_type='gerber'))
  810. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  811. lambda: self.del_extension(ext_type='excellon'))
  812. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  813. lambda: self.del_extension(ext_type='gcode'))
  814. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  815. lambda: self.del_extension(ext_type='gerber'))
  816. # connect the 'Apply' buttons from the Preferences/File Associations
  817. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  818. lambda: self.on_register_files(obj_type='excellon'))
  819. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  820. lambda: self.on_register_files(obj_type='gcode'))
  821. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  822. lambda: self.on_register_files(obj_type='gerber'))
  823. # ###########################################################################################################
  824. # ########################################### KEYWORDS SIGNALS ##############################################
  825. # ###########################################################################################################
  826. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  827. lambda: self.restore_extensions(ext_type='keyword'))
  828. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  829. lambda: self.delete_all_extensions(ext_type='keyword'))
  830. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  831. lambda: self.add_extension(ext_type='keyword'))
  832. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  833. lambda: self.del_extension(ext_type='keyword'))
  834. # ###########################################################################################################
  835. # ########################################### GUI SIGNALS ###################################################
  836. # ###########################################################################################################
  837. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  838. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  839. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  840. # ###########################################################################################################
  841. # ####################################### VARIOUS SIGNALS ###################################################
  842. # ###########################################################################################################
  843. # connect the abort_all_tasks related slots to the related signals
  844. self.proc_container.idle_flag.connect(self.app_is_idle)
  845. # signal emitted when a tab is closed in the Plot Area
  846. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  847. # signal to close the application
  848. self.close_app_signal.connect(self.kill_app)
  849. # ################################# FINISHED CONNECTING SIGNALS #############################################
  850. # ###########################################################################################################
  851. # ###########################################################################################################
  852. # ###########################################################################################################
  853. self.log.debug("Finished connecting Signals.")
  854. # ###########################################################################################################
  855. # ########################################## Other setups ###################################################
  856. # ###########################################################################################################
  857. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  858. # depending on from where those tools are called different actions can be done
  859. self.call_source = 'app'
  860. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  861. self.tool_tab_locked = False
  862. # decide if to show or hide the Notebook side of the screen at startup
  863. if self.defaults["global_project_at_startup"] is True:
  864. self.ui.splitter.setSizes([1, 1])
  865. else:
  866. self.ui.splitter.setSizes([0, 1])
  867. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  868. self.setup_component_editor()
  869. # ###########################################################################################################
  870. # ####################################### Auto-complete KEYWORDS ############################################
  871. # ###########################################################################################################
  872. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  873. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  874. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  875. 'export_exc',
  876. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  877. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  878. 'interiors', 'isolate', 'join_excellon',
  879. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  880. 'mirror', 'ncc',
  881. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  882. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  883. 'options', 'origin',
  884. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  885. 'save', 'save_project',
  886. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  887. 'skew', 'subtract_poly', 'subtract_rectangle',
  888. 'version', 'write_gcode'
  889. ]
  890. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  891. 'Paste_1',
  892. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  893. 'Toolchange_manual', 'True', 'Users',
  894. 'all', 'auto', 'axis',
  895. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  896. 'contour', 'default',
  897. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  898. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  899. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  900. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  901. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  902. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  903. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  904. 'spacing_columns',
  905. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  906. 'toolchange_xy', 'toolchangez', 'travelz',
  907. 'tooldia', 'use_threads', 'value',
  908. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  909. ]
  910. self.tcl_keywords = [
  911. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  912. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  913. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  914. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  915. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  916. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  917. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  918. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  919. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  920. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  921. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  922. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  923. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  924. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  925. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  926. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  927. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  928. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  929. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  930. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  931. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  932. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  933. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  934. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  935. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  936. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  937. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  938. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  939. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  940. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  941. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  942. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  943. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  944. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  945. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  946. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  947. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  948. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  949. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  950. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  951. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  952. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  953. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  954. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  955. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  956. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  957. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  958. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  959. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  960. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  961. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  962. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  963. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  964. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  965. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  966. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  967. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  968. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  969. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  970. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  971. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  972. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  973. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  974. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  975. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  976. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  977. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  978. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  979. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  980. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  981. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  982. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  983. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  984. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  985. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  986. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  987. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  988. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  989. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  990. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  991. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  992. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  993. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  994. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  995. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  996. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  997. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  998. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  999. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1000. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1001. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1002. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1003. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1004. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1005. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1006. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1007. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1008. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1009. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1010. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1011. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1012. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1013. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1014. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1015. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1016. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1017. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1018. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1019. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1020. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1021. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1022. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1023. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1024. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1025. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1026. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1027. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1028. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1029. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1030. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1031. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1032. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1033. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1034. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1035. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1036. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1037. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1038. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1039. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1040. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1041. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1042. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1043. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1044. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1045. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1046. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1047. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1048. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1049. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1050. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1051. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1052. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1053. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1054. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1055. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1056. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1057. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1058. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1059. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1060. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1061. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1062. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1063. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1064. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1065. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1066. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1067. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1068. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1069. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1070. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1071. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1072. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1073. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1074. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1075. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1076. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1077. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1078. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1079. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1080. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1081. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1082. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1083. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1084. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1085. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1086. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1087. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1088. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1089. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1090. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1091. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1092. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1093. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1094. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1095. ]
  1096. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1097. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1098. # ###########################################################################################################
  1099. # ########################################## Tools and Plugins ##############################################
  1100. # ###########################################################################################################
  1101. self.shell = None
  1102. self.dblsidedtool = None
  1103. self.distance_tool = None
  1104. self.distance_min_tool = None
  1105. self.panelize_tool = None
  1106. self.film_tool = None
  1107. self.paste_tool = None
  1108. self.calculator_tool = None
  1109. self.rules_tool = None
  1110. self.sub_tool = None
  1111. self.move_tool = None
  1112. self.cutout_tool = None
  1113. self.ncclear_tool = None
  1114. self.paint_tool = None
  1115. self.isolation_tool = None
  1116. self.drilling_tool = None
  1117. self.optimal_tool = None
  1118. self.transform_tool = None
  1119. self.properties_tool = None
  1120. self.pdf_tool = None
  1121. self.image_tool = None
  1122. self.pcb_wizard_tool = None
  1123. self.cal_exc_tool = None
  1124. self.qrcode_tool = None
  1125. self.copper_thieving_tool = None
  1126. self.fiducial_tool = None
  1127. self.edrills_tool = None
  1128. self.align_objects_tool = None
  1129. self.punch_tool = None
  1130. self.invert_tool = None
  1131. self.corners_tool = None
  1132. self.etch_tool = None
  1133. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1134. try:
  1135. self.install_tools()
  1136. except AttributeError as e:
  1137. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1138. # ###########################################################################################################
  1139. # ############################################ SETUP RECENT ITEMS ###########################################
  1140. # ###########################################################################################################
  1141. self.setup_recent_items()
  1142. # ###########################################################################################################
  1143. # ######################################### BookMarks Manager ###############################################
  1144. # ###########################################################################################################
  1145. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1146. self.install_bookmarks()
  1147. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1148. # ###########################################################################################################
  1149. # ########################################### Tools Database ################################################
  1150. # ###########################################################################################################
  1151. self.tools_db_tab = None
  1152. # ### System Font Parsing ###
  1153. # self.f_parse = ParseFont(self)
  1154. # self.parse_system_fonts()
  1155. # ###########################################################################################################
  1156. # ############################################## Shell SETUP ################################################
  1157. # ###########################################################################################################
  1158. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1159. if self.defaults["global_shell_at_startup"]:
  1160. self.ui.shell_dock.show()
  1161. else:
  1162. self.ui.shell_dock.hide()
  1163. # ###########################################################################################################
  1164. # ######################################### Check for updates ###############################################
  1165. # ###########################################################################################################
  1166. # Separate thread (Not worker)
  1167. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1168. if (self.beta is False or self.beta is None) and \
  1169. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1170. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1171. # self.thr2 = QtCore.QThread()
  1172. self.worker_task.emit({'fcn': self.version_check,
  1173. 'params': []})
  1174. # self.thr2.start(QtCore.QThread.LowPriority)
  1175. # ###########################################################################################################
  1176. # ##################################### Register files with FlatCAM; #######################################
  1177. # ################################### It works only for Windows for now ####################################
  1178. # ###########################################################################################################
  1179. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1180. self.on_register_files()
  1181. # ###########################################################################################################
  1182. # ######################################## Variables for global usage #######################################
  1183. # ###########################################################################################################
  1184. # hold the App units
  1185. self.units = 'MM'
  1186. # coordinates for relative position display
  1187. self.rel_point1 = (0, 0)
  1188. self.rel_point2 = (0, 0)
  1189. # variable to store coordinates
  1190. self.pos = (0, 0)
  1191. self.pos_canvas = (0, 0)
  1192. self.pos_jump = (0, 0)
  1193. # variable to store mouse coordinates
  1194. self.mouse = [0, 0]
  1195. # variable to store the delta positions on cavnas
  1196. self.dx = 0
  1197. self.dy = 0
  1198. # decide if we have a double click or single click
  1199. self.doubleclick = False
  1200. # store here the is_dragging value
  1201. self.event_is_dragging = False
  1202. # variable to store if a command is active (then the var is not None) and which one it is
  1203. self.command_active = None
  1204. # variable to store the status of moving selection action
  1205. # None value means that it's not an selection action
  1206. # True value = a selection from left to right
  1207. # False value = a selection from right to left
  1208. self.selection_type = None
  1209. # List to store the objects that are currently loaded in FlatCAM
  1210. # This list is updated on each object creation or object delete
  1211. self.all_objects_list = []
  1212. self.objects_under_the_click_list = []
  1213. # List to store the objects that are selected
  1214. self.sel_objects_list = []
  1215. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1216. self.key_modifiers = None
  1217. # Variable to store the status of the code editor
  1218. self.toggle_codeeditor = False
  1219. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1220. self.click_noproject = False
  1221. self.cursor = None
  1222. # Variable to store the GCODE that was edited
  1223. self.gcode_edited = ""
  1224. # Variable to store old state of the Tools Toolbar; used in the Editor2Object and in Object2Editor methods
  1225. self.old_state_of_tools_toolbar = False
  1226. self.text_editor_tab = None
  1227. # reference for the self.ui.code_editor
  1228. self.reference_code_editor = None
  1229. self.script_code = ''
  1230. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1231. self.tools_db_changed_flag = False
  1232. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1233. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1234. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1235. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1236. 'tsm']
  1237. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1238. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1239. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1240. 'sbp', 'tap', 'xpi']
  1241. self.svg_list = ['svg']
  1242. self.dxf_list = ['dxf']
  1243. self.pdf_list = ['pdf']
  1244. self.prj_list = ['flatprj']
  1245. self.conf_list = ['flatconfig']
  1246. # last used filters
  1247. self.last_op_gerber_filter = None
  1248. self.last_op_excellon_filter = None
  1249. self.last_op_gcode_filter = None
  1250. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1251. # flag for polygons not cleared
  1252. self.poly_not_cleared = False
  1253. # VisPy visuals
  1254. self.isHovering = False
  1255. self.notHovering = True
  1256. # Window geometry
  1257. self.x_pos = None
  1258. self.y_pos = None
  1259. self.width = None
  1260. self.height = None
  1261. # when True, the app has to return from any thread
  1262. self.abort_flag = False
  1263. # set the value used in the Windows Title
  1264. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1265. # this holds a widget that is installed in the Plot Area when View Source option is used
  1266. self.source_editor_tab = None
  1267. self.pagesize = {}
  1268. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1269. # VisPy visuals
  1270. if self.is_legacy is False:
  1271. try:
  1272. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1273. except AttributeError:
  1274. self.tool_shapes = None
  1275. else:
  1276. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1277. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1278. # used in the delayed shutdown self.start_delayed_quit() method
  1279. self.save_timer = None
  1280. # ###########################################################################################################
  1281. # ################################## ADDING FlatCAM EDITORS section #########################################
  1282. # ###########################################################################################################
  1283. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1284. # at the first launch of the App , the editors will not be functional.
  1285. try:
  1286. self.geo_editor = AppGeoEditor(self)
  1287. except Exception as es:
  1288. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1289. try:
  1290. self.exc_editor = AppExcEditor(self)
  1291. except Exception as es:
  1292. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1293. try:
  1294. self.grb_editor = AppGerberEditor(self)
  1295. except Exception as es:
  1296. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1297. try:
  1298. self.gcode_editor = AppGCodeEditor(self)
  1299. except Exception as es:
  1300. log.debug("app_Main.__init__() --> GCode Editor Error: %s" % str(es))
  1301. self.log.debug("Finished adding FlatCAM Editor's.")
  1302. self.set_ui_title(name=_("New Project - Not saved"))
  1303. current_platform = platform.architecture()[0]
  1304. if current_platform != '64bit':
  1305. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1306. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1307. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1308. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1309. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1310. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1311. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1312. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1313. # ###########################################################################################################
  1314. # ########################################### EXCLUSION AREAS ###############################################
  1315. # ###########################################################################################################
  1316. self.exc_areas = ExclusionAreas(app=self)
  1317. # ###########################################################################################################
  1318. # ##################################### Finished the CONSTRUCTOR ############################################
  1319. # ###########################################################################################################
  1320. App.log.debug("END of constructor. Releasing control.")
  1321. # ###########################################################################################################
  1322. # ########################################## SHOW GUI #######################################################
  1323. # ###########################################################################################################
  1324. # if the app is not started as headless, show it
  1325. if self.cmd_line_headless != 1:
  1326. if show_splash:
  1327. # finish the splash
  1328. self.splash.finish(self.ui)
  1329. mgui_settings = QSettings("Open Source", "FlatCAM")
  1330. if mgui_settings.contains("maximized_gui"):
  1331. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1332. if maximized_ui is True:
  1333. self.ui.showMaximized()
  1334. else:
  1335. self.ui.show()
  1336. else:
  1337. self.ui.show()
  1338. if self.defaults["global_systray_icon"]:
  1339. self.trayIcon.show()
  1340. else:
  1341. log.warning("******************* RUNNING HEADLESS *******************")
  1342. # ###########################################################################################################
  1343. # ######################################## START-UP ARGUMENTS ###############################################
  1344. # ###########################################################################################################
  1345. # test if the program was started with a script as parameter
  1346. if self.cmd_line_shellvar:
  1347. try:
  1348. cnt = 0
  1349. command_tcl = 0
  1350. for i in self.cmd_line_shellvar.split(','):
  1351. if i is not None:
  1352. # noinspection PyBroadException
  1353. try:
  1354. command_tcl = eval(i)
  1355. except Exception:
  1356. command_tcl = i
  1357. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1358. cnt += 1
  1359. # if there are Windows paths then replace the path separator with a Unix like one
  1360. if sys.platform == 'win32':
  1361. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1362. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1363. except Exception as ext:
  1364. print("ERROR: ", ext)
  1365. sys.exit(2)
  1366. if self.cmd_line_shellfile:
  1367. if self.cmd_line_headless != 1:
  1368. if self.ui.shell_dock.isHidden():
  1369. self.ui.shell_dock.show()
  1370. try:
  1371. with open(self.cmd_line_shellfile, "r") as myfile:
  1372. # if show_splash:
  1373. # self.splash.showMessage('%s: %ssec\n%s' % (
  1374. # _("Canvas initialization started.\n"
  1375. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1376. # _("Executing Tcl Script ...")),
  1377. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1378. # color=QtGui.QColor("gray"))
  1379. cmd_line_shellfile_text = myfile.read()
  1380. if self.cmd_line_headless != 1:
  1381. self.shell.exec_command(cmd_line_shellfile_text)
  1382. else:
  1383. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1384. except Exception as ext:
  1385. print("ERROR: ", ext)
  1386. sys.exit(2)
  1387. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1388. # the path/file_name must be enclosed in quotes if it contain spaces
  1389. if App.args:
  1390. self.args_at_startup.emit(App.args)
  1391. if self.defaults.old_defaults_found is True:
  1392. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1393. "Please reboot the application to update."))
  1394. self.defaults.old_defaults_found = False
  1395. # ######################################### INIT FINISHED #######################################################
  1396. # #################################################################################################################
  1397. # #################################################################################################################
  1398. # #################################################################################################################
  1399. # #################################################################################################################
  1400. # #################################################################################################################
  1401. @staticmethod
  1402. def copy_and_overwrite(from_path, to_path):
  1403. """
  1404. From here:
  1405. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1406. :param from_path: source path
  1407. :param to_path: destination path
  1408. :return: None
  1409. """
  1410. if os.path.exists(to_path):
  1411. shutil.rmtree(to_path)
  1412. try:
  1413. shutil.copytree(from_path, to_path)
  1414. except FileNotFoundError:
  1415. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1416. shutil.copytree(from_new_path, to_path)
  1417. def on_startup_args(self, args, silent=False):
  1418. """
  1419. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1420. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1421. :param args: a list containing the application args at startup
  1422. :return: None
  1423. """
  1424. if args is not None:
  1425. args_to_process = args
  1426. else:
  1427. args_to_process = App.args
  1428. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1429. for argument in args_to_process:
  1430. if '.FlatPrj'.lower() in argument.lower():
  1431. try:
  1432. project_name = str(argument)
  1433. if project_name == "":
  1434. if silent is False:
  1435. self.inform.emit(_("Cancelled."))
  1436. else:
  1437. # self.open_project(project_name)
  1438. run_from_arg = True
  1439. # self.worker_task.emit({'fcn': self.open_project,
  1440. # 'params': [project_name, run_from_arg]})
  1441. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1442. except Exception as e:
  1443. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1444. elif '.FlatConfig'.lower() in argument.lower():
  1445. try:
  1446. file_name = str(argument)
  1447. if file_name == "":
  1448. if silent is False:
  1449. self.inform.emit(_("Open Config file failed."))
  1450. else:
  1451. run_from_arg = True
  1452. # self.worker_task.emit({'fcn': self.open_config_file,
  1453. # 'params': [file_name, run_from_arg]})
  1454. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1455. except Exception as e:
  1456. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1457. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1458. try:
  1459. file_name = str(argument)
  1460. if file_name == "":
  1461. if silent is False:
  1462. self.inform.emit(_("Open Script file failed."))
  1463. else:
  1464. if silent is False:
  1465. self.on_fileopenscript(name=file_name)
  1466. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1467. self.on_filerunscript(name=file_name)
  1468. except Exception as e:
  1469. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1470. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1471. log.debug("App.on_startup_args() --> Quit event.")
  1472. sys.exit()
  1473. elif 'save'.lower() in argument.lower():
  1474. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1475. self.preferencesUiManager.save_defaults()
  1476. else:
  1477. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1478. proc_arg = argument.lower()
  1479. for ext in exc_list:
  1480. proc_ext = ext.replace(' ', '')
  1481. proc_ext = '.%s' % proc_ext
  1482. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1483. file_name = str(argument)
  1484. if file_name == "":
  1485. if silent is False:
  1486. self.inform.emit(_("Open Excellon file failed."))
  1487. else:
  1488. self.on_fileopenexcellon(name=file_name, signal=None)
  1489. return
  1490. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1491. for ext in gco_list:
  1492. proc_ext = ext.replace(' ', '')
  1493. proc_ext = '.%s' % proc_ext
  1494. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1495. file_name = str(argument)
  1496. if file_name == "":
  1497. if silent is False:
  1498. self.inform.emit(_("Open GCode file failed."))
  1499. else:
  1500. self.on_fileopengcode(name=file_name, signal=None)
  1501. return
  1502. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1503. for ext in grb_list:
  1504. proc_ext = ext.replace(' ', '')
  1505. proc_ext = '.%s' % proc_ext
  1506. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1507. file_name = str(argument)
  1508. if file_name == "":
  1509. if silent is False:
  1510. self.inform.emit(_("Open Gerber file failed."))
  1511. else:
  1512. self.on_fileopengerber(name=file_name, signal=None)
  1513. return
  1514. # if it reached here without already returning then the app was registered with a file that it does not
  1515. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1516. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1517. # for arg in args_to_process:
  1518. # if 'FlatCAM.exe' in arg:
  1519. # continue
  1520. # else:
  1521. # sys.exit(2)
  1522. def set_ui_title(self, name):
  1523. """
  1524. Sets the title of the main window.
  1525. :param name: String that store the project path and project name
  1526. :return: None
  1527. """
  1528. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1529. (self.version,
  1530. ('BETA' if self.beta else ''),
  1531. platform.architecture()[0],
  1532. self.engine,
  1533. name)
  1534. )
  1535. def on_app_restart(self):
  1536. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1537. # be left in the SySTray
  1538. try:
  1539. self.trayIcon.hide()
  1540. except Exception:
  1541. pass
  1542. fcTranslate.restart_program(app=self)
  1543. def clear_pool(self):
  1544. """
  1545. Clear the multiprocessing pool and calls garbage collector.
  1546. :return: None
  1547. """
  1548. self.pool.close()
  1549. self.pool = Pool()
  1550. self.pool_recreated.emit(self.pool)
  1551. gc.collect()
  1552. def install_tools(self):
  1553. """
  1554. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1555. Instantiation of the Tools classes.
  1556. The order that the tools are installed is important as they can depend on each other install position.
  1557. :return: None
  1558. """
  1559. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1560. self.shell = FCShell(app=self, version=self.version)
  1561. self.distance_tool = Distance(self)
  1562. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1563. before=self.ui.menueditorigin,
  1564. separator=False)
  1565. self.distance_min_tool = DistanceMin(self)
  1566. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1567. pos=self.ui.menuedit,
  1568. before=self.ui.menueditorigin,
  1569. separator=True)
  1570. self.dblsidedtool = DblSidedTool(self)
  1571. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1572. self.cal_exc_tool = ToolCalibration(self)
  1573. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1574. before=self.dblsidedtool.menuAction,
  1575. separator=False)
  1576. self.align_objects_tool = AlignObjects(self)
  1577. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1578. self.edrills_tool = ToolExtractDrills(self)
  1579. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1580. self.panelize_tool = Panelize(self)
  1581. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1582. self.film_tool = Film(self)
  1583. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1584. self.paste_tool = SolderPaste(self)
  1585. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1586. self.calculator_tool = ToolCalculator(self)
  1587. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1588. self.sub_tool = ToolSub(self)
  1589. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1590. pos=self.ui.menutool, separator=True)
  1591. self.rules_tool = RulesCheck(self)
  1592. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1593. pos=self.ui.menutool, separator=False)
  1594. self.optimal_tool = ToolOptimal(self)
  1595. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1596. pos=self.ui.menutool, separator=True)
  1597. self.move_tool = ToolMove(self)
  1598. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1599. before=self.ui.menueditorigin, separator=True)
  1600. self.cutout_tool = CutOut(self)
  1601. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1602. before=self.sub_tool.menuAction)
  1603. self.ncclear_tool = NonCopperClear(self)
  1604. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1605. before=self.sub_tool.menuAction, separator=True)
  1606. self.paint_tool = ToolPaint(self)
  1607. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1608. before=self.sub_tool.menuAction, separator=True)
  1609. self.isolation_tool = ToolIsolation(self)
  1610. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1611. before=self.sub_tool.menuAction, separator=True)
  1612. self.drilling_tool = ToolDrilling(self)
  1613. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1614. before=self.sub_tool.menuAction, separator=True)
  1615. self.copper_thieving_tool = ToolCopperThieving(self)
  1616. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1617. pos=self.ui.menutool)
  1618. self.fiducial_tool = ToolFiducials(self)
  1619. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1620. pos=self.ui.menutool)
  1621. self.qrcode_tool = QRCode(self)
  1622. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1623. pos=self.ui.menutool)
  1624. self.punch_tool = ToolPunchGerber(self)
  1625. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1626. self.invert_tool = ToolInvertGerber(self)
  1627. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1628. self.corners_tool = ToolCorners(self)
  1629. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1630. self.etch_tool = ToolEtchCompensation(self)
  1631. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1632. self.transform_tool = ToolTransform(self)
  1633. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1634. pos=self.ui.menuoptions, separator=True)
  1635. self.properties_tool = Properties(self)
  1636. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1637. pos=self.ui.menuoptions)
  1638. self.pdf_tool = ToolPDF(self)
  1639. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1640. pos=self.ui.menufileimport,
  1641. separator=True)
  1642. self.image_tool = ToolImage(self)
  1643. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1644. pos=self.ui.menufileimport,
  1645. separator=True)
  1646. self.pcb_wizard_tool = PcbWizard(self)
  1647. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1648. pos=self.ui.menufileimport)
  1649. self.log.debug("Tools are installed.")
  1650. def remove_tools(self):
  1651. """
  1652. Will remove all the actions in the Tool menu.
  1653. :return: None
  1654. """
  1655. for act in self.ui.menutool.actions():
  1656. self.ui.menutool.removeAction(act)
  1657. def init_tools(self):
  1658. """
  1659. Initialize the Tool tab in the notebook side of the central widget.
  1660. Remove the actions in the Tools menu.
  1661. Instantiate again the FlatCAM tools (plugins).
  1662. All this is required when changing the layout: standard, compact etc.
  1663. :return: None
  1664. """
  1665. log.debug("init_tools()")
  1666. # delete the data currently in the Tools Tab and the Tab itself
  1667. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1668. if widget is not None:
  1669. widget.deleteLater()
  1670. self.ui.notebook.removeTab(2)
  1671. # rebuild the Tools Tab
  1672. self.ui.tool_tab = QtWidgets.QWidget()
  1673. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1674. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1675. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1676. self.ui.tool_scroll_area = VerticalScrollArea()
  1677. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1678. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1679. # first remove all of them
  1680. self.remove_tools()
  1681. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1682. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1683. '&Command Line\tS')
  1684. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1685. # third install all of them
  1686. try:
  1687. self.install_tools()
  1688. except AttributeError:
  1689. pass
  1690. self.log.debug("Tools are initialized.")
  1691. # def parse_system_fonts(self):
  1692. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1693. # 'params': []})
  1694. def connect_tools_signals_to_toolbar(self, ui):
  1695. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1696. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1697. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1698. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1699. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1700. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1701. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1702. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1703. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1704. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1705. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1706. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1707. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1708. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1709. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1710. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1711. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1712. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1713. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1714. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1715. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1716. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1717. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1718. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1719. def connect_toolbar_signals(self, ui):
  1720. """
  1721. Reconnect the signals to the actions in the toolbar.
  1722. This has to be done each time after the FlatCAM tools are removed/installed.
  1723. :return: None
  1724. """
  1725. # Toolbar
  1726. # File Toolbar Signals
  1727. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1728. ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1729. ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1730. ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1731. ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1732. # View Toolbar Signals
  1733. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1734. ui.replot_btn.triggered.connect(self.plot_all)
  1735. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1736. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1737. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1738. # Edit Toolbar Signals
  1739. ui.editgeo_btn.triggered.connect(self.object2editor)
  1740. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1741. ui.copy_btn.triggered.connect(self.on_copy_command)
  1742. ui.delete_btn.triggered.connect(self.on_delete)
  1743. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1744. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1745. ui.origin_btn.triggered.connect(self.on_set_origin)
  1746. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1747. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1748. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1749. # Scripting Toolbar Signals
  1750. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1751. ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1752. ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1753. ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1754. # Tools Toolbar Signals
  1755. try:
  1756. self.connect_tools_signals_to_toolbar(ui=ui)
  1757. except Exception as err:
  1758. log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1759. def object2editor(self):
  1760. """
  1761. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1762. :return: None
  1763. """
  1764. self.defaults.report_usage("object2editor()")
  1765. # disable the objects menu as it may interfere with the appEditors
  1766. self.ui.menuobjects.setDisabled(True)
  1767. edited_object = self.collection.get_active()
  1768. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1769. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1770. pass
  1771. else:
  1772. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1773. return
  1774. if isinstance(edited_object, GeometryObject):
  1775. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1776. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1777. # we set the notebook to hidden
  1778. # self.ui.splitter.setSizes([0, 1])
  1779. if edited_object.multigeo is True:
  1780. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1781. if len(sel_rows) > 1:
  1782. self.inform.emit('[WARNING_NOTCL] %s' %
  1783. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1784. "is not possible.\n"
  1785. "Edit only one geometry at a time."))
  1786. if not sel_rows:
  1787. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1788. return
  1789. # determine the tool dia of the selected tool
  1790. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1791. # now find the key in the edited_object.tools that has this tooldia
  1792. multi_tool = 1
  1793. for tool in edited_object.tools:
  1794. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1795. multi_tool = tool
  1796. break
  1797. log.debug("Editing MultiGeo Geometry with tool diameter: %s" % str(multi_tool))
  1798. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1799. else:
  1800. log.debug("Editing SingleGeo Geometry with tool diameter.")
  1801. self.geo_editor.edit_fcgeometry(edited_object)
  1802. # set call source to the Editor we go into
  1803. self.call_source = 'geo_editor'
  1804. elif isinstance(edited_object, ExcellonObject):
  1805. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1806. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1807. if self.ui.splitter.sizes()[0] == 0:
  1808. self.ui.splitter.setSizes([1, 1])
  1809. self.exc_editor.edit_fcexcellon(edited_object)
  1810. # set call source to the Editor we go into
  1811. self.call_source = 'exc_editor'
  1812. elif isinstance(edited_object, GerberObject):
  1813. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1814. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1815. if self.ui.splitter.sizes()[0] == 0:
  1816. self.ui.splitter.setSizes([1, 1])
  1817. self.grb_editor.edit_fcgerber(edited_object)
  1818. # set call source to the Editor we go into
  1819. self.call_source = 'grb_editor'
  1820. # reset the following variables so the UI is built again after edit
  1821. edited_object.ui_build = False
  1822. elif isinstance(edited_object, CNCJobObject):
  1823. if self.ui.splitter.sizes()[0] == 0:
  1824. self.ui.splitter.setSizes([1, 1])
  1825. # set call source to the Editor we go into
  1826. self.call_source = 'gcode_editor'
  1827. self.gcode_editor.edit_fcgcode(edited_object)
  1828. # make sure that we can't select another object while in Editor Mode:
  1829. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1830. self.ui.project_frame.setDisabled(True)
  1831. # delete any selection shape that might be active as they are not relevant in Editor
  1832. self.delete_selection_shape()
  1833. # hide the Tools Toolbar
  1834. tools_tb = self.ui.toolbartools
  1835. if tools_tb.isVisible():
  1836. self.old_state_of_tools_toolbar = True
  1837. tools_tb.hide()
  1838. else:
  1839. self.old_state_of_tools_toolbar = False
  1840. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1841. self.ui.plot_tab_area.protectTab(0)
  1842. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1843. self.should_we_save = True
  1844. def editor2object(self, cleanup=None):
  1845. """
  1846. Transfers the Geometry or Excellon from it's editor to the current object.
  1847. :return: None
  1848. """
  1849. self.defaults.report_usage("editor2object()")
  1850. # re-enable the objects menu that was disabled on entry in Editor mode
  1851. self.ui.menuobjects.setDisabled(False)
  1852. # do not update a geometry or excellon object unless it comes out of an editor
  1853. if self.call_source != 'app':
  1854. edited_obj = self.collection.get_active()
  1855. if cleanup is None:
  1856. msgbox = QtWidgets.QMessageBox()
  1857. msgbox.setText(_("Do you want to save the edited object?"))
  1858. msgbox.setWindowTitle(_("Close Editor"))
  1859. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1860. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1861. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1862. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1863. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1864. msgbox.setDefaultButton(bt_yes)
  1865. msgbox.exec_()
  1866. response = msgbox.clickedButton()
  1867. if response == bt_yes:
  1868. # show the Tools Toolbar
  1869. tools_tb = self.ui.toolbartools
  1870. if self.old_state_of_tools_toolbar is True:
  1871. tools_tb.show()
  1872. # clean the Tools Tab
  1873. self.ui.tool_scroll_area.takeWidget()
  1874. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1875. self.ui.notebook.setTabText(2, "Tool")
  1876. if edited_obj.kind == 'geometry':
  1877. obj_type = "Geometry"
  1878. self.geo_editor.update_fcgeometry(edited_obj)
  1879. # self.geo_editor.update_options(edited_obj)
  1880. # restore GUI to the Selected TAB
  1881. # Remove anything else in the appGUI
  1882. self.ui.tool_scroll_area.takeWidget()
  1883. # update the geo object options so it is including the bounding box values
  1884. try:
  1885. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1886. edited_obj.options['xmin'] = xmin
  1887. edited_obj.options['ymin'] = ymin
  1888. edited_obj.options['xmax'] = xmax
  1889. edited_obj.options['ymax'] = ymax
  1890. except AttributeError as e:
  1891. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1892. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1893. edited_obj.build_ui()
  1894. edited_obj.plot()
  1895. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1896. elif edited_obj.kind == 'gerber':
  1897. obj_type = "Gerber"
  1898. self.grb_editor.update_fcgerber()
  1899. # self.grb_editor.update_options(edited_obj)
  1900. # delete the old object (the source object) if it was an empty one
  1901. try:
  1902. if len(edited_obj.solid_geometry) == 0:
  1903. old_name = edited_obj.options['name']
  1904. self.collection.delete_by_name(old_name)
  1905. except TypeError:
  1906. # if the solid_geometry is a single Polygon the len() will not work
  1907. # in any case, falling here means that we have something in the solid_geometry, even if only
  1908. # a single Polygon, therefore we pass this
  1909. pass
  1910. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1911. # restore GUI to the Selected TAB
  1912. # Remove anything else in the GUI
  1913. self.ui.selected_scroll_area.takeWidget()
  1914. elif edited_obj.kind == 'excellon':
  1915. obj_type = "Excellon"
  1916. self.exc_editor.update_fcexcellon(edited_obj)
  1917. # self.exc_editor.update_options(edited_obj)
  1918. # restore GUI to the Selected TAB
  1919. # Remove anything else in the GUI
  1920. self.ui.tool_scroll_area.takeWidget()
  1921. # delete the old object (the source object) if it was an empty one
  1922. # find if we have drills:
  1923. has_drills = None
  1924. for tt in edited_obj.tools:
  1925. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1926. has_drills = True
  1927. break
  1928. # find if we have slots:
  1929. has_slots = None
  1930. for tt in edited_obj.tools:
  1931. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1932. has_slots = True
  1933. break
  1934. if has_drills is None and has_slots is None:
  1935. old_name = edited_obj.options['name']
  1936. self.collection.delete_by_name(name=old_name)
  1937. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1938. elif edited_obj.kind == 'cncjob':
  1939. obj_type = "CNCJob"
  1940. self.gcode_editor.update_fcgcode(edited_obj)
  1941. # self.exc_editor.update_options(edited_obj)
  1942. # restore GUI to the Selected TAB
  1943. # Remove anything else in the GUI
  1944. self.ui.tool_scroll_area.takeWidget()
  1945. edited_obj.build_ui()
  1946. # close the open tab
  1947. for idx in range(self.ui.plot_tab_area.count()):
  1948. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1949. self.ui.plot_tab_area.closeTab(idx)
  1950. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1951. else:
  1952. self.inform.emit('[WARNING_NOTCL] %s' %
  1953. _("Select a Gerber, Geometry, Excellon or CNCJobObject to update."))
  1954. return
  1955. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1956. elif response == bt_no:
  1957. # show the Tools Toolbar
  1958. tools_tb = self.ui.toolbartools
  1959. if self.old_state_of_tools_toolbar is True:
  1960. tools_tb.show()
  1961. # clean the Tools Tab
  1962. self.ui.tool_scroll_area.takeWidget()
  1963. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1964. self.ui.notebook.setTabText(2, "Tool")
  1965. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1966. if edited_obj.kind == 'geometry':
  1967. self.geo_editor.deactivate()
  1968. edited_obj.build_ui()
  1969. edited_obj.plot()
  1970. elif edited_obj.kind == 'gerber':
  1971. self.grb_editor.deactivate_grb_editor()
  1972. edited_obj.build_ui()
  1973. elif edited_obj.kind == 'excellon':
  1974. self.exc_editor.deactivate()
  1975. edited_obj.build_ui()
  1976. elif edited_obj.kind == 'cncjob':
  1977. self.gcode_editor.deactivate()
  1978. edited_obj.build_ui()
  1979. # close the open tab
  1980. for idx in range(self.ui.plot_tab_area.count()):
  1981. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1982. self.ui.plot_tab_area.closeTab(idx)
  1983. else:
  1984. self.inform.emit('[WARNING_NOTCL] %s' %
  1985. _("Select a Gerber, Geometry, Excellon or CNCJobObject to update."))
  1986. return
  1987. elif response == bt_cancel:
  1988. return
  1989. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1990. # edited_obj.build_ui()
  1991. # Switch notebook to Selected page
  1992. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1993. else:
  1994. # show the Tools Toolbar
  1995. tools_tb = self.ui.toolbartools
  1996. if self.old_state_of_tools_toolbar is True:
  1997. tools_tb.show()
  1998. if isinstance(edited_obj, GeometryObject):
  1999. self.geo_editor.deactivate()
  2000. elif isinstance(edited_obj, GerberObject):
  2001. self.grb_editor.deactivate_grb_editor()
  2002. elif isinstance(edited_obj, ExcellonObject):
  2003. self.exc_editor.deactivate()
  2004. else:
  2005. self.inform.emit('[WARNING_NOTCL] %s' %
  2006. _("Select a Gerber, Geometry or Excellon Object to update."))
  2007. return
  2008. # if notebook is hidden we show it
  2009. if self.ui.splitter.sizes()[0] == 0:
  2010. self.ui.splitter.setSizes([1, 1])
  2011. # restore the call_source to app
  2012. self.call_source = 'app'
  2013. # edited_obj.plot()
  2014. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2015. self.ui.plot_tab_area.protectTab(0)
  2016. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2017. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2018. self.ui.project_frame.setDisabled(False)
  2019. def get_last_folder(self):
  2020. """
  2021. Get the folder path from where the last file was opened.
  2022. :return: String, last opened folder path
  2023. """
  2024. return self.defaults["global_last_folder"]
  2025. def get_last_save_folder(self):
  2026. """
  2027. Get the folder path from where the last file was saved.
  2028. :return: String, last saved folder path
  2029. """
  2030. loc = self.defaults["global_last_save_folder"]
  2031. if loc is None:
  2032. loc = self.defaults["global_last_folder"]
  2033. if loc is None:
  2034. loc = os.path.dirname(__file__)
  2035. return loc
  2036. @QtCore.pyqtSlot(str)
  2037. @QtCore.pyqtSlot(str, bool)
  2038. def info(self, msg, shell_echo=True):
  2039. """
  2040. Informs the user. Normally on the status bar, optionally
  2041. also on the shell.
  2042. :param msg: Text to write.
  2043. :type msg: str
  2044. :param shell_echo: Control if to display the message msg in the Shell
  2045. :type shell_echo: bool
  2046. :return: None
  2047. """
  2048. # Type of message in brackets at the beginning of the message.
  2049. match = re.search(r"\[(.*)\](.*)", msg)
  2050. if match:
  2051. level = match.group(1)
  2052. msg_ = match.group(2)
  2053. self.ui.fcinfo.set_status(str(msg_), level=level)
  2054. if shell_echo is True:
  2055. if level.lower() == "error":
  2056. self.shell_message(msg, error=True, show=True)
  2057. elif level.lower() == "warning":
  2058. self.shell_message(msg, warning=True, show=True)
  2059. elif level.lower() == "error_notcl":
  2060. self.shell_message(msg, error=True, show=False)
  2061. elif level.lower() == "warning_notcl":
  2062. self.shell_message(msg, warning=True, show=False)
  2063. elif level.lower() == "success":
  2064. self.shell_message(msg, success=True, show=False)
  2065. elif level.lower() == "selected":
  2066. self.shell_message(msg, selected=True, show=False)
  2067. else:
  2068. self.shell_message(msg, show=False)
  2069. else:
  2070. self.ui.fcinfo.set_status(str(msg), level="info")
  2071. # make sure that if the message is to clear the infobar with a space
  2072. # is not printed over and over on the shell
  2073. if msg != '' and shell_echo is True:
  2074. self.shell_message(msg)
  2075. def info_shell(self, msg):
  2076. self.shell_message(msg=msg)
  2077. def on_import_preferences(self):
  2078. """
  2079. Loads the application default settings from a saved file into
  2080. ``self.defaults`` dictionary.
  2081. :return: None
  2082. """
  2083. self.defaults.report_usage("on_import_preferences")
  2084. App.log.debug("App.on_import_preferences()")
  2085. # Show file chooser
  2086. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2087. try:
  2088. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2089. directory=self.data_path,
  2090. filter=filter_)
  2091. except TypeError:
  2092. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2093. filter=filter_)
  2094. filename = str(filename)
  2095. if filename == "":
  2096. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2097. return
  2098. # Load in the defaults from the chosen file
  2099. self.defaults.load(filename=filename)
  2100. self.preferencesUiManager.on_preferences_edited()
  2101. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2102. def on_export_preferences(self):
  2103. """
  2104. Save the defaults dictionary to a file.
  2105. :return: None
  2106. """
  2107. self.defaults.report_usage("on_export_preferences")
  2108. App.log.debug("on_export_preferences()")
  2109. # defaults_file_content = None
  2110. # Show file chooser
  2111. date = str(datetime.today()).rpartition('.')[0]
  2112. date = ''.join(c for c in date if c not in ':-')
  2113. date = date.replace(' ', '_')
  2114. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2115. try:
  2116. filename, _f = FCFileSaveDialog.get_saved_filename(
  2117. caption=_("Export FlatCAM Preferences"),
  2118. directory=self.data_path + '/preferences_' + date,
  2119. ext_filter=filter__
  2120. )
  2121. except TypeError:
  2122. filename, _f = FCFileSaveDialog.get_saved_filename(
  2123. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2124. filename = str(filename)
  2125. if filename == "":
  2126. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2127. return
  2128. # Update options
  2129. self.preferencesUiManager.defaults_read_form()
  2130. self.defaults.propagate_defaults()
  2131. # Save update options
  2132. try:
  2133. self.defaults.write(filename=filename)
  2134. except Exception:
  2135. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2136. return
  2137. if self.defaults["global_open_style"] is False:
  2138. self.file_opened.emit("preferences", filename)
  2139. self.file_saved.emit("preferences", filename)
  2140. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2141. def save_to_file(self, content_to_save, txt_content):
  2142. """
  2143. Save something to a file.
  2144. :return: None
  2145. """
  2146. self.defaults.report_usage("save_to_file")
  2147. App.log.debug("save_to_file()")
  2148. self.date = str(datetime.today()).rpartition('.')[0]
  2149. self.date = ''.join(c for c in self.date if c not in ':-')
  2150. self.date = self.date.replace(' ', '_')
  2151. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2152. path_to_save = self.defaults["global_last_save_folder"] if \
  2153. self.defaults["global_last_save_folder"] is not None else self.data_path
  2154. try:
  2155. filename, _f = FCFileSaveDialog.get_saved_filename(
  2156. caption=_("Save to file"),
  2157. directory=path_to_save + '/file_' + self.date,
  2158. ext_filter=filter__
  2159. )
  2160. except TypeError:
  2161. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2162. filename = str(filename)
  2163. if filename == "":
  2164. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2165. return
  2166. else:
  2167. try:
  2168. with open(filename, 'w') as f:
  2169. ___ = f.read()
  2170. except PermissionError:
  2171. self.inform.emit('[WARNING] %s' %
  2172. _("Permission denied, saving not possible.\n"
  2173. "Most likely another app is holding the file open and not accessible."))
  2174. return
  2175. except IOError:
  2176. App.log.debug('Creating a new file ...')
  2177. f = open(filename, 'w')
  2178. f.close()
  2179. except Exception:
  2180. e = sys.exc_info()[0]
  2181. App.log.error("Could not load the file.")
  2182. App.log.error(str(e))
  2183. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2184. return
  2185. # Save content
  2186. if filename.rpartition('.')[2].lower() == 'html':
  2187. file_content = content_to_save
  2188. else:
  2189. file_content = txt_content
  2190. try:
  2191. with open(filename, "w") as f:
  2192. f.write(file_content)
  2193. except Exception:
  2194. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2195. return
  2196. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2197. def register_recent(self, kind, filename):
  2198. """
  2199. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2200. dictionary.
  2201. :param kind: type of file that was opened
  2202. :param filename: the path and file name for the file that was opened
  2203. :return:
  2204. """
  2205. self.log.debug("register_recent()")
  2206. self.log.debug(" %s" % kind)
  2207. self.log.debug(" %s" % filename)
  2208. record = {'kind': str(kind), 'filename': str(filename)}
  2209. if record in self.recent:
  2210. return
  2211. if record in self.recent_projects:
  2212. return
  2213. if record['kind'] == 'project':
  2214. self.recent_projects.insert(0, record)
  2215. else:
  2216. self.recent.insert(0, record)
  2217. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2218. self.recent.pop()
  2219. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2220. self.recent_projects.pop()
  2221. try:
  2222. f = open(self.data_path + '/recent.json', 'w')
  2223. except IOError:
  2224. App.log.error("Failed to open recent items file for writing.")
  2225. self.inform.emit('[ERROR_NOTCL] %s' %
  2226. _('Failed to open recent files file for writing.'))
  2227. return
  2228. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2229. f.close()
  2230. try:
  2231. fp = open(self.data_path + '/recent_projects.json', 'w')
  2232. except IOError:
  2233. App.log.error("Failed to open recent items file for writing.")
  2234. self.inform.emit('[ERROR_NOTCL] %s' %
  2235. _('Failed to open recent projects file for writing.'))
  2236. return
  2237. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2238. fp.close()
  2239. # Re-build the recent items menu
  2240. self.setup_recent_items()
  2241. def on_about(self):
  2242. """
  2243. Displays the "about" dialog found in the Menu --> Help.
  2244. :return: None
  2245. """
  2246. self.defaults.report_usage("on_about")
  2247. version = self.version
  2248. version_date = self.version_date
  2249. beta = self.beta
  2250. class AboutDialog(QtWidgets.QDialog):
  2251. def __init__(self, app, parent=None):
  2252. QtWidgets.QDialog.__init__(self, parent)
  2253. self.app = app
  2254. # Icon and title
  2255. self.setWindowIcon(parent.app_icon)
  2256. self.setWindowTitle(_("About FlatCAM"))
  2257. self.resize(600, 200)
  2258. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2259. # self.setStyleSheet(
  2260. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2261. # "background-attachment: fixed"
  2262. # )
  2263. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2264. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2265. # palette = QtGui.QPalette()
  2266. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2267. # self.setPalette(palette)
  2268. logo = QtWidgets.QLabel()
  2269. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2270. title = QtWidgets.QLabel(
  2271. "<font size=8><B>FlatCAM</B></font><BR>"
  2272. "{title}<BR>"
  2273. "<BR>"
  2274. "<BR>"
  2275. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2276. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2277. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2278. "<B>{issue}</B></a><BR>".format(
  2279. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2280. devel=_("Development"),
  2281. down=_("DOWNLOAD"),
  2282. issue=_("Issue tracker"))
  2283. )
  2284. title.setOpenExternalLinks(True)
  2285. closebtn = QtWidgets.QPushButton(_("Close"))
  2286. tab_widget = QtWidgets.QTabWidget()
  2287. description_label = QtWidgets.QLabel(
  2288. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2289. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2290. version=version,
  2291. beta=('BETA' if beta else ''),
  2292. date=version_date,
  2293. arch=platform.architecture()[0])
  2294. )
  2295. description_label.setOpenExternalLinks(True)
  2296. lic_lbl_header = QtWidgets.QLabel(
  2297. '%s:<br>%s<br>' % (
  2298. _('Licensed under the MIT license'),
  2299. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2300. "http://www.opensource.org/licenses/mit-license.php</a>"
  2301. )
  2302. )
  2303. lic_lbl_header.setOpenExternalLinks(True)
  2304. lic_lbl_body = QtWidgets.QLabel(
  2305. _(
  2306. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2307. 'of this software and associated documentation files (the "Software"), to deal\n'
  2308. 'in the Software without restriction, including without limitation the rights\n'
  2309. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2310. 'copies of the Software, and to permit persons to whom the Software is\n'
  2311. 'furnished to do so, subject to the following conditions:\n\n'
  2312. 'The above copyright notice and this permission notice shall be included in\n'
  2313. 'all copies or substantial portions of the Software.\n\n'
  2314. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2315. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2316. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2317. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2318. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2319. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2320. 'THE SOFTWARE.'
  2321. )
  2322. )
  2323. attributions_label = QtWidgets.QLabel(
  2324. _(
  2325. 'Some of the icons used are from the following sources:<br>'
  2326. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2327. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2328. 'title="Flaticon">www.flaticon.com</a></div>'
  2329. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2330. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2331. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2332. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2333. 'title="Flaticon">www.flaticon.com</a></div>'
  2334. )
  2335. )
  2336. attributions_label.setOpenExternalLinks(True)
  2337. # layouts
  2338. layout1 = QtWidgets.QVBoxLayout()
  2339. layout1_1 = QtWidgets.QHBoxLayout()
  2340. layout1_2 = QtWidgets.QHBoxLayout()
  2341. layout2 = QtWidgets.QHBoxLayout()
  2342. layout3 = QtWidgets.QHBoxLayout()
  2343. self.setLayout(layout1)
  2344. layout1.addLayout(layout1_1)
  2345. layout1.addLayout(layout1_2)
  2346. layout1.addLayout(layout2)
  2347. layout1.addLayout(layout3)
  2348. layout1_1.addStretch()
  2349. layout1_1.addWidget(description_label)
  2350. layout1_2.addWidget(tab_widget)
  2351. self.splash_tab = QtWidgets.QWidget()
  2352. self.splash_tab.setObjectName("splash_about")
  2353. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2354. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2355. tab_widget.addTab(self.splash_tab, _("Splash"))
  2356. self.programmmers_tab = QtWidgets.QWidget()
  2357. self.programmmers_tab.setObjectName("programmers_about")
  2358. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2359. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2360. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2361. self.translators_tab = QtWidgets.QWidget()
  2362. self.translators_tab.setObjectName("translators_about")
  2363. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2364. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2365. tab_widget.addTab(self.translators_tab, _("Translators"))
  2366. self.license_tab = QtWidgets.QWidget()
  2367. self.license_tab.setObjectName("license_about")
  2368. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2369. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2370. tab_widget.addTab(self.license_tab, _("License"))
  2371. self.attributions_tab = QtWidgets.QWidget()
  2372. self.attributions_tab.setObjectName("attributions_about")
  2373. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2374. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2375. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2376. self.splash_tab_layout.addWidget(logo, stretch=0)
  2377. self.splash_tab_layout.addWidget(title, stretch=1)
  2378. pal = QtGui.QPalette()
  2379. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2380. self.prog_grid_lay = QtWidgets.QGridLayout()
  2381. self.prog_grid_lay.setHorizontalSpacing(20)
  2382. self.prog_grid_lay.setColumnStretch(0, 0)
  2383. self.prog_grid_lay.setColumnStretch(2, 1)
  2384. prog_widget = QtWidgets.QWidget()
  2385. prog_widget.setLayout(self.prog_grid_lay)
  2386. prog_scroll = QtWidgets.QScrollArea()
  2387. prog_scroll.setWidget(prog_widget)
  2388. prog_scroll.setWidgetResizable(True)
  2389. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2390. prog_scroll.setPalette(pal)
  2391. self.programmmers_tab_layout.addWidget(prog_scroll)
  2392. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2393. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2394. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2395. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2396. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2397. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2398. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2399. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2400. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2401. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2402. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2403. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2404. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2405. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2406. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2407. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2408. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2409. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2410. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2411. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2412. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2413. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2414. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2415. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2416. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2417. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2418. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2419. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2420. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2421. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2422. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2423. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2424. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2425. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2426. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2427. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2428. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2429. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2430. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2431. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2432. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2433. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2434. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2435. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2436. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2437. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2438. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2439. self.translator_grid_lay = QtWidgets.QGridLayout()
  2440. self.translator_grid_lay.setColumnStretch(0, 0)
  2441. self.translator_grid_lay.setColumnStretch(1, 0)
  2442. self.translator_grid_lay.setColumnStretch(2, 1)
  2443. self.translator_grid_lay.setColumnStretch(3, 0)
  2444. # trans_widget = QtWidgets.QWidget()
  2445. # trans_widget.setLayout(self.translator_grid_lay)
  2446. # self.translators_tab_layout.addWidget(trans_widget)
  2447. # self.translators_tab_layout.addStretch()
  2448. trans_widget = QtWidgets.QWidget()
  2449. trans_widget.setLayout(self.translator_grid_lay)
  2450. trans_scroll = QtWidgets.QScrollArea()
  2451. trans_scroll.setWidget(trans_widget)
  2452. trans_scroll.setWidgetResizable(True)
  2453. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2454. trans_scroll.setPalette(pal)
  2455. self.translators_tab_layout.addWidget(trans_scroll)
  2456. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2457. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2458. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2459. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2460. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2461. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2462. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2463. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2464. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2465. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2466. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2467. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2468. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2469. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2470. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2471. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2472. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2473. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2474. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2475. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2476. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2477. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2478. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2479. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2480. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2481. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2482. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2483. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2484. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2485. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2486. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2487. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2488. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2489. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2490. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2491. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2492. self.translator_grid_lay.setColumnStretch(0, 0)
  2493. self.translators_tab_layout.addStretch()
  2494. self.license_tab_layout.addWidget(lic_lbl_header)
  2495. self.license_tab_layout.addWidget(lic_lbl_body)
  2496. self.license_tab_layout.addStretch()
  2497. self.attributions_tab_layout.addWidget(attributions_label)
  2498. self.attributions_tab_layout.addStretch()
  2499. layout3.addStretch()
  2500. layout3.addWidget(closebtn)
  2501. closebtn.clicked.connect(self.accept)
  2502. AboutDialog(app=self, parent=self.ui).exec_()
  2503. def on_readme(self):
  2504. """
  2505. Displays the "about" dialog found in the Menu --> Help.
  2506. :return: None
  2507. """
  2508. class ReadmeDialog(QtWidgets.QDialog):
  2509. def __init__(self, app, parent=None):
  2510. QtWidgets.QDialog.__init__(self, parent)
  2511. self.app = app
  2512. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2513. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2514. "<b>click</b></a>"
  2515. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2516. # donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2517. # "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2518. # Icon and title
  2519. self.setWindowIcon(parent.app_icon)
  2520. self.setWindowTitle(_("Important Information's"))
  2521. self.resize(750, 375)
  2522. logo = QtWidgets.QLabel()
  2523. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2524. # content = QtWidgets.QLabel(
  2525. # "%s<br>"
  2526. # "%s<br><br>"
  2527. # "%s,<br>"
  2528. # "%s<br>"
  2529. # "<ul>"
  2530. # "<li> &nbsp;%s %s</li>"
  2531. # "<li> &nbsp;%s %s</li>"
  2532. # "</ul>"
  2533. # "%s %s.<br>"
  2534. # "%s"
  2535. # "<ul>"
  2536. # "<li> &nbsp;%s &#128077;</li>"
  2537. # "<li> &nbsp;%s &#128513;</li>"
  2538. # "</ul>" %
  2539. # (
  2540. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2541. # _("Yet it cannot evolve without <b>contributions</b>."),
  2542. # _("If you want to see this application grow and become better and better"),
  2543. # _("you can <b>contribute</b> to the development yourself by:"),
  2544. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2545. # new_features_link,
  2546. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2547. # bugs_link,
  2548. # _("If you like or use this program you can make a donation"),
  2549. # donation_link,
  2550. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2551. # _("it will be welcomed with joy"),
  2552. # _("it will give me a reason to continue")
  2553. # )
  2554. # )
  2555. content = QtWidgets.QLabel(
  2556. "%s<br>"
  2557. "%s<br><br>"
  2558. "%s,<br>"
  2559. "%s<br>"
  2560. "<ul>"
  2561. "<li> &nbsp;%s %s</li>"
  2562. "<li> &nbsp;%s %s</li>"
  2563. "</ul>" %
  2564. (
  2565. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2566. _("Yet it cannot evolve without <b>contributions</b>."),
  2567. _("If you want to see this application grow and become better and better"),
  2568. _("you can <b>contribute</b> to the development yourself by:"),
  2569. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2570. new_features_link,
  2571. _("Bug Reports by providing the steps required to reproduce the bug"),
  2572. bugs_link
  2573. )
  2574. )
  2575. content.setOpenExternalLinks(True)
  2576. # palette
  2577. pal = QtGui.QPalette()
  2578. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2579. # layouts
  2580. main_layout = QtWidgets.QVBoxLayout()
  2581. self.setLayout(main_layout)
  2582. tab_layout = QtWidgets.QHBoxLayout()
  2583. buttons_hlay = QtWidgets.QHBoxLayout()
  2584. main_layout.addLayout(tab_layout)
  2585. main_layout.addLayout(buttons_hlay)
  2586. tab_widget = QtWidgets.QTabWidget()
  2587. tab_layout.addWidget(tab_widget)
  2588. closebtn = QtWidgets.QPushButton(_("Close"))
  2589. buttons_hlay.addStretch()
  2590. buttons_hlay.addWidget(closebtn)
  2591. # CONTRIBUTE section
  2592. self.intro_tab = QtWidgets.QWidget()
  2593. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2594. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2595. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2596. self.grid_lay = QtWidgets.QGridLayout()
  2597. self.grid_lay.setHorizontalSpacing(20)
  2598. self.grid_lay.setColumnStretch(0, 0)
  2599. self.grid_lay.setColumnStretch(1, 1)
  2600. intro_wdg = QtWidgets.QWidget()
  2601. intro_wdg.setLayout(self.grid_lay)
  2602. intro_scroll_area = QtWidgets.QScrollArea()
  2603. intro_scroll_area.setWidget(intro_wdg)
  2604. intro_scroll_area.setWidgetResizable(True)
  2605. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2606. intro_scroll_area.setPalette(pal)
  2607. self.grid_lay.addWidget(logo, 0, 0)
  2608. self.grid_lay.addWidget(content, 0, 1)
  2609. self.intro_tab_layout.addWidget(intro_scroll_area)
  2610. # LINKS EXCHANGE section
  2611. self.links_tab = QtWidgets.QWidget()
  2612. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2613. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2614. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2615. self.links_lay = QtWidgets.QHBoxLayout()
  2616. links_wdg = QtWidgets.QWidget()
  2617. links_wdg.setLayout(self.links_lay)
  2618. links_scroll_area = QtWidgets.QScrollArea()
  2619. links_scroll_area.setWidget(links_wdg)
  2620. links_scroll_area.setWidgetResizable(True)
  2621. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2622. links_scroll_area.setPalette(pal)
  2623. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2624. self.links_tab_layout.addWidget(links_scroll_area)
  2625. # HOW TO section
  2626. self.howto_tab = QtWidgets.QWidget()
  2627. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2628. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2629. tab_widget.addTab(self.howto_tab, _("How To's"))
  2630. self.howto_lay = QtWidgets.QHBoxLayout()
  2631. howto_wdg = QtWidgets.QWidget()
  2632. howto_wdg.setLayout(self.howto_lay)
  2633. howto_scroll_area = QtWidgets.QScrollArea()
  2634. howto_scroll_area.setWidget(howto_wdg)
  2635. howto_scroll_area.setWidgetResizable(True)
  2636. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2637. howto_scroll_area.setPalette(pal)
  2638. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2639. self.howto_tab_layout.addWidget(howto_scroll_area)
  2640. # BUTTONS section
  2641. closebtn.clicked.connect(self.accept)
  2642. ReadmeDialog(app=self, parent=self.ui).exec_()
  2643. def install_bookmarks(self, book_dict=None):
  2644. """
  2645. Install the bookmarks actions in the Help menu -> Bookmarks
  2646. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2647. :return: None
  2648. """
  2649. if book_dict is None:
  2650. self.defaults["global_bookmarks"].update(
  2651. {
  2652. '1': ['FlatCAM', "http://flatcam.org"],
  2653. '2': ['Backup Site', ""]
  2654. }
  2655. )
  2656. else:
  2657. self.defaults["global_bookmarks"].clear()
  2658. self.defaults["global_bookmarks"].update(book_dict)
  2659. # first try to disconnect if somehow they get connected from elsewhere
  2660. for act in self.ui.menuhelp_bookmarks.actions():
  2661. try:
  2662. act.triggered.disconnect()
  2663. except TypeError:
  2664. pass
  2665. # clear all actions except the last one who is the Bookmark manager
  2666. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2667. pass
  2668. else:
  2669. self.ui.menuhelp_bookmarks.removeAction(act)
  2670. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2671. if self.defaults["global_bookmarks"]:
  2672. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2673. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2674. # the JSON is first making the keys as strings (therefore I have to use strings too
  2675. # or do the conversion :(
  2676. # )
  2677. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2678. # the '10' entry jsut after '1' therefore ordering as strings
  2679. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2680. key=lambda x: int(x[0]))
  2681. for entry, bookmark in sorted_bookmarks:
  2682. title = bookmark[0]
  2683. weblink = bookmark[1]
  2684. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2685. act.setText(title)
  2686. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2687. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2688. if title == 'Backup Site' and weblink == "":
  2689. act.triggered.connect(self.on_backup_site)
  2690. else:
  2691. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2692. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2693. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2694. def on_bookmarks_manager(self):
  2695. """
  2696. Adds the bookmark manager in a Tab in Plot Area
  2697. :return:
  2698. """
  2699. for idx in range(self.ui.plot_tab_area.count()):
  2700. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2701. # there can be only one instance of Bookmark Manager at one time
  2702. return
  2703. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2704. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2705. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2706. # add the tab if it was closed
  2707. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2708. # delete the absolute and relative position and messages in the infobar
  2709. # self.ui.position_label.setText("")
  2710. # self.ui.rel_position_label.setText("")
  2711. # hide coordinates toolbars in the infobar while in DB
  2712. self.ui.coords_toolbar.hide()
  2713. self.ui.delta_coords_toolbar.hide()
  2714. # Switch plot_area to preferences page
  2715. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2716. def on_backup_site(self):
  2717. msgbox = QtWidgets.QMessageBox()
  2718. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2719. "1. FlatCAM.org website is down\n"
  2720. "2. Someone forked FlatCAM project and wants to point\n"
  2721. "to his own website\n\n"
  2722. "If you can't get any informations about FlatCAM beta\n"
  2723. "use the YouTube channel link from the Help menu."))
  2724. msgbox.setWindowTitle(_("Alternative website"))
  2725. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2726. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2727. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2728. msgbox.setDefaultButton(bt_yes)
  2729. msgbox.exec_()
  2730. # response = msgbox.clickedButton()
  2731. def on_file_savedefaults(self):
  2732. """
  2733. Callback for menu item File->Save Defaults. Saves application default options
  2734. ``self.defaults`` to current_defaults.FlatConfig.
  2735. :return: None
  2736. """
  2737. self.preferencesUiManager.save_defaults()
  2738. def final_save(self):
  2739. """
  2740. Callback for doing a preferences save to file whenever the application is about to quit.
  2741. If the project has changes, it will ask the user to save the project.
  2742. :return: None
  2743. """
  2744. if self.save_in_progress:
  2745. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2746. return
  2747. if self.should_we_save and self.collection.get_list():
  2748. msgbox = QtWidgets.QMessageBox()
  2749. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2750. "\n"
  2751. "Do you want to Save the project?"))
  2752. msgbox.setWindowTitle(_("Save changes"))
  2753. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2754. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2755. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2756. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2757. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2758. msgbox.setDefaultButton(bt_yes)
  2759. msgbox.exec_()
  2760. response = msgbox.clickedButton()
  2761. if response == bt_yes:
  2762. try:
  2763. self.trayIcon.hide()
  2764. except Exception:
  2765. pass
  2766. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2767. elif response == bt_no:
  2768. try:
  2769. self.trayIcon.hide()
  2770. except Exception:
  2771. pass
  2772. self.quit_application()
  2773. elif response == bt_cancel:
  2774. return
  2775. else:
  2776. try:
  2777. self.trayIcon.hide()
  2778. except Exception:
  2779. pass
  2780. self.quit_application()
  2781. def quit_application(self):
  2782. """
  2783. Called (as a pyslot or not) when the application is quit.
  2784. :return: None
  2785. """
  2786. # close editors before quiting the app, if they are open
  2787. if self.geo_editor.editor_active is True:
  2788. self.geo_editor.deactivate()
  2789. try:
  2790. self.geo_editor.disconnect()
  2791. except TypeError:
  2792. pass
  2793. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2794. if self.exc_editor.editor_active is True:
  2795. self.exc_editor.deactivate()
  2796. try:
  2797. self.grb_editor.disconnect()
  2798. except TypeError:
  2799. pass
  2800. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2801. if self.grb_editor.editor_active is True:
  2802. self.grb_editor.deactivate_grb_editor()
  2803. try:
  2804. self.exc_editor.disconnect()
  2805. except TypeError:
  2806. pass
  2807. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2808. # disconnect the mouse events
  2809. if self.is_legacy:
  2810. self.plotcanvas.graph_event_disconnect(self.mm)
  2811. self.plotcanvas.graph_event_disconnect(self.mp)
  2812. self.plotcanvas.graph_event_disconnect(self.mr)
  2813. self.plotcanvas.graph_event_disconnect(self.mdc)
  2814. self.plotcanvas.graph_event_disconnect(self.kp)
  2815. else:
  2816. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2817. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2818. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2819. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2820. self.on_mouse_double_click_over_plot)
  2821. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2822. self.preferencesUiManager.save_defaults(silent=True)
  2823. log.debug("App.quit_application() --> App Defaults saved.")
  2824. if self.cmd_line_headless != 1:
  2825. # save app state to file
  2826. stgs = QSettings("Open Source", "FlatCAM")
  2827. stgs.setValue('saved_gui_state', self.ui.saveState())
  2828. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2829. stgs.setValue(
  2830. 'language',
  2831. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2832. )
  2833. stgs.setValue(
  2834. 'notebook_font_size',
  2835. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2836. )
  2837. stgs.setValue(
  2838. 'axis_font_size',
  2839. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2840. )
  2841. stgs.setValue(
  2842. 'textbox_font_size',
  2843. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2844. )
  2845. stgs.setValue(
  2846. 'hud_font_size',
  2847. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2848. )
  2849. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2850. stgs.setValue(
  2851. 'machinist',
  2852. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2853. )
  2854. # This will write the setting to the platform specific storage.
  2855. del stgs
  2856. log.debug("App.quit_application() --> App UI state saved.")
  2857. # try to quit the Socket opened by ArgsThread class
  2858. try:
  2859. # self.new_launch.thread_exit = True
  2860. # self.new_launch.listener.close()
  2861. self.new_launch.stop.emit()
  2862. except Exception as err:
  2863. log.debug("App.quit_application() --> %s" % str(err))
  2864. # try to quit the QThread that run ArgsThread class
  2865. try:
  2866. # del self.new_launch
  2867. self.listen_th.quit()
  2868. except Exception as e:
  2869. log.debug("App.quit_application() --> %s" % str(e))
  2870. # terminate workers
  2871. # self.workers.__del__()
  2872. self.clear_pool()
  2873. # quit app by signalling for self.kill_app() method
  2874. # self.close_app_signal.emit()
  2875. QtWidgets.qApp.quit()
  2876. sys.exit(0)
  2877. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2878. # we use the following command
  2879. # minor_v = sys.version_info.minor
  2880. # if minor_v < 8:
  2881. # # make sure that the app closes
  2882. # sys.exit(0)
  2883. # else:
  2884. # os._exit(0) # fix to work with Python 3.8
  2885. @staticmethod
  2886. def kill_app():
  2887. QtWidgets.qApp.quit()
  2888. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2889. # we use the following command
  2890. sys.exit(0)
  2891. def on_portable_checked(self, state):
  2892. """
  2893. Callback called when the checkbox in Preferences GUI is checked.
  2894. It will set the application as portable by creating the preferences and recent files in the
  2895. 'config' folder found in the FlatCAM installation folder.
  2896. :param state: boolean, the state of the checkbox when clicked/checked
  2897. :return:
  2898. """
  2899. line_no = 0
  2900. data = None
  2901. if sys.platform != 'win32':
  2902. # this won't work in Linux or MacOS
  2903. return
  2904. # test if the app was frozen and choose the path for the configuration file
  2905. if getattr(sys, "frozen", False) is True:
  2906. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2907. else:
  2908. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2909. config_file = current_data_path + '\\configuration.txt'
  2910. try:
  2911. with open(config_file, 'r') as f:
  2912. try:
  2913. data = f.readlines()
  2914. except Exception as e:
  2915. log.debug('App.__init__() -->%s' % str(e))
  2916. return
  2917. except FileNotFoundError:
  2918. pass
  2919. for line in data:
  2920. line = line.strip('\n')
  2921. param = str(line).rpartition('=')
  2922. if param[0] == 'portable':
  2923. break
  2924. line_no += 1
  2925. if state:
  2926. data[line_no] = 'portable=True\n'
  2927. # create the new defauults files
  2928. # create current_defaults.FlatConfig file if there is none
  2929. try:
  2930. f = open(current_data_path + '/current_defaults.FlatConfig')
  2931. f.close()
  2932. except IOError:
  2933. App.log.debug('Creating empty current_defaults.FlatConfig')
  2934. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2935. json.dump({}, f)
  2936. f.close()
  2937. # create factory_defaults.FlatConfig file if there is none
  2938. try:
  2939. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2940. f.close()
  2941. except IOError:
  2942. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2943. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2944. json.dump({}, f)
  2945. f.close()
  2946. try:
  2947. f = open(current_data_path + '/recent.json')
  2948. f.close()
  2949. except IOError:
  2950. App.log.debug('Creating empty recent.json')
  2951. f = open(current_data_path + '/recent.json', 'w')
  2952. json.dump([], f)
  2953. f.close()
  2954. try:
  2955. fp = open(current_data_path + '/recent_projects.json')
  2956. fp.close()
  2957. except IOError:
  2958. App.log.debug('Creating empty recent_projects.json')
  2959. fp = open(current_data_path + '/recent_projects.json', 'w')
  2960. json.dump([], fp)
  2961. fp.close()
  2962. # save the current defaults to the new defaults file
  2963. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2964. else:
  2965. data[line_no] = 'portable=False\n'
  2966. with open(config_file, 'w') as f:
  2967. f.writelines(data)
  2968. def on_register_files(self, obj_type=None):
  2969. """
  2970. Called whenever there is a need to register file extensions with FlatCAM.
  2971. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2972. :param obj_type: the type of object to be register for.
  2973. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2974. :return: None
  2975. """
  2976. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2977. new_reg_path = 'Software\\Classes\\'
  2978. # find if the current user is admin
  2979. try:
  2980. is_admin = os.getuid() == 0
  2981. except AttributeError:
  2982. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2983. if is_admin is True:
  2984. root_path = winreg.HKEY_LOCAL_MACHINE
  2985. else:
  2986. root_path = winreg.HKEY_CURRENT_USER
  2987. # create the keys
  2988. def set_reg(name, root_pth, new_reg_path, value):
  2989. try:
  2990. winreg.CreateKey(root_pth, new_reg_path)
  2991. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2992. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2993. return True
  2994. except WindowsError:
  2995. return False
  2996. # delete key in registry
  2997. def delete_reg(root_pth, reg_path, key_to_del):
  2998. key_to_del_path = reg_path + key_to_del
  2999. try:
  3000. winreg.DeleteKey(root_pth, key_to_del_path)
  3001. return True
  3002. except WindowsError:
  3003. return False
  3004. if obj_type is None or obj_type == 'excellon':
  3005. exc_list = \
  3006. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3007. exc_list = [x for x in exc_list if x != '']
  3008. # register all keys in the Preferences window
  3009. for ext in exc_list:
  3010. new_k = new_reg_path + '.%s' % ext
  3011. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3012. # and unregister those that are no longer in the Preferences windows but are in the file
  3013. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3014. if ext not in exc_list:
  3015. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3016. # now write the updated extensions to the self.defaults
  3017. # new_ext = ''
  3018. # for ext in exc_list:
  3019. # new_ext = new_ext + ext + ', '
  3020. # self.defaults["fa_excellon"] = new_ext
  3021. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3022. if obj_type is None or obj_type == 'gcode':
  3023. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3024. gco_list = [x for x in gco_list if x != '']
  3025. # register all keys in the Preferences window
  3026. for ext in gco_list:
  3027. new_k = new_reg_path + '.%s' % ext
  3028. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3029. # and unregister those that are no longer in the Preferences windows but are in the file
  3030. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3031. if ext not in gco_list:
  3032. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3033. # now write the updated extensions to the self.defaults
  3034. # new_ext = ''
  3035. # for ext in gco_list:
  3036. # new_ext = new_ext + ext + ', '
  3037. # self.defaults["fa_gcode"] = new_ext
  3038. self.inform.emit('[success] %s' %
  3039. _("Selected GCode file extensions registered with FlatCAM."))
  3040. if obj_type is None or obj_type == 'gerber':
  3041. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3042. grb_list = [x for x in grb_list if x != '']
  3043. # register all keys in the Preferences window
  3044. for ext in grb_list:
  3045. new_k = new_reg_path + '.%s' % ext
  3046. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3047. # and unregister those that are no longer in the Preferences windows but are in the file
  3048. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3049. if ext not in grb_list:
  3050. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3051. # now write the updated extensions to the self.defaults
  3052. # new_ext = ''
  3053. # for ext in grb_list:
  3054. # new_ext = new_ext + ext + ', '
  3055. # self.defaults["fa_gerber"] = new_ext
  3056. self.inform.emit('[success] %s' %
  3057. _("Selected Gerber file extensions registered with FlatCAM."))
  3058. def add_extension(self, ext_type):
  3059. """
  3060. Add a file extension to the list for a specific object
  3061. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3062. :return:
  3063. """
  3064. if ext_type == 'excellon':
  3065. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3066. if new_ext == '':
  3067. return
  3068. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3069. if new_ext in old_val:
  3070. return
  3071. old_val.append(new_ext)
  3072. old_val.sort()
  3073. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3074. if ext_type == 'gcode':
  3075. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3076. if new_ext == '':
  3077. return
  3078. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3079. if new_ext in old_val:
  3080. return
  3081. old_val.append(new_ext)
  3082. old_val.sort()
  3083. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3084. if ext_type == 'gerber':
  3085. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3086. if new_ext == '':
  3087. return
  3088. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3089. if new_ext in old_val:
  3090. return
  3091. old_val.append(new_ext)
  3092. old_val.sort()
  3093. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3094. if ext_type == 'keyword':
  3095. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3096. if new_kw == '':
  3097. return
  3098. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3099. if new_kw in old_val:
  3100. return
  3101. old_val.append(new_kw)
  3102. old_val.sort()
  3103. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3104. # update the self.myKeywords so the model is updated
  3105. self.autocomplete_kw_list = \
  3106. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3107. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3108. self.shell._edit.set_model_data(self.myKeywords)
  3109. def del_extension(self, ext_type):
  3110. """
  3111. Remove a file extension from the list for a specific object
  3112. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3113. :return:
  3114. """
  3115. if ext_type == 'excellon':
  3116. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3117. if new_ext == '':
  3118. return
  3119. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3120. if new_ext not in old_val:
  3121. return
  3122. old_val.remove(new_ext)
  3123. old_val.sort()
  3124. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3125. if ext_type == 'gcode':
  3126. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3127. if new_ext == '':
  3128. return
  3129. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3130. if new_ext not in old_val:
  3131. return
  3132. old_val.remove(new_ext)
  3133. old_val.sort()
  3134. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3135. if ext_type == 'gerber':
  3136. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3137. if new_ext == '':
  3138. return
  3139. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3140. if new_ext not in old_val:
  3141. return
  3142. old_val.remove(new_ext)
  3143. old_val.sort()
  3144. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3145. if ext_type == 'keyword':
  3146. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3147. if new_kw == '':
  3148. return
  3149. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3150. if new_kw not in old_val:
  3151. return
  3152. old_val.remove(new_kw)
  3153. old_val.sort()
  3154. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3155. # update the self.myKeywords so the model is updated
  3156. self.autocomplete_kw_list = \
  3157. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3158. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3159. self.shell._edit.set_model_data(self.myKeywords)
  3160. def restore_extensions(self, ext_type):
  3161. """
  3162. Restore all file extensions associations with FlatCAM, for a specific object
  3163. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3164. :return:
  3165. """
  3166. if ext_type == 'excellon':
  3167. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3168. # for the ability to open Excellon files with .txt extension
  3169. new_exc_list = deepcopy(self.exc_list)
  3170. try:
  3171. new_exc_list.remove('txt')
  3172. except ValueError:
  3173. pass
  3174. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3175. if ext_type == 'gcode':
  3176. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3177. if ext_type == 'gerber':
  3178. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3179. if ext_type == 'keyword':
  3180. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3181. # update the self.myKeywords so the model is updated
  3182. self.autocomplete_kw_list = self.default_keywords
  3183. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3184. self.shell._edit.set_model_data(self.myKeywords)
  3185. def delete_all_extensions(self, ext_type):
  3186. """
  3187. Delete all file extensions associations with FlatCAM, for a specific object
  3188. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3189. :return:
  3190. """
  3191. if ext_type == 'excellon':
  3192. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3193. if ext_type == 'gcode':
  3194. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3195. if ext_type == 'gerber':
  3196. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3197. if ext_type == 'keyword':
  3198. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3199. # update the self.myKeywords so the model is updated
  3200. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3201. self.shell._edit.set_model_data(self.myKeywords)
  3202. def on_edit_join(self, name=None):
  3203. """
  3204. Callback for Edit->Join. Joins the selected geometry objects into
  3205. a new one.
  3206. :return: None
  3207. """
  3208. self.defaults.report_usage("on_edit_join()")
  3209. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3210. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3211. geo_type_set = set()
  3212. objs = self.collection.get_selected()
  3213. if len(objs) < 2:
  3214. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3215. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3216. return 'fail'
  3217. for obj in objs:
  3218. geo_type_set.add(obj.multigeo)
  3219. # if len(geo_type_list) == 1 means that all list elements are the same
  3220. if len(geo_type_set) != 1:
  3221. self.inform.emit('[ERROR] %s' %
  3222. _("Failed join. The Geometry objects are of different types.\n"
  3223. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3224. "convert from one to another and retry joining \n"
  3225. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3226. "the result may not be what was expected. \n"
  3227. "Check the generated GCODE."))
  3228. return
  3229. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3230. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3231. if True in geo_type_set:
  3232. def initialize(geo_obj, app):
  3233. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3234. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3235. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3236. for v in geo_obj.tools.values():
  3237. v['data']['name'] = obj_name_multi
  3238. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3239. else:
  3240. def initialize(geo_obj, app):
  3241. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3242. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3243. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3244. for v in geo_obj.tools.values():
  3245. v['data']['name'] = obj_name_single
  3246. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3247. self.should_we_save = True
  3248. def on_edit_join_exc(self):
  3249. """
  3250. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3251. a new Excellon.
  3252. :return: None
  3253. """
  3254. self.defaults.report_usage("on_edit_join_exc()")
  3255. objs = self.collection.get_selected()
  3256. for obj in objs:
  3257. if not isinstance(obj, ExcellonObject):
  3258. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3259. return
  3260. if len(objs) < 2:
  3261. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3262. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3263. return 'fail'
  3264. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3265. def initialize(exc_obj, app):
  3266. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3267. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3268. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3269. self.should_we_save = True
  3270. def on_edit_join_grb(self):
  3271. """
  3272. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3273. a new Gerber object.
  3274. :return: None
  3275. """
  3276. self.defaults.report_usage("on_edit_join_grb()")
  3277. objs = self.collection.get_selected()
  3278. for obj in objs:
  3279. if not isinstance(obj, GerberObject):
  3280. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3281. return
  3282. if len(objs) < 2:
  3283. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3284. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3285. return 'fail'
  3286. def initialize(grb_obj, app):
  3287. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3288. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3289. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3290. self.should_we_save = True
  3291. def on_convert_singlegeo_to_multigeo(self):
  3292. """
  3293. Called for converting a Geometry object from single-geo to multi-geo.
  3294. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3295. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3296. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3297. the solid-geometry of that tool.
  3298. :return: None
  3299. """
  3300. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3301. obj = self.collection.get_active()
  3302. if obj is None:
  3303. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3304. return
  3305. if not isinstance(obj, GeometryObject):
  3306. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3307. return
  3308. obj.multigeo = True
  3309. for tooluid, dict_value in obj.tools.items():
  3310. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3311. if not isinstance(obj.solid_geometry, list):
  3312. obj.solid_geometry = [obj.solid_geometry]
  3313. # obj.solid_geometry[:] = []
  3314. obj.plot()
  3315. self.should_we_save = True
  3316. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3317. def on_convert_multigeo_to_singlegeo(self):
  3318. """
  3319. Called for converting a Geometry object from multi-geo to single-geo.
  3320. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3321. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3322. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3323. the solid-geometry of that tool.
  3324. :return: None
  3325. """
  3326. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3327. obj = self.collection.get_active()
  3328. if obj is None:
  3329. self.inform.emit('[ERROR_NOTCL] %s' %
  3330. _("Failed. Select a Geometry Object and try again."))
  3331. return
  3332. if not isinstance(obj, GeometryObject):
  3333. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3334. (_("Expected a GeometryObject, got"), type(obj)))
  3335. return
  3336. obj.multigeo = False
  3337. total_solid_geometry = []
  3338. for tooluid, dict_value in obj.tools.items():
  3339. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3340. # clear the original geometry
  3341. dict_value['solid_geometry'][:] = []
  3342. obj.solid_geometry = deepcopy(total_solid_geometry)
  3343. obj.plot()
  3344. self.should_we_save = True
  3345. self.inform.emit('[success] %s' %
  3346. _("A Geometry object was converted to SingleGeo type."))
  3347. def on_defaults_dict_change(self, field):
  3348. """
  3349. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3350. Edit -> Preferences tab window.
  3351. :param field: the key of the self.defaults dictionary that was changed.
  3352. :return: None
  3353. """
  3354. self.preferencesUiManager.defaults_write_form_field(field=field)
  3355. if field == "units":
  3356. self.set_screen_units(self.defaults['units'])
  3357. def set_screen_units(self, units):
  3358. """
  3359. Set the FlatCAM units on the status bar.
  3360. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3361. :return: None
  3362. """
  3363. self.ui.units_label.setText("[" + units.lower() + "]")
  3364. def on_toggle_units_click(self):
  3365. try:
  3366. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3367. except (TypeError, AttributeError):
  3368. pass
  3369. if self.defaults["units"] == 'MM':
  3370. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3371. else:
  3372. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3373. self.on_toggle_units(no_pref=True)
  3374. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3375. lambda: self.on_toggle_units(no_pref=False))
  3376. def on_toggle_units(self, no_pref=False):
  3377. """
  3378. Callback for the Units radio-button change in the Preferences tab.
  3379. Changes the application's default units adn for the project too.
  3380. If changing the project's units, the change propagates to all of
  3381. the objects in the project.
  3382. :return: None
  3383. """
  3384. self.defaults.report_usage("on_toggle_units")
  3385. if self.toggle_units_ignore:
  3386. return
  3387. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3388. # If option is the same, then ignore
  3389. if new_units == self.defaults["units"].upper():
  3390. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3391. return
  3392. # Keys in self.defaults for which to scale their values
  3393. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3394. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3395. "tools_iso_tool_vtipdia",
  3396. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3397. "gerber_editor_ma_high",
  3398. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3399. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3400. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3401. "excellon_feedrate_probe", "excellon_milling_dia",
  3402. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3403. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3404. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3405. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3406. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3407. "geometry_extracut_length", "geometry_z_pdepth",
  3408. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3409. 'cncjob_tooldia',
  3410. 'tools_paintoffset', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3411. "tools_paintnewdia",
  3412. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3413. "tools_nccnewdia", "tools_ncc_offset_value",
  3414. "tools_2sided_drilldia",
  3415. "tools_film_boundary", "tools_film_scale_stroke",
  3416. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3417. "tools_cutout_depthperpass",
  3418. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3419. "tools_panelize_spacing_rows",
  3420. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3421. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3422. "tools_transform_buffer_dis",
  3423. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3424. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3425. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3426. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3427. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3428. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3429. "tools_cr_h2h_val", "tools_cr_dh_val",
  3430. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3431. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3432. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3433. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3434. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3435. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3436. "tools_copper_thieving_mask_clearance",
  3437. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3438. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3439. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3440. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3441. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3442. "tools_invert_margin",
  3443. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3444. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3445. def scale_defaults(sfactor):
  3446. for dim in dimensions:
  3447. if dim in [
  3448. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3449. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3450. 'tools_transform_mirror_point'
  3451. ]:
  3452. if self.defaults[dim] is None or self.defaults[dim] == '':
  3453. continue
  3454. try:
  3455. coordinates = self.defaults[dim].split(",")
  3456. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3457. coords_xy[0] *= sfactor
  3458. coords_xy[1] *= sfactor
  3459. self.defaults[dim] = "%.*f, %.*f" % (
  3460. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3461. except Exception as e:
  3462. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3463. elif dim in [
  3464. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3465. ]:
  3466. if self.defaults[dim] is None or self.defaults[dim] == '':
  3467. continue
  3468. try:
  3469. self.defaults[dim] = float(self.defaults[dim])
  3470. tools_diameters = [self.defaults[dim]]
  3471. except ValueError:
  3472. try:
  3473. tools_string = self.defaults[dim].split(",")
  3474. tools_diameters = [eval(a) for a in tools_string if a != '']
  3475. except Exception as e:
  3476. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3477. continue
  3478. self.defaults[dim] = ''
  3479. td_len = len(tools_diameters)
  3480. if td_len > 1:
  3481. for t in range(td_len):
  3482. tools_diameters[t] *= sfactor
  3483. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3484. else:
  3485. tools_diameters[0] *= sfactor
  3486. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3487. elif dim in ['global_gridx', 'global_gridy']:
  3488. # format the number of decimals to the one specified in self.decimals
  3489. try:
  3490. val = float(self.defaults[dim]) * sfactor
  3491. except Exception as e:
  3492. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3493. continue
  3494. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3495. else:
  3496. # the number of decimals for the rest is kept unchanged
  3497. if self.defaults[dim]:
  3498. try:
  3499. val = float(self.defaults[dim]) * sfactor
  3500. except Exception as e:
  3501. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3502. continue
  3503. self.defaults[dim] = val
  3504. # The scaling factor depending on choice of units.
  3505. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3506. # Changing project units. Warn user.
  3507. msgbox = QtWidgets.QMessageBox()
  3508. msgbox.setWindowTitle(_("Toggle Units"))
  3509. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3510. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3511. msgbox.setText(_("Changing the units of the project\n"
  3512. "will scale all objects.\n\n"
  3513. "Do you want to continue?"))
  3514. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3515. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3516. msgbox.setDefaultButton(bt_ok)
  3517. msgbox.exec_()
  3518. response = msgbox.clickedButton()
  3519. if response == bt_ok:
  3520. if no_pref is False:
  3521. self.preferencesUiManager.defaults_read_form()
  3522. scale_defaults(factor)
  3523. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3524. self.defaults["units"] = new_units
  3525. # update the defaults from form, some may assume that the conversion is enough and it's not
  3526. self.on_options_app2project()
  3527. # update the objects
  3528. for obj in self.collection.get_list():
  3529. obj.convert_units(new_units)
  3530. # make that the properties stored in the object are also updated
  3531. self.app_obj.object_changed.emit(obj)
  3532. # rebuild the object UI
  3533. obj.build_ui()
  3534. # change this only if the workspace is active
  3535. if self.defaults['global_workspace'] is True:
  3536. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3537. # adjust the grid values on the main toolbar
  3538. val_x = float(self.defaults['global_gridx']) * factor
  3539. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3540. current = self.collection.get_active()
  3541. if current is not None:
  3542. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3543. if not isinstance(current, GeometryObject):
  3544. current.to_form()
  3545. # replot all objects
  3546. self.plot_all()
  3547. # set the status labels to reflect the current FlatCAM units
  3548. self.set_screen_units(new_units)
  3549. # signal to the app that we changed the object properties and it should save the project
  3550. self.should_we_save = True
  3551. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3552. else:
  3553. # Undo toggling
  3554. self.toggle_units_ignore = True
  3555. if self.defaults['units'].upper() == 'MM':
  3556. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3557. else:
  3558. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3559. self.toggle_units_ignore = False
  3560. # store the grid values so they are not changed in the next step
  3561. val_x = float(self.defaults['global_gridx'])
  3562. val_y = float(self.defaults['global_gridy'])
  3563. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3564. self.preferencesUiManager.defaults_read_form()
  3565. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3566. # in self.defaults from the GUI elements but
  3567. # I don't want it for the grid values, so I update them here
  3568. self.defaults['global_gridx'] = val_x
  3569. self.defaults['global_gridy'] = val_y
  3570. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3571. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3572. def on_deselect_all(self):
  3573. self.collection.set_all_inactive()
  3574. self.delete_selection_shape()
  3575. def on_workspace_modified(self):
  3576. # self.save_defaults(silent=True)
  3577. self.plotcanvas.delete_workspace()
  3578. self.preferencesUiManager.defaults_read_form()
  3579. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3580. def on_workspace(self):
  3581. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3582. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3583. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3584. else:
  3585. self.plotcanvas.delete_workspace()
  3586. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3587. self.preferencesUiManager.defaults_read_form()
  3588. # self.save_defaults(silent=True)
  3589. def on_workspace_toggle(self):
  3590. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3591. try:
  3592. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3593. except TypeError:
  3594. pass
  3595. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3596. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3597. self.on_workspace()
  3598. def on_cursor_type(self, val):
  3599. """
  3600. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3601. :return: None
  3602. """
  3603. self.app_cursor.enabled = False
  3604. if val == 'small':
  3605. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3606. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3607. self.app_cursor = self.plotcanvas.new_cursor()
  3608. else:
  3609. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3610. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3611. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3612. if self.ui.grid_snap_btn.isChecked():
  3613. self.app_cursor.enabled = True
  3614. else:
  3615. self.app_cursor.enabled = False
  3616. def on_tool_add_keypress(self):
  3617. # ## Current application units in Upper Case
  3618. self.units = self.defaults['units'].upper()
  3619. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3620. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3621. if notebook_widget_name == 'selected_tab':
  3622. if self.collection.get_active().kind == 'geometry':
  3623. # Tool add works for Geometry only if Advanced is True in Preferences
  3624. if self.defaults["global_app_level"] == 'a':
  3625. tool_add_popup = FCInputDialog(title="New Tool ...",
  3626. text='Enter a Tool Diameter:',
  3627. min=0.0000, max=99.9999, decimals=4)
  3628. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3629. val, ok = tool_add_popup.get_value()
  3630. if ok:
  3631. if float(val) == 0:
  3632. self.inform.emit('[WARNING_NOTCL] %s' %
  3633. _("Please enter a tool diameter with non-zero value, in Float format."))
  3634. return
  3635. self.collection.get_active().on_tool_add(dia=float(val))
  3636. else:
  3637. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3638. else:
  3639. msgbox = QtWidgets.QMessageBox()
  3640. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3641. "Go to Preferences -> General - Show Advanced Options."))
  3642. msgbox.setWindowTitle("Tool adding ...")
  3643. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3644. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3645. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3646. msgbox.setDefaultButton(bt_ok)
  3647. msgbox.exec_()
  3648. # work only if the notebook tab on focus is the Tools_Tab
  3649. if notebook_widget_name == 'tool_tab':
  3650. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3651. # and only if the tool is NCC Tool
  3652. if tool_widget == self.ncclear_tool.toolName:
  3653. self.ncclear_tool.on_add_tool_by_key()
  3654. # and only if the tool is Paint Area Tool
  3655. elif tool_widget == self.paint_tool.toolName:
  3656. self.paint_tool.on_add_tool_by_key()
  3657. # and only if the tool is Solder Paste Dispensing Tool
  3658. elif tool_widget == self.paste_tool.toolName:
  3659. self.paste_tool.on_add_tool_by_key()
  3660. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3661. # See description below.
  3662. def on_delete_keypress(self):
  3663. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3664. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3665. if notebook_widget_name == 'selected_tab':
  3666. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3667. self.collection.get_active().on_tool_delete()
  3668. # work only if the notebook tab on focus is the Tools_Tab
  3669. elif notebook_widget_name == 'tool_tab':
  3670. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3671. # and only if the tool is NCC Tool
  3672. if tool_widget == self.ncclear_tool.toolName:
  3673. self.ncclear_tool.on_tool_delete()
  3674. # and only if the tool is Paint Tool
  3675. elif tool_widget == self.paint_tool.toolName:
  3676. self.paint_tool.on_tool_delete()
  3677. # and only if the tool is Solder Paste Dispensing Tool
  3678. elif tool_widget == self.paste_tool.toolName:
  3679. self.paste_tool.on_tool_delete()
  3680. # and only if the tool is Isolation Tool
  3681. elif tool_widget == self.isolation_tool.toolName:
  3682. self.isolation_tool.on_tool_delete()
  3683. else:
  3684. self.on_delete()
  3685. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3686. # some screens you have to be careful where you hover with your mouse.
  3687. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3688. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3689. # Complicated, I know :)
  3690. def on_delete(self, force_deletion=False):
  3691. """
  3692. Delete the currently selected FlatCAMObjs.
  3693. :param force_deletion: used by Tcl command
  3694. :return: None
  3695. """
  3696. self.defaults.report_usage("on_delete()")
  3697. response = None
  3698. bt_ok = None
  3699. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3700. # a geometry object before we update it.
  3701. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3702. and self.grb_editor.editor_active is False and self.gcode_editor.editor_active is False:
  3703. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3704. msgbox = QtWidgets.QMessageBox()
  3705. msgbox.setWindowTitle(_("Delete objects"))
  3706. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3707. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3708. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3709. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3710. "the selected objects?"))
  3711. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3712. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3713. msgbox.setDefaultButton(bt_ok)
  3714. msgbox.exec_()
  3715. response = msgbox.clickedButton()
  3716. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3717. response = bt_ok
  3718. if response == bt_ok:
  3719. if self.collection.get_active():
  3720. self.log.debug("App.on_delete()")
  3721. for obj_active in self.collection.get_selected():
  3722. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3723. if obj_active.kind == 'gerber':
  3724. obj_active.mark_shapes_storage.clear()
  3725. obj_active.mark_shapes.clear(update=True)
  3726. obj_active.mark_shapes.enabled = False
  3727. elif obj_active.kind == 'cncjob':
  3728. try:
  3729. obj_active.text_col.enabled = False
  3730. del obj_active.text_col
  3731. obj_active.annotation.clear(update=True)
  3732. del obj_active.annotation
  3733. except AttributeError as e:
  3734. log.debug(
  3735. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3736. )
  3737. while self.collection.get_selected():
  3738. self.delete_first_selected()
  3739. # make sure that the selection shape is deleted, too
  3740. self.delete_selection_shape()
  3741. # if there are no longer objects delete also the exclusion areas shapes
  3742. if not self.collection.get_list():
  3743. self.exc_areas.clear_shapes()
  3744. self.inform.emit('%s...' % _("Object(s) deleted"))
  3745. else:
  3746. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3747. else:
  3748. self.inform.emit(_("Save the work in Editor and try again ..."))
  3749. def delete_first_selected(self):
  3750. # Keep this for later
  3751. try:
  3752. sel_obj = self.collection.get_active()
  3753. name = sel_obj.options["name"]
  3754. isPlotted = sel_obj.options["plot"]
  3755. except AttributeError:
  3756. self.log.debug("Nothing selected for deletion")
  3757. return
  3758. if self.is_legacy is True:
  3759. # Remove plot only if the object was plotted otherwise delaxes will fail
  3760. if isPlotted:
  3761. try:
  3762. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3763. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3764. except Exception as e:
  3765. log.debug("App.delete_first_selected() --> %s" % str(e))
  3766. self.plotcanvas.auto_adjust_axes()
  3767. # Remove from dictionary
  3768. self.collection.delete_active()
  3769. # Clear form
  3770. self.setup_component_editor()
  3771. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3772. def on_set_origin(self):
  3773. """
  3774. Set the origin to the left mouse click position
  3775. :return: None
  3776. """
  3777. # display the message for the user
  3778. # and ask him to click on the desired position
  3779. self.defaults.report_usage("on_set_origin()")
  3780. def origin_replot():
  3781. def worker_task():
  3782. with self.proc_container.new('%s...' % _("Plotting")):
  3783. for obj in self.collection.get_list():
  3784. obj.plot()
  3785. self.plotcanvas.fit_view()
  3786. if self.is_legacy:
  3787. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3788. else:
  3789. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3790. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3791. self.inform.emit(_('Click to set the origin ...'))
  3792. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3793. # first disconnect it as it may have been used by something else
  3794. try:
  3795. self.replot_signal.disconnect()
  3796. except TypeError:
  3797. pass
  3798. self.replot_signal[list].connect(origin_replot)
  3799. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3800. """
  3801. :param event:
  3802. :param location:
  3803. :param noplot:
  3804. :param use_thread:
  3805. :return:
  3806. """
  3807. noplot_sig = noplot
  3808. def worker_task():
  3809. with self.proc_container.new(_("Setting Origin...")):
  3810. obj_list = self.collection.get_list()
  3811. for obj in obj_list:
  3812. obj.offset((x, y))
  3813. self.app_obj.object_changed.emit(obj)
  3814. # Update the object bounding box options
  3815. a, b, c, d = obj.bounds()
  3816. obj.options['xmin'] = a
  3817. obj.options['ymin'] = b
  3818. obj.options['xmax'] = c
  3819. obj.options['ymax'] = d
  3820. self.inform.emit('[success] %s...' % _('Origin set'))
  3821. for obj in obj_list:
  3822. out_name = obj.options["name"]
  3823. if obj.kind == 'gerber':
  3824. obj.source_file = self.export_gerber(
  3825. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3826. elif obj.kind == 'excellon':
  3827. obj.source_file = self.export_excellon(
  3828. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3829. if noplot_sig is False:
  3830. self.replot_signal.emit([])
  3831. if location is not None:
  3832. if len(location) != 2:
  3833. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3834. return 'fail'
  3835. x, y = location
  3836. if use_thread is True:
  3837. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3838. else:
  3839. worker_task()
  3840. self.should_we_save = True
  3841. return
  3842. if event is not None and event.button == 1:
  3843. if self.is_legacy is False:
  3844. event_pos = event.pos
  3845. else:
  3846. event_pos = (event.xdata, event.ydata)
  3847. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3848. if self.grid_status():
  3849. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3850. else:
  3851. pos = pos_canvas
  3852. x = 0 - pos[0]
  3853. y = 0 - pos[1]
  3854. if use_thread is True:
  3855. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3856. else:
  3857. worker_task()
  3858. self.should_we_save = True
  3859. def on_move2origin(self, use_thread=True):
  3860. """
  3861. Move selected objects to origin.
  3862. :param use_thread: Control if to use threaded operation. Boolean.
  3863. :return:
  3864. """
  3865. def worker_task():
  3866. with self.proc_container.new(_("Moving to Origin...")):
  3867. obj_list = self.collection.get_selected()
  3868. if not obj_list:
  3869. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3870. return
  3871. xminlist = []
  3872. yminlist = []
  3873. # first get a bounding box to fit all
  3874. for obj in obj_list:
  3875. xmin, ymin, xmax, ymax = obj.bounds()
  3876. xminlist.append(xmin)
  3877. yminlist.append(ymin)
  3878. # get the minimum x,y for all objects selected
  3879. x = min(xminlist)
  3880. y = min(yminlist)
  3881. for obj in obj_list:
  3882. obj.offset((-x, -y))
  3883. self.app_obj.object_changed.emit(obj)
  3884. # Update the object bounding box options
  3885. a, b, c, d = obj.bounds()
  3886. obj.options['xmin'] = a
  3887. obj.options['ymin'] = b
  3888. obj.options['xmax'] = c
  3889. obj.options['ymax'] = d
  3890. for obj in obj_list:
  3891. obj.plot()
  3892. for obj in obj_list:
  3893. out_name = obj.options["name"]
  3894. if obj.kind == 'gerber':
  3895. obj.source_file = self.export_gerber(
  3896. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3897. elif obj.kind == 'excellon':
  3898. obj.source_file = self.export_excellon(
  3899. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3900. self.inform.emit('[success] %s...' % _('Origin set'))
  3901. if use_thread is True:
  3902. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3903. else:
  3904. worker_task()
  3905. self.should_we_save = True
  3906. def on_jump_to(self, custom_location=None, fit_center=True):
  3907. """
  3908. Jump to a location by setting the mouse cursor location.
  3909. :param custom_location: Jump to a specified point. (x, y) tuple.
  3910. :param fit_center: If to fit view. Boolean.
  3911. :return:
  3912. """
  3913. self.defaults.report_usage("on_jump_to()")
  3914. if not custom_location:
  3915. dia_box_location = None
  3916. try:
  3917. dia_box_location = eval(self.clipboard.text())
  3918. except Exception:
  3919. pass
  3920. if type(dia_box_location) == tuple:
  3921. dia_box_location = str(dia_box_location)
  3922. else:
  3923. dia_box_location = None
  3924. # dia_box = Dialog_box(title=_("Jump to ..."),
  3925. # label=_("Enter the coordinates in format X,Y:"),
  3926. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3927. # initial_text=dia_box_location)
  3928. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3929. label=_("Enter the coordinates in format X,Y:"),
  3930. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3931. initial_text=dia_box_location,
  3932. reference=self.defaults['global_jump_ref'])
  3933. if dia_box.ok is True:
  3934. try:
  3935. location = eval(dia_box.location)
  3936. if not isinstance(location, tuple):
  3937. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3938. return
  3939. if dia_box.reference == 'rel':
  3940. rel_x = self.mouse[0] + location[0]
  3941. rel_y = self.mouse[1] + location[1]
  3942. location = (rel_x, rel_y)
  3943. self.defaults['global_jump_ref'] = dia_box.reference
  3944. except Exception:
  3945. return
  3946. else:
  3947. return
  3948. else:
  3949. location = custom_location
  3950. self.jump_signal.emit(location)
  3951. if fit_center:
  3952. self.plotcanvas.fit_center(loc=location)
  3953. cursor = QtGui.QCursor()
  3954. if self.is_legacy is False:
  3955. # I don't know where those differences come from but they are constant for the current
  3956. # execution of the application and they are multiples of a value around 0.0263mm.
  3957. # In a random way sometimes they are more sometimes they are less
  3958. # if units == 'MM':
  3959. # cal_factor = 0.0263
  3960. # else:
  3961. # cal_factor = 0.0263 / 25.4
  3962. cal_location = (location[0], location[1])
  3963. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3964. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3965. j_pos = (
  3966. int(canvas_origin.x() + round(jump_loc[0])),
  3967. int(canvas_origin.y() + round(jump_loc[1]))
  3968. )
  3969. cursor.setPos(j_pos[0], j_pos[1])
  3970. else:
  3971. # find the canvas origin which is in the top left corner
  3972. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3973. # determine the coordinates for the lowest left point of the canvas
  3974. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3975. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3976. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3977. # canvas) and the point (width, height) is in the top-right location
  3978. loc = self.plotcanvas.axes.transData.transform_point(location)
  3979. j_pos = (
  3980. int(x0 + loc[0]),
  3981. int(y0 - loc[1])
  3982. )
  3983. cursor.setPos(j_pos[0], j_pos[1])
  3984. self.plotcanvas.mouse = [location[0], location[1]]
  3985. if self.defaults["global_cursor_color_enabled"] is True:
  3986. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3987. else:
  3988. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3989. if self.grid_status():
  3990. # Update cursor
  3991. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3992. symbol='++', edge_color=self.cursor_color_3D,
  3993. edge_width=self.defaults["global_cursor_width"],
  3994. size=self.defaults["global_cursor_size"])
  3995. # Set the relative position label
  3996. dx = location[0] - float(self.rel_point1[0])
  3997. dy = location[1] - float(self.rel_point1[1])
  3998. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3999. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4000. # Set the position label
  4001. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4002. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4003. units = self.defaults["units"].lower()
  4004. self.plotcanvas.text_hud.text = \
  4005. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4006. dx, units, dy, units, location[0], units, location[1], units)
  4007. self.inform.emit('[success] %s' % _("Done."))
  4008. return location
  4009. def on_locate(self, obj, fit_center=True):
  4010. """
  4011. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4012. :param obj: The object on which to locate certain points
  4013. :param fit_center: If to fit view. Boolean.
  4014. :return: A point location. (x, y) tuple.
  4015. """
  4016. self.defaults.report_usage("on_locate()")
  4017. if obj is None:
  4018. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4019. return 'fail'
  4020. class DialogBoxChoice(QtWidgets.QDialog):
  4021. def __init__(self, title=None, icon=None, choice='bl'):
  4022. """
  4023. :param title: string with the window title
  4024. """
  4025. super(DialogBoxChoice, self).__init__()
  4026. self.ok = False
  4027. self.setWindowIcon(icon)
  4028. self.setWindowTitle(str(title))
  4029. self.form = QtWidgets.QFormLayout(self)
  4030. self.ref_radio = RadioSet([
  4031. {"label": _("Bottom-Left"), "value": "bl"},
  4032. {"label": _("Top-Left"), "value": "tl"},
  4033. {"label": _("Bottom-Right"), "value": "br"},
  4034. {"label": _("Top-Right"), "value": "tr"},
  4035. {"label": _("Center"), "value": "c"}
  4036. ], orientation='vertical', stretch=False)
  4037. self.ref_radio.set_value(choice)
  4038. self.form.addRow(self.ref_radio)
  4039. self.button_box = QtWidgets.QDialogButtonBox(
  4040. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4041. Qt.Horizontal, parent=self)
  4042. self.form.addRow(self.button_box)
  4043. self.button_box.accepted.connect(self.accept)
  4044. self.button_box.rejected.connect(self.reject)
  4045. if self.exec_() == QtWidgets.QDialog.Accepted:
  4046. self.ok = True
  4047. self.location_point = self.ref_radio.get_value()
  4048. else:
  4049. self.ok = False
  4050. self.location_point = None
  4051. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4052. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4053. choice=self.defaults['global_locate_pt'])
  4054. if dia_box.ok is True:
  4055. try:
  4056. location_point = dia_box.location_point
  4057. self.defaults['global_locate_pt'] = dia_box.location_point
  4058. except Exception:
  4059. return
  4060. else:
  4061. return
  4062. loc_b = obj.bounds()
  4063. if location_point == 'bl':
  4064. location = (loc_b[0], loc_b[1])
  4065. elif location_point == 'tl':
  4066. location = (loc_b[0], loc_b[3])
  4067. elif location_point == 'br':
  4068. location = (loc_b[2], loc_b[1])
  4069. elif location_point == 'tr':
  4070. location = (loc_b[2], loc_b[3])
  4071. else:
  4072. # center
  4073. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4074. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4075. location = (cx, cy)
  4076. self.locate_signal.emit(location, location_point)
  4077. if fit_center:
  4078. self.plotcanvas.fit_center(loc=location)
  4079. cursor = QtGui.QCursor()
  4080. if self.is_legacy is False:
  4081. # I don't know where those differences come from but they are constant for the current
  4082. # execution of the application and they are multiples of a value around 0.0263mm.
  4083. # In a random way sometimes they are more sometimes they are less
  4084. # if units == 'MM':
  4085. # cal_factor = 0.0263
  4086. # else:
  4087. # cal_factor = 0.0263 / 25.4
  4088. cal_location = (location[0], location[1])
  4089. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4090. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4091. j_pos = (
  4092. int(canvas_origin.x() + round(jump_loc[0])),
  4093. int(canvas_origin.y() + round(jump_loc[1]))
  4094. )
  4095. cursor.setPos(j_pos[0], j_pos[1])
  4096. else:
  4097. # find the canvas origin which is in the top left corner
  4098. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4099. # determine the coordinates for the lowest left point of the canvas
  4100. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4101. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4102. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4103. # canvas) and the point (width, height) is in the top-right location
  4104. loc = self.plotcanvas.axes.transData.transform_point(location)
  4105. j_pos = (
  4106. int(x0 + loc[0]),
  4107. int(y0 - loc[1])
  4108. )
  4109. cursor.setPos(j_pos[0], j_pos[1])
  4110. self.plotcanvas.mouse = [location[0], location[1]]
  4111. if self.defaults["global_cursor_color_enabled"] is True:
  4112. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4113. else:
  4114. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4115. if self.grid_status():
  4116. # Update cursor
  4117. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4118. symbol='++', edge_color=self.cursor_color_3D,
  4119. edge_width=self.defaults["global_cursor_width"],
  4120. size=self.defaults["global_cursor_size"])
  4121. # Set the relative position label
  4122. self.dx = location[0] - float(self.rel_point1[0])
  4123. self.dy = location[1] - float(self.rel_point1[1])
  4124. # Set the position label
  4125. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4126. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4127. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4128. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4129. units = self.defaults["units"].lower()
  4130. self.plotcanvas.text_hud.text = \
  4131. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4132. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4133. self.inform.emit('[success] %s' % _("Done."))
  4134. return location
  4135. def on_copy_command(self):
  4136. """
  4137. Will copy a selection of objects, creating new objects.
  4138. :return:
  4139. """
  4140. self.defaults.report_usage("on_copy_command()")
  4141. def initialize(obj_init, app):
  4142. """
  4143. :param obj_init: the new object
  4144. :type obj_init: class
  4145. :param app: An instance of the App class
  4146. :type app: App
  4147. :return: None
  4148. :rtype:
  4149. """
  4150. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4151. try:
  4152. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4153. except AttributeError:
  4154. pass
  4155. try:
  4156. obj_init.apertures = deepcopy(obj.apertures)
  4157. except AttributeError:
  4158. pass
  4159. try:
  4160. if obj.tools:
  4161. obj_init.tools = deepcopy(obj.tools)
  4162. except Exception as err:
  4163. log.debug("App.on_copy_command() --> %s" % str(err))
  4164. try:
  4165. obj_init.source_file = deepcopy(obj.source_file)
  4166. except (AttributeError, TypeError):
  4167. pass
  4168. def initialize_excellon(obj_init, app):
  4169. obj_init.source_file = deepcopy(obj.source_file)
  4170. obj_init.tools = deepcopy(obj.tools)
  4171. # drills are offset, so they need to be deep copied
  4172. obj_init.drills = deepcopy(obj.drills)
  4173. # slots are offset, so they need to be deep copied
  4174. obj_init.slots = deepcopy(obj.slots)
  4175. obj_init.create_geometry()
  4176. def initialize_script(obj_init, app_obj):
  4177. obj_init.source_file = deepcopy(obj.source_file)
  4178. def initialize_document(obj_init, app_obj):
  4179. obj_init.source_file = deepcopy(obj.source_file)
  4180. for obj in self.collection.get_selected():
  4181. obj_name = obj.options["name"]
  4182. try:
  4183. if isinstance(obj, ExcellonObject):
  4184. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4185. elif isinstance(obj, GerberObject):
  4186. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4187. elif isinstance(obj, GeometryObject):
  4188. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4189. elif isinstance(obj, ScriptObject):
  4190. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4191. elif isinstance(obj, DocumentObject):
  4192. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4193. except Exception as e:
  4194. return "Operation failed: %s" % str(e)
  4195. def on_copy_object2(self, custom_name):
  4196. def initialize_geometry(obj_init, app):
  4197. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4198. try:
  4199. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4200. except AttributeError:
  4201. pass
  4202. try:
  4203. obj_init.apertures = deepcopy(obj.apertures)
  4204. except AttributeError:
  4205. pass
  4206. try:
  4207. if obj.tools:
  4208. obj_init.tools = deepcopy(obj.tools)
  4209. except Exception as ee:
  4210. log.debug("on_copy_object2() --> %s" % str(ee))
  4211. def initialize_gerber(obj_init, app):
  4212. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4213. obj_init.apertures = deepcopy(obj.apertures)
  4214. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4215. def initialize_excellon(obj_init, app):
  4216. obj_init.tools = deepcopy(obj.tools)
  4217. # drills are offset, so they need to be deep copied
  4218. obj_init.drills = deepcopy(obj.drills)
  4219. # slots are offset, so they need to be deep copied
  4220. obj_init.slots = deepcopy(obj.slots)
  4221. obj_init.create_geometry()
  4222. for obj in self.collection.get_selected():
  4223. obj_name = obj.options["name"]
  4224. try:
  4225. if isinstance(obj, ExcellonObject):
  4226. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4227. elif isinstance(obj, GerberObject):
  4228. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4229. elif isinstance(obj, GeometryObject):
  4230. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4231. except Exception as er:
  4232. return "Operation failed: %s" % str(er)
  4233. def on_rename_object(self, text):
  4234. """
  4235. Will rename an object.
  4236. :param text: New name for the object.
  4237. :return:
  4238. """
  4239. self.defaults.report_usage("on_rename_object()")
  4240. named_obj = self.collection.get_active()
  4241. for obj in named_obj:
  4242. if obj is list:
  4243. self.on_rename_object(text)
  4244. else:
  4245. try:
  4246. obj.options['name'] = text
  4247. except Exception as e:
  4248. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4249. def convert_any2geo(self):
  4250. """
  4251. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4252. :return:
  4253. """
  4254. self.defaults.report_usage("convert_any2geo()")
  4255. def initialize(obj_init, app):
  4256. obj_init.solid_geometry = obj.solid_geometry
  4257. try:
  4258. obj_init.follow_geometry = obj.follow_geometry
  4259. except AttributeError:
  4260. pass
  4261. try:
  4262. obj_init.apertures = obj.apertures
  4263. except AttributeError:
  4264. pass
  4265. try:
  4266. if obj.tools:
  4267. obj_init.tools = obj.tools
  4268. except AttributeError:
  4269. pass
  4270. def initialize_excellon(obj_init, app):
  4271. # objs = self.collection.get_selected()
  4272. # GeometryObject.merge(objs, obj)
  4273. solid_geo = []
  4274. for tool in obj.tools:
  4275. for geo in obj.tools[tool]['solid_geometry']:
  4276. solid_geo.append(geo)
  4277. obj_init.solid_geometry = deepcopy(solid_geo)
  4278. if not self.collection.get_selected():
  4279. log.warning("App.convert_any2geo --> No object selected")
  4280. self.inform.emit('[WARNING_NOTCL] %s' %
  4281. _("No object is selected. Select an object and try again."))
  4282. return
  4283. for obj in self.collection.get_selected():
  4284. obj_name = obj.options["name"]
  4285. try:
  4286. if obj.kind == 'excellon':
  4287. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4288. else:
  4289. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4290. except Exception as e:
  4291. return "Operation failed: %s" % str(e)
  4292. def convert_any2gerber(self):
  4293. """
  4294. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4295. :return:
  4296. """
  4297. def initialize_geometry(obj_init, app):
  4298. apertures = {}
  4299. apid = 0
  4300. apertures[str(apid)] = {}
  4301. apertures[str(apid)]['geometry'] = []
  4302. for obj_orig in obj.solid_geometry:
  4303. new_elem = {}
  4304. new_elem['solid'] = obj_orig
  4305. try:
  4306. new_elem['follow'] = obj_orig.exterior
  4307. except AttributeError:
  4308. pass
  4309. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4310. apertures[str(apid)]['size'] = 0.0
  4311. apertures[str(apid)]['type'] = 'C'
  4312. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4313. obj_init.apertures = deepcopy(apertures)
  4314. def initialize_excellon(obj_init, app):
  4315. apertures = {}
  4316. apid = 10
  4317. for tool in obj.tools:
  4318. apertures[str(apid)] = {}
  4319. apertures[str(apid)]['geometry'] = []
  4320. for geo in obj.tools[tool]['solid_geometry']:
  4321. new_el = {}
  4322. new_el['solid'] = geo
  4323. new_el['follow'] = geo.exterior
  4324. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4325. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4326. apertures[str(apid)]['type'] = 'C'
  4327. apid += 1
  4328. # create solid_geometry
  4329. solid_geometry = []
  4330. for apid in apertures:
  4331. for geo_el in apertures[apid]['geometry']:
  4332. solid_geometry.append(geo_el['solid'])
  4333. solid_geometry = MultiPolygon(solid_geometry)
  4334. solid_geometry = solid_geometry.buffer(0.0000001)
  4335. obj_init.solid_geometry = deepcopy(solid_geometry)
  4336. obj_init.apertures = deepcopy(apertures)
  4337. # clear the working objects (perhaps not necessary due of Python GC)
  4338. apertures.clear()
  4339. if not self.collection.get_selected():
  4340. log.warning("App.convert_any2gerber --> No object selected")
  4341. self.inform.emit('[WARNING_NOTCL] %s' %
  4342. _("No object is selected. Select an object and try again."))
  4343. return
  4344. for obj in self.collection.get_selected():
  4345. obj_name = obj.options["name"]
  4346. try:
  4347. if obj.kind == 'excellon':
  4348. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4349. elif obj.kind == 'geometry':
  4350. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4351. else:
  4352. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4353. except Exception as e:
  4354. return "Operation failed: %s" % str(e)
  4355. def convert_any2excellon(self):
  4356. """
  4357. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4358. :return:
  4359. """
  4360. def initialize_geometry(obj_init, app):
  4361. tools = {}
  4362. tooluid = 1
  4363. obj_init.solid_geometry = []
  4364. for geo in obj.solid_geometry:
  4365. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4366. continue
  4367. minx, miny, maxx, maxy = geo.bounds
  4368. new_dia = min([maxx-minx, maxy-miny])
  4369. new_drill = geo.centroid
  4370. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4371. current_tooldias = []
  4372. if tools:
  4373. for tool in tools:
  4374. if tools[tool] and 'tooldia' in tools[tool]:
  4375. current_tooldias.append(tools[tool]['tooldia'])
  4376. if new_dia in current_tooldias:
  4377. for tool in tools:
  4378. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float('%.*f' % (self.decimals,
  4379. new_dia)):
  4380. tools[tool]['drills'].append(new_drill)
  4381. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4382. else:
  4383. tools[tooluid] = {}
  4384. tools[tooluid]['tooldia'] = new_dia
  4385. tools[tooluid]['drills'] = [new_drill]
  4386. tools[tooluid]['slots'] = []
  4387. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4388. tooluid += 1
  4389. try:
  4390. obj_init.solid_geometry.append(new_drill_geo)
  4391. except (TypeError, AttributeError):
  4392. obj_init.solid_geometry = [new_drill_geo]
  4393. obj_init.tools = deepcopy(tools)
  4394. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4395. def initialize_gerber(obj_init, app):
  4396. tools = {}
  4397. tooluid = 1
  4398. obj_init.solid_geometry = []
  4399. for apid in obj.apertures:
  4400. if 'geometry' in obj.apertures[apid]:
  4401. for geo_dict in obj.apertures[apid]['geometry']:
  4402. if 'follow' in geo_dict:
  4403. if isinstance(geo_dict['follow'], Point):
  4404. geo = geo_dict['solid']
  4405. minx, miny, maxx, maxy = geo.bounds
  4406. new_dia = min([maxx - minx, maxy - miny])
  4407. new_drill = geo.centroid
  4408. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4409. current_tooldias = []
  4410. if tools:
  4411. for tool in tools:
  4412. if tools[tool] and 'tooldia' in tools[tool]:
  4413. current_tooldias.append(
  4414. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4415. )
  4416. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4417. for tool in tools:
  4418. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4419. '%.*f' % (self.decimals, new_dia)):
  4420. if new_drill not in tools[tool]['drills']:
  4421. tools[tool]['drills'].append(new_drill)
  4422. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4423. else:
  4424. tools[tooluid] = {}
  4425. tools[tooluid]['tooldia'] = new_dia
  4426. tools[tooluid]['drills'] = [new_drill]
  4427. tools[tooluid]['slots'] = []
  4428. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4429. tooluid += 1
  4430. try:
  4431. obj_init.solid_geometry.append(new_drill_geo)
  4432. except (TypeError, AttributeError):
  4433. obj_init.solid_geometry = [new_drill_geo]
  4434. elif isinstance(geo_dict['follow'], LineString):
  4435. geo_coords = list(geo_dict['follow'].coords)
  4436. # slots can have only a start and stop point and no intermediate points
  4437. if len(geo_coords) != 2:
  4438. continue
  4439. geo = geo_dict['solid']
  4440. try:
  4441. new_dia = obj.apertures[apid]['size']
  4442. except Exception:
  4443. continue
  4444. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4445. new_slot_geo = geo
  4446. current_tooldias = []
  4447. if tools:
  4448. for tool in tools:
  4449. if tools[tool] and 'tooldia' in tools[tool]:
  4450. current_tooldias.append(
  4451. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4452. )
  4453. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4454. for tool in tools:
  4455. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4456. '%.*f' % (self.decimals, new_dia)):
  4457. if new_slot not in tools[tool]['slots']:
  4458. tools[tool]['slots'].append(new_slot)
  4459. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4460. else:
  4461. tools[tooluid] = {}
  4462. tools[tooluid]['tooldia'] = new_dia
  4463. tools[tooluid]['drills'] = []
  4464. tools[tooluid]['slots'] = [new_slot]
  4465. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4466. tooluid += 1
  4467. try:
  4468. obj_init.solid_geometry.append(new_slot_geo)
  4469. except (TypeError, AttributeError):
  4470. obj_init.solid_geometry = [new_slot_geo]
  4471. obj_init.tools = deepcopy(tools)
  4472. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4473. if not self.collection.get_selected():
  4474. log.warning("App.convert_any2excellon--> No object selected")
  4475. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4476. return
  4477. for obj in self.collection.get_selected():
  4478. obj_name = obj.options["name"]
  4479. try:
  4480. if obj.kind == 'gerber':
  4481. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4482. elif obj.kind == 'geometry':
  4483. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4484. else:
  4485. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4486. except Exception as e:
  4487. return "Operation failed: %s" % str(e)
  4488. def abort_all_tasks(self):
  4489. """
  4490. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4491. on the first possible occasion.
  4492. :return:
  4493. """
  4494. if self.abort_flag is False:
  4495. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4496. self.abort_flag = True
  4497. self.cleanup.emit()
  4498. def app_is_idle(self):
  4499. if self.abort_flag:
  4500. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4501. self.abort_flag = False
  4502. def on_selectall(self):
  4503. """
  4504. Will draw a selection box shape around the selected objects.
  4505. :return:
  4506. """
  4507. self.defaults.report_usage("on_selectall()")
  4508. # delete the possible selection box around a possible selected object
  4509. self.delete_selection_shape()
  4510. for name in self.collection.get_names():
  4511. self.collection.set_active(name)
  4512. curr_sel_obj = self.collection.get_by_name(name)
  4513. # create the selection box around the selected object
  4514. if self.defaults['global_selection_shape'] is True:
  4515. self.draw_selection_shape(curr_sel_obj)
  4516. def on_toggle_preferences(self):
  4517. pref_open = False
  4518. for idx in range(self.ui.plot_tab_area.count()):
  4519. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4520. pref_open = True
  4521. if pref_open:
  4522. for idx in range(self.ui.plot_tab_area.count()):
  4523. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4524. self.ui.plot_tab_area.removeTab(idx)
  4525. break
  4526. self.ui.pref_status_label.setStyleSheet("")
  4527. else:
  4528. self.on_preferences()
  4529. def on_preferences(self):
  4530. """
  4531. Adds the Preferences in a Tab in Plot Area
  4532. :return:
  4533. """
  4534. # add the tab if it was closed
  4535. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4536. # delete the absolute and relative position and messages in the infobar
  4537. # self.ui.position_label.setText("")
  4538. # self.ui.rel_position_label.setText("")
  4539. # hide coordinates toolbars in the infobar while in DB
  4540. self.ui.coords_toolbar.hide()
  4541. self.ui.delta_coords_toolbar.hide()
  4542. # Switch plot_area to preferences page
  4543. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4544. # self.ui.show()
  4545. self.ui.pref_status_label.setStyleSheet("""
  4546. QLabel
  4547. {
  4548. color: black;
  4549. background-color: lightseagreen;
  4550. }
  4551. """
  4552. )
  4553. # detect changes in the preferences
  4554. for idx in range(self.ui.pref_tab_area.count()):
  4555. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4556. try:
  4557. try:
  4558. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4559. except (TypeError, AttributeError):
  4560. pass
  4561. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4562. except AttributeError:
  4563. pass
  4564. try:
  4565. try:
  4566. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4567. except (TypeError, AttributeError):
  4568. pass
  4569. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4570. except AttributeError:
  4571. pass
  4572. try:
  4573. try:
  4574. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4575. except (TypeError, AttributeError):
  4576. pass
  4577. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4578. except AttributeError:
  4579. pass
  4580. try:
  4581. try:
  4582. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4583. except (TypeError, AttributeError):
  4584. pass
  4585. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4586. except AttributeError:
  4587. pass
  4588. try:
  4589. try:
  4590. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4591. except (TypeError, AttributeError):
  4592. pass
  4593. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4594. except AttributeError:
  4595. pass
  4596. def on_tools_database(self, source='app'):
  4597. """
  4598. Adds the Tools Database in a Tab in Plot Area.
  4599. :return:
  4600. """
  4601. for idx in range(self.ui.plot_tab_area.count()):
  4602. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4603. # there can be only one instance of Tools Database at one time
  4604. return
  4605. if source == 'app':
  4606. self.tools_db_tab = ToolsDB2(
  4607. app=self,
  4608. parent=self.ui,
  4609. callback_on_edited=self.on_tools_db_edited,
  4610. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4611. )
  4612. elif source == 'ncc':
  4613. self.tools_db_tab = ToolsDB2(
  4614. app=self,
  4615. parent=self.ui,
  4616. callback_on_edited=self.on_tools_db_edited,
  4617. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4618. )
  4619. elif source == 'paint':
  4620. self.tools_db_tab = ToolsDB2(
  4621. app=self,
  4622. parent=self.ui,
  4623. callback_on_edited=self.on_tools_db_edited,
  4624. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4625. )
  4626. elif source == 'iso':
  4627. self.tools_db_tab = ToolsDB2(
  4628. app=self,
  4629. parent=self.ui,
  4630. callback_on_edited=self.on_tools_db_edited,
  4631. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4632. )
  4633. # add the tab if it was closed
  4634. try:
  4635. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4636. self.tools_db_tab.setObjectName("database_tab")
  4637. except Exception as e:
  4638. log.debug("App.on_tools_database() --> %s" % str(e))
  4639. return
  4640. # delete the absolute and relative position and messages in the infobar
  4641. # self.ui.position_label.setText("")
  4642. # self.ui.rel_position_label.setText("")
  4643. # hide coordinates toolbars in the infobar while in DB
  4644. self.ui.coords_toolbar.hide()
  4645. self.ui.delta_coords_toolbar.hide()
  4646. # Switch plot_area to preferences page
  4647. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4648. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4649. self.tools_db_tab.ui_connect()
  4650. def on_tools_db_edited(self):
  4651. """
  4652. Executed whenever a tool is edited in Tools Database.
  4653. Will color the text of the Tools Database tab to Red color.
  4654. :return:
  4655. """
  4656. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4657. for idx in range(self.ui.plot_tab_area.count()):
  4658. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4659. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4660. self.tools_db_tab.ui.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4661. self.tools_db_changed_flag = True
  4662. def on_geometry_tool_add_from_db_executed(self, tool):
  4663. """
  4664. Here add the tool from DB in the selected geometry object.
  4665. :return:
  4666. """
  4667. tool_from_db = deepcopy(tool)
  4668. obj = self.collection.get_active()
  4669. if obj.kind == 'geometry':
  4670. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4671. # close the tab and delete it
  4672. for idx in range(self.ui.plot_tab_area.count()):
  4673. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4674. wdg = self.ui.plot_tab_area.widget(idx)
  4675. wdg.deleteLater()
  4676. self.ui.plot_tab_area.removeTab(idx)
  4677. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4678. elif obj.kind == 'gerber':
  4679. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4680. # close the tab and delete it
  4681. for idx in range(self.ui.plot_tab_area.count()):
  4682. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4683. wdg = self.ui.plot_tab_area.widget(idx)
  4684. wdg.deleteLater()
  4685. self.ui.plot_tab_area.removeTab(idx)
  4686. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4687. else:
  4688. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4689. def on_plot_area_tab_closed(self, tab_obj_name):
  4690. """
  4691. Executed whenever a QTab is closed in the Plot Area.
  4692. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4693. :return:
  4694. """
  4695. if tab_obj_name == "preferences_tab":
  4696. self.preferencesUiManager.on_close_preferences_tab()
  4697. elif tab_obj_name == "database_tab":
  4698. # disconnect the signals from the table widget in tab
  4699. self.tools_db_tab.ui_disconnect()
  4700. if self.tools_db_changed_flag is True:
  4701. msgbox = QtWidgets.QMessageBox()
  4702. msgbox.setText(_("One or more Tools are edited.\n"
  4703. "Do you want to update the Tools Database?"))
  4704. msgbox.setWindowTitle(_("Save Tools Database"))
  4705. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4706. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4707. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4708. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4709. msgbox.setDefaultButton(bt_yes)
  4710. msgbox.exec_()
  4711. response = msgbox.clickedButton()
  4712. if response == bt_yes:
  4713. self.tools_db_tab.on_save_tools_db()
  4714. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4715. else:
  4716. self.tools_db_changed_flag = False
  4717. self.inform.emit('')
  4718. return
  4719. self.tools_db_tab.deleteLater()
  4720. elif tab_obj_name == "text_editor_tab":
  4721. self.toggle_codeeditor = False
  4722. elif tab_obj_name == "bookmarks_tab":
  4723. self.book_dialog_tab.rebuild_actions()
  4724. self.book_dialog_tab.deleteLater()
  4725. else:
  4726. pass
  4727. # restore the coords toolbars
  4728. self.ui.toggle_coords(checked=self.defaults["global_coords_show"])
  4729. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coords_show"])
  4730. def on_flipy(self):
  4731. """
  4732. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4733. :return:
  4734. """
  4735. self.defaults.report_usage("on_flipy()")
  4736. obj_list = self.collection.get_selected()
  4737. xminlist = []
  4738. yminlist = []
  4739. xmaxlist = []
  4740. ymaxlist = []
  4741. if not obj_list:
  4742. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4743. else:
  4744. try:
  4745. # first get a bounding box to fit all
  4746. for obj in obj_list:
  4747. xmin, ymin, xmax, ymax = obj.bounds()
  4748. xminlist.append(xmin)
  4749. yminlist.append(ymin)
  4750. xmaxlist.append(xmax)
  4751. ymaxlist.append(ymax)
  4752. # get the minimum x,y and maximum x,y for all objects selected
  4753. xminimal = min(xminlist)
  4754. yminimal = min(yminlist)
  4755. xmaximal = max(xmaxlist)
  4756. ymaximal = max(ymaxlist)
  4757. px = 0.5 * (xminimal + xmaximal)
  4758. py = 0.5 * (yminimal + ymaximal)
  4759. # execute mirroring
  4760. for obj in obj_list:
  4761. obj.mirror('X', [px, py])
  4762. obj.plot()
  4763. self.app_obj.object_changed.emit(obj)
  4764. self.inform.emit('[success] %s' %
  4765. _("Flip on Y axis done."))
  4766. except Exception as e:
  4767. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4768. return
  4769. def on_flipx(self):
  4770. """
  4771. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4772. :return:
  4773. """
  4774. self.defaults.report_usage("on_flipx()")
  4775. obj_list = self.collection.get_selected()
  4776. xminlist = []
  4777. yminlist = []
  4778. xmaxlist = []
  4779. ymaxlist = []
  4780. if not obj_list:
  4781. self.inform.emit('[WARNING_NOTCL] %s' %
  4782. _("No object selected to Flip on X axis."))
  4783. else:
  4784. try:
  4785. # first get a bounding box to fit all
  4786. for obj in obj_list:
  4787. xmin, ymin, xmax, ymax = obj.bounds()
  4788. xminlist.append(xmin)
  4789. yminlist.append(ymin)
  4790. xmaxlist.append(xmax)
  4791. ymaxlist.append(ymax)
  4792. # get the minimum x,y and maximum x,y for all objects selected
  4793. xminimal = min(xminlist)
  4794. yminimal = min(yminlist)
  4795. xmaximal = max(xmaxlist)
  4796. ymaximal = max(ymaxlist)
  4797. px = 0.5 * (xminimal + xmaximal)
  4798. py = 0.5 * (yminimal + ymaximal)
  4799. # execute mirroring
  4800. for obj in obj_list:
  4801. obj.mirror('Y', [px, py])
  4802. obj.plot()
  4803. self.app_obj.object_changed.emit(obj)
  4804. self.inform.emit('[success] %s' %
  4805. _("Flip on X axis done."))
  4806. except Exception as e:
  4807. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4808. return
  4809. def on_rotate(self, silent=False, preset=None):
  4810. """
  4811. Executed when Options -> Rotate Selection menu entry is clicked.
  4812. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4813. :param preset: A value to be used as predefined angle for rotation.
  4814. :return:
  4815. """
  4816. self.defaults.report_usage("on_rotate()")
  4817. obj_list = self.collection.get_selected()
  4818. xminlist = []
  4819. yminlist = []
  4820. xmaxlist = []
  4821. ymaxlist = []
  4822. if not obj_list:
  4823. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4824. else:
  4825. if silent is False:
  4826. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4827. min=-360, max=360, decimals=4,
  4828. init_val=float(self.defaults['tools_transform_rotate']))
  4829. num, ok = rotatebox.get_value()
  4830. else:
  4831. num = preset
  4832. ok = True
  4833. if ok:
  4834. try:
  4835. # first get a bounding box to fit all
  4836. for obj in obj_list:
  4837. xmin, ymin, xmax, ymax = obj.bounds()
  4838. xminlist.append(xmin)
  4839. yminlist.append(ymin)
  4840. xmaxlist.append(xmax)
  4841. ymaxlist.append(ymax)
  4842. # get the minimum x,y and maximum x,y for all objects selected
  4843. xminimal = min(xminlist)
  4844. yminimal = min(yminlist)
  4845. xmaximal = max(xmaxlist)
  4846. ymaximal = max(ymaxlist)
  4847. px = 0.5 * (xminimal + xmaximal)
  4848. py = 0.5 * (yminimal + ymaximal)
  4849. for sel_obj in obj_list:
  4850. sel_obj.rotate(-float(num), point=(px, py))
  4851. sel_obj.plot()
  4852. self.app_obj.object_changed.emit(sel_obj)
  4853. self.inform.emit('[success] %s' % _("Rotation done."))
  4854. except Exception as e:
  4855. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4856. return
  4857. def on_skewx(self):
  4858. """
  4859. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4860. :return:
  4861. """
  4862. self.defaults.report_usage("on_skewx()")
  4863. obj_list = self.collection.get_selected()
  4864. xminlist = []
  4865. yminlist = []
  4866. if not obj_list:
  4867. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4868. else:
  4869. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4870. min=-360, max=360, decimals=4,
  4871. init_val=float(self.defaults['tools_transform_skew_x']))
  4872. num, ok = skewxbox.get_value()
  4873. if ok:
  4874. # first get a bounding box to fit all
  4875. for obj in obj_list:
  4876. xmin, ymin, xmax, ymax = obj.bounds()
  4877. xminlist.append(xmin)
  4878. yminlist.append(ymin)
  4879. # get the minimum x,y and maximum x,y for all objects selected
  4880. xminimal = min(xminlist)
  4881. yminimal = min(yminlist)
  4882. for obj in obj_list:
  4883. obj.skew(num, 0, point=(xminimal, yminimal))
  4884. obj.plot()
  4885. self.app_obj.object_changed.emit(obj)
  4886. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4887. def on_skewy(self):
  4888. """
  4889. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4890. :return:
  4891. """
  4892. self.defaults.report_usage("on_skewy()")
  4893. obj_list = self.collection.get_selected()
  4894. xminlist = []
  4895. yminlist = []
  4896. if not obj_list:
  4897. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4898. else:
  4899. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4900. min=-360, max=360, decimals=4,
  4901. init_val=float(self.defaults['tools_transform_skew_y']))
  4902. num, ok = skewybox.get_value()
  4903. if ok:
  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. # get the minimum x,y and maximum x,y for all objects selected
  4910. xminimal = min(xminlist)
  4911. yminimal = min(yminlist)
  4912. for obj in obj_list:
  4913. obj.skew(0, num, point=(xminimal, yminimal))
  4914. obj.plot()
  4915. self.app_obj.object_changed.emit(obj)
  4916. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4917. def on_plots_updated(self):
  4918. """
  4919. Callback used to report when the plots have changed.
  4920. Adjust axes and zooms to fit.
  4921. :return: None
  4922. """
  4923. if self.is_legacy is False:
  4924. self.plotcanvas.update()
  4925. else:
  4926. self.plotcanvas.auto_adjust_axes()
  4927. self.on_zoom_fit()
  4928. self.collection.update_view()
  4929. # self.inform.emit(_("Plots updated ..."))
  4930. def on_toolbar_replot(self):
  4931. """
  4932. Callback for toolbar button. Re-plots all objects.
  4933. :return: None
  4934. """
  4935. self.log.debug("on_toolbar_replot()")
  4936. try:
  4937. obj = self.collection.get_active()
  4938. if obj:
  4939. obj.read_form()
  4940. else:
  4941. self.on_zoom_fit()
  4942. except AttributeError as e:
  4943. log.debug("on_toolbar_replot() -> %s" % str(e))
  4944. pass
  4945. self.plot_all()
  4946. def grid_status(self):
  4947. return True if self.ui.grid_snap_btn.isChecked() else False
  4948. def populate_cmenu_grids(self):
  4949. units = self.defaults['units'].lower()
  4950. # for act in self.ui.cmenu_gridmenu.actions():
  4951. # act.triggered.disconnect()
  4952. self.ui.cmenu_gridmenu.clear()
  4953. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4954. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4955. _("Grid On/Off"))
  4956. grid_toggle.setCheckable(True)
  4957. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4958. self.ui.cmenu_gridmenu.addSeparator()
  4959. for grid in sorted_list:
  4960. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4961. "%s" % str(grid))
  4962. action.triggered.connect(self.set_grid)
  4963. self.ui.cmenu_gridmenu.addSeparator()
  4964. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4965. _("Add"))
  4966. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4967. _("Delete"))
  4968. grid_add.triggered.connect(self.on_grid_add)
  4969. grid_delete.triggered.connect(self.on_grid_delete)
  4970. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4971. def set_grid(self):
  4972. menu_action = self.sender()
  4973. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4974. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4975. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4976. def on_grid_add(self):
  4977. # ## Current application units in lower Case
  4978. units = self.defaults['units'].lower()
  4979. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4980. text=_('Enter a Grid Value:'),
  4981. min=0.0000, max=99.9999, decimals=4)
  4982. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4983. val, ok = grid_add_popup.get_value()
  4984. if ok:
  4985. if float(val) == 0:
  4986. self.inform.emit('[WARNING_NOTCL] %s' %
  4987. _("Please enter a grid value with non-zero value, in Float format."))
  4988. return
  4989. else:
  4990. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4991. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4992. self.inform.emit('[success] %s...' % _("New Grid added"))
  4993. else:
  4994. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4995. else:
  4996. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4997. def on_grid_delete(self):
  4998. # ## Current application units in lower Case
  4999. units = self.defaults['units'].lower()
  5000. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5001. text='Enter a Grid Value:',
  5002. min=0.0000, max=99.9999, decimals=4)
  5003. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5004. val, ok = grid_del_popup.get_value()
  5005. if ok:
  5006. if float(val) == 0:
  5007. self.inform.emit('[WARNING_NOTCL] %s' %
  5008. _("Please enter a grid value with non-zero value, in Float format."))
  5009. return
  5010. else:
  5011. try:
  5012. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5013. except ValueError:
  5014. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  5015. return
  5016. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5017. else:
  5018. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5019. def on_shortcut_list(self):
  5020. self.defaults.report_usage("on_shortcut_list()")
  5021. # add the tab if it was closed
  5022. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5023. # delete the absolute and relative position and messages in the infobar
  5024. # self.ui.position_label.setText("")
  5025. # self.ui.rel_position_label.setText("")
  5026. # hide coordinates toolbars in the infobar while in DB
  5027. self.ui.coords_toolbar.hide()
  5028. self.ui.delta_coords_toolbar.hide()
  5029. # Switch plot_area to preferences page
  5030. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5031. # self.ui.show()
  5032. def on_select_tab(self, name):
  5033. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5034. if self.ui.splitter.sizes()[0] == 0:
  5035. self.ui.splitter.setSizes([1, 1])
  5036. else:
  5037. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5038. self.ui.splitter.setSizes([0, 1])
  5039. if name == 'project':
  5040. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5041. elif name == 'selected':
  5042. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5043. elif name == 'tool':
  5044. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5045. def on_copy_name(self):
  5046. self.defaults.report_usage("on_copy_name()")
  5047. obj = self.collection.get_active()
  5048. try:
  5049. name = obj.options["name"]
  5050. except AttributeError:
  5051. log.debug("on_copy_name() --> No object selected to copy it's name")
  5052. self.inform.emit('[WARNING_NOTCL] %s' %
  5053. _(" No object selected to copy it's name"))
  5054. return
  5055. self.clipboard.setText(name)
  5056. self.inform.emit(_("Name copied on clipboard ..."))
  5057. def on_mouse_click_over_plot(self, event):
  5058. """
  5059. Default actions are:
  5060. :param event: Contains information about the event, like which button
  5061. was clicked, the pixel coordinates and the axes coordinates.
  5062. :return: None
  5063. """
  5064. self.pos = []
  5065. if self.is_legacy is False:
  5066. event_pos = event.pos
  5067. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5068. # # Set the mouse button for panning
  5069. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5070. else:
  5071. event_pos = (event.xdata, event.ydata)
  5072. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5073. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5074. # So it can receive key presses
  5075. self.plotcanvas.native.setFocus()
  5076. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5077. if self.grid_status():
  5078. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5079. else:
  5080. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5081. try:
  5082. if event.button == 1:
  5083. # Reset here the relative coordinates so there is a new reference on the click position
  5084. if self.rel_point1 is None:
  5085. self.rel_point1 = self.pos
  5086. else:
  5087. self.rel_point2 = copy(self.rel_point1)
  5088. self.rel_point1 = self.pos
  5089. self.on_mouse_move_over_plot(event, origin_click=True)
  5090. except Exception as e:
  5091. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5092. def on_mouse_double_click_over_plot(self, event):
  5093. if event.button == 1:
  5094. self.doubleclick = True
  5095. def on_mouse_move_over_plot(self, event, origin_click=None):
  5096. """
  5097. Callback for the mouse motion event over the plot.
  5098. :param event: Contains information about the event.
  5099. :param origin_click
  5100. :return: None
  5101. """
  5102. if self.is_legacy is False:
  5103. event_pos = event.pos
  5104. if self.defaults["global_pan_button"] == '2':
  5105. pan_button = 2
  5106. else:
  5107. pan_button = 3
  5108. self.event_is_dragging = event.is_dragging
  5109. else:
  5110. event_pos = (event.xdata, event.ydata)
  5111. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5112. if self.defaults["global_pan_button"] == '2':
  5113. pan_button = 3
  5114. else:
  5115. pan_button = 2
  5116. self.event_is_dragging = self.plotcanvas.is_dragging
  5117. # So it can receive key presses but not when the Tcl Shell is active
  5118. if not self.ui.shell_dock.isVisible():
  5119. if not self.plotcanvas.native.hasFocus():
  5120. self.plotcanvas.native.setFocus()
  5121. self.pos_jump = event_pos
  5122. self.ui.popMenu.mouse_is_panning = False
  5123. if origin_click is None:
  5124. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5125. if event.button == pan_button and self.event_is_dragging == 1:
  5126. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5127. if self.ui.popMenu.popup_active:
  5128. self.ui.popMenu.popup_active = False
  5129. return
  5130. self.ui.popMenu.mouse_is_panning = True
  5131. return
  5132. if self.rel_point1 is not None:
  5133. try: # May fail in case mouse not within axes
  5134. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5135. if pos_canvas[0] is None or pos_canvas[1] is None:
  5136. return
  5137. if self.grid_status():
  5138. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5139. # Update cursor
  5140. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5141. symbol='++', edge_color=self.cursor_color_3D,
  5142. edge_width=self.defaults["global_cursor_width"],
  5143. size=self.defaults["global_cursor_size"])
  5144. else:
  5145. pos = (pos_canvas[0], pos_canvas[1])
  5146. self.dx = pos[0] - float(self.rel_point1[0])
  5147. self.dy = pos[1] - float(self.rel_point1[1])
  5148. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5149. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5150. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5151. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5152. units = self.defaults["units"].lower()
  5153. self.plotcanvas.text_hud.text = \
  5154. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5155. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5156. self.mouse = [pos[0], pos[1]]
  5157. if self.defaults['global_selection_shape'] is False:
  5158. self.selection_type = None
  5159. return
  5160. # if the mouse is moved and the LMB is clicked then the action is a selection
  5161. if self.event_is_dragging == 1 and event.button == 1:
  5162. self.delete_selection_shape()
  5163. if self.dx < 0:
  5164. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5165. face_color=self.defaults['global_alt_sel_fill'])
  5166. self.selection_type = False
  5167. elif self.dx >= 0:
  5168. self.draw_moving_selection_shape(self.pos, pos)
  5169. self.selection_type = True
  5170. else:
  5171. self.selection_type = None
  5172. else:
  5173. self.selection_type = None
  5174. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5175. if self.defaults['global_hover']:
  5176. for obj in self.collection.get_list():
  5177. try:
  5178. # select the object(s) only if it is enabled (plotted)
  5179. if obj.options['plot']:
  5180. if obj not in self.collection.get_selected():
  5181. poly_obj = Polygon(
  5182. [(obj.options['xmin'], obj.options['ymin']),
  5183. (obj.options['xmax'], obj.options['ymin']),
  5184. (obj.options['xmax'], obj.options['ymax']),
  5185. (obj.options['xmin'], obj.options['ymax'])]
  5186. )
  5187. if Point(pos).within(poly_obj):
  5188. if obj.isHovering is False:
  5189. obj.isHovering = True
  5190. obj.notHovering = True
  5191. # create the selection box around the selected object
  5192. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5193. else:
  5194. if obj.notHovering is True:
  5195. obj.notHovering = False
  5196. obj.isHovering = False
  5197. self.delete_hover_shape()
  5198. except Exception:
  5199. # the Exception here will happen if we try to select on screen and we have an
  5200. # newly (and empty) just created Geometry or Excellon object that do not have the
  5201. # xmin, xmax, ymin, ymax options.
  5202. # In this case poly_obj creation (see above) will fail
  5203. pass
  5204. except Exception as e:
  5205. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5206. self.ui.position_label.setText("")
  5207. self.ui.rel_position_label.setText("")
  5208. self.mouse = None
  5209. def on_mouse_click_release_over_plot(self, event):
  5210. """
  5211. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5212. and has been registered in ''self.__init__()''.
  5213. :param event: contains information about the event.
  5214. :return:
  5215. """
  5216. if self.is_legacy is False:
  5217. event_pos = event.pos
  5218. right_button = 2
  5219. else:
  5220. event_pos = (event.xdata, event.ydata)
  5221. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5222. right_button = 3
  5223. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5224. if self.grid_status():
  5225. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5226. else:
  5227. pos = (pos_canvas[0], pos_canvas[1])
  5228. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5229. # canvas menu
  5230. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5231. self.ui.popMenu.mouse_is_panning = False
  5232. self.cursor = QtGui.QCursor()
  5233. self.populate_cmenu_grids()
  5234. self.ui.popMenu.popup(self.cursor.pos())
  5235. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5236. # selection and then select a type of selection ("enclosing" or "touching")
  5237. if event.button == 1: # left click
  5238. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5239. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5240. if modifiers == QtCore.Qt.ShiftModifier:
  5241. # do not auto open the Project Tab
  5242. self.click_noproject = True
  5243. self.clipboard.setText(
  5244. self.defaults["global_point_clipboard_format"] %
  5245. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5246. )
  5247. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5248. return
  5249. if self.doubleclick is True:
  5250. self.doubleclick = False
  5251. if self.collection.get_selected():
  5252. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5253. if self.ui.splitter.sizes()[0] == 0:
  5254. self.ui.splitter.setSizes([1, 1])
  5255. try:
  5256. # delete the selection shape(S) as it may be in the way
  5257. self.delete_selection_shape()
  5258. self.delete_hover_shape()
  5259. except Exception as e:
  5260. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5261. return
  5262. else:
  5263. # WORKAROUND for LEGACY MODE
  5264. if self.is_legacy is True:
  5265. # if there is no move on canvas then we have no dragging selection
  5266. if self.dx == 0 or self.dy == 0:
  5267. self.selection_type = None
  5268. if self.selection_type is not None:
  5269. try:
  5270. self.selection_area_handler(self.pos, pos, self.selection_type)
  5271. self.selection_type = None
  5272. except Exception as e:
  5273. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5274. return
  5275. else:
  5276. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5277. if key_modifier == QtCore.Qt.ShiftModifier:
  5278. mod_key = 'Shift'
  5279. elif key_modifier == QtCore.Qt.ControlModifier:
  5280. mod_key = 'Control'
  5281. else:
  5282. mod_key = None
  5283. try:
  5284. if self.command_active is None:
  5285. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5286. # deselect, and if it's not selected then it will be selected
  5287. # If there is no active command (self.command_active is None) then we check if we clicked
  5288. # on a object by checking the bounding limits against mouse click position
  5289. if mod_key == self.defaults["global_mselect_key"]:
  5290. self.select_objects(key='multisel')
  5291. else:
  5292. # If there is no active command (self.command_active is None) then we check if
  5293. # we clicked on a object by checking the bounding limits against mouse click position
  5294. self.select_objects()
  5295. self.delete_hover_shape()
  5296. except Exception as e:
  5297. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5298. return
  5299. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5300. """
  5301. :param start_pos: mouse position when the selection LMB click was done
  5302. :param end_pos: mouse position when the left mouse button is released
  5303. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5304. :return:
  5305. """
  5306. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5307. # delete previous selection shape
  5308. self.delete_selection_shape()
  5309. # make all objects inactive
  5310. self.collection.set_all_inactive()
  5311. for obj in self.collection.get_list():
  5312. try:
  5313. # select the object(s) only if it is enabled (plotted)
  5314. if obj.options['plot']:
  5315. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5316. (obj.options['xmax'], obj.options['ymin']),
  5317. (obj.options['xmax'], obj.options['ymax']),
  5318. (obj.options['xmin'], obj.options['ymax'])])
  5319. if sel_type is True:
  5320. if poly_obj.within(poly_selection):
  5321. # create the selection box around the selected object
  5322. if self.defaults['global_selection_shape'] is True:
  5323. self.draw_selection_shape(obj)
  5324. self.collection.set_active(obj.options['name'])
  5325. else:
  5326. if poly_selection.intersects(poly_obj):
  5327. # create the selection box around the selected object
  5328. if self.defaults['global_selection_shape'] is True:
  5329. self.draw_selection_shape(obj)
  5330. self.collection.set_active(obj.options['name'])
  5331. obj.selection_shape_drawn = True
  5332. except Exception as e:
  5333. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5334. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5335. # In this case poly_obj creation (see above) will fail
  5336. log.debug("App.selection_area_handler() --> %s" % str(e))
  5337. def select_objects(self, key=None):
  5338. """
  5339. Will select objects clicked on canvas
  5340. :param key: for future use in cumulative selection
  5341. :return:
  5342. """
  5343. # list where we store the overlapped objects under our mouse left click position
  5344. if key is None:
  5345. self.objects_under_the_click_list = []
  5346. # Populate the list with the overlapped objects on the click position
  5347. curr_x, curr_y = self.pos
  5348. for obj in self.all_objects_list:
  5349. # ScriptObject and DocumentObject objects can't be selected
  5350. if obj.kind == 'script' or obj.kind == 'document':
  5351. continue
  5352. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5353. continue
  5354. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5355. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5356. if obj.options['name'] not in self.objects_under_the_click_list:
  5357. if obj.options['plot']:
  5358. # add objects to the objects_under_the_click list only if the object is plotted
  5359. # (active and not disabled)
  5360. self.objects_under_the_click_list.append(obj.options['name'])
  5361. try:
  5362. if self.objects_under_the_click_list:
  5363. curr_sel_obj = self.collection.get_active()
  5364. # case when there is only an object under the click and we toggle it
  5365. if len(self.objects_under_the_click_list) == 1:
  5366. if curr_sel_obj is None:
  5367. self.collection.set_active(self.objects_under_the_click_list[0])
  5368. curr_sel_obj = self.collection.get_active()
  5369. # create the selection box around the selected object
  5370. if self.defaults['global_selection_shape'] is True:
  5371. self.draw_selection_shape(curr_sel_obj)
  5372. curr_sel_obj.selection_shape_drawn = True
  5373. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5374. self.collection.on_objects_selection(False)
  5375. self.delete_selection_shape()
  5376. curr_sel_obj.selection_shape_drawn = False
  5377. self.collection.set_active(self.objects_under_the_click_list[0])
  5378. curr_sel_obj = self.collection.get_active()
  5379. # create the selection box around the selected object
  5380. if self.defaults['global_selection_shape'] is True:
  5381. self.draw_selection_shape(curr_sel_obj)
  5382. curr_sel_obj.selection_shape_drawn = True
  5383. self.selected_message(curr_sel_obj=curr_sel_obj)
  5384. elif curr_sel_obj.selection_shape_drawn is False:
  5385. if self.defaults['global_selection_shape'] is True:
  5386. self.draw_selection_shape(curr_sel_obj)
  5387. curr_sel_obj.selection_shape_drawn = True
  5388. else:
  5389. self.collection.on_objects_selection(False)
  5390. self.delete_selection_shape()
  5391. if self.call_source != 'app':
  5392. self.call_source = 'app'
  5393. self.selected_message(curr_sel_obj=curr_sel_obj)
  5394. else:
  5395. # If there is no selected object
  5396. # make active the first element of the overlapped objects list
  5397. if self.collection.get_active() is None:
  5398. self.collection.set_active(self.objects_under_the_click_list[0])
  5399. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5400. name_sel_obj = self.collection.get_active().options['name']
  5401. # In case that there is a selected object but it is not in the overlapped object list
  5402. # make that object inactive and activate the first element in the overlapped object list
  5403. if name_sel_obj not in self.objects_under_the_click_list:
  5404. self.collection.set_inactive(name_sel_obj)
  5405. name_sel_obj = self.objects_under_the_click_list[0]
  5406. self.collection.set_active(name_sel_obj)
  5407. else:
  5408. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5409. self.collection.set_all_inactive()
  5410. self.collection.set_active(
  5411. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5412. curr_sel_obj = self.collection.get_active()
  5413. # delete the possible selection box around a possible selected object
  5414. self.delete_selection_shape()
  5415. curr_sel_obj.selection_shape_drawn = False
  5416. # create the selection box around the selected object
  5417. if self.defaults['global_selection_shape'] is True:
  5418. self.draw_selection_shape(curr_sel_obj)
  5419. curr_sel_obj.selection_shape_drawn = True
  5420. self.selected_message(curr_sel_obj=curr_sel_obj)
  5421. else:
  5422. # deselect everything
  5423. self.collection.on_objects_selection(False)
  5424. # delete the possible selection box around a possible selected object
  5425. self.delete_selection_shape()
  5426. for o in self.collection.get_list():
  5427. o.selection_shape_drawn = False
  5428. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5429. # only when working on App
  5430. if self.call_source == 'app':
  5431. if self.click_noproject is False:
  5432. # if the Tool Tab is in focus don't change focus to Project Tab
  5433. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5434. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5435. else:
  5436. # restore auto open the Project Tab
  5437. self.click_noproject = False
  5438. # delete any text in the status bar, implicitly the last object name that was selected
  5439. # self.inform.emit("")
  5440. else:
  5441. self.call_source = 'app'
  5442. except Exception as e:
  5443. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5444. def selected_message(self, curr_sel_obj):
  5445. if curr_sel_obj:
  5446. if curr_sel_obj.kind == 'gerber':
  5447. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5448. color='green',
  5449. name=str(curr_sel_obj.options['name']),
  5450. tx=_("selected"))
  5451. )
  5452. elif curr_sel_obj.kind == 'excellon':
  5453. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5454. color='brown',
  5455. name=str(curr_sel_obj.options['name']),
  5456. tx=_("selected"))
  5457. )
  5458. elif curr_sel_obj.kind == 'cncjob':
  5459. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5460. color='blue',
  5461. name=str(curr_sel_obj.options['name']),
  5462. tx=_("selected"))
  5463. )
  5464. elif curr_sel_obj.kind == 'geometry':
  5465. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5466. color='red',
  5467. name=str(curr_sel_obj.options['name']),
  5468. tx=_("selected"))
  5469. )
  5470. def delete_hover_shape(self):
  5471. self.hover_shapes.clear()
  5472. self.hover_shapes.redraw()
  5473. def draw_hover_shape(self, sel_obj, color=None):
  5474. """
  5475. :param sel_obj: The object for which the hover shape must be drawn
  5476. :param color: The color of the hover shape
  5477. :return: None
  5478. """
  5479. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5480. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5481. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5482. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5483. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5484. if self.defaults['units'].upper() == 'MM':
  5485. hover_rect = hover_rect.buffer(-0.1)
  5486. hover_rect = hover_rect.buffer(0.2)
  5487. else:
  5488. hover_rect = hover_rect.buffer(-0.00393)
  5489. hover_rect = hover_rect.buffer(0.00787)
  5490. # if color:
  5491. # face = Color(color)
  5492. # face.alpha = 0.2
  5493. # outline = Color(color, alpha=0.8)
  5494. # else:
  5495. # face = Color(self.defaults['global_sel_fill'])
  5496. # face.alpha = 0.2
  5497. # outline = self.defaults['global_sel_line']
  5498. if color:
  5499. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5500. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5501. else:
  5502. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5503. outline = self.defaults['global_sel_line']
  5504. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5505. if self.is_legacy is True:
  5506. self.hover_shapes.redraw()
  5507. def delete_selection_shape(self):
  5508. self.move_tool.sel_shapes.clear()
  5509. self.move_tool.sel_shapes.redraw()
  5510. def draw_selection_shape(self, sel_obj, color=None):
  5511. """
  5512. Will draw a selection shape around the selected object.
  5513. :param sel_obj: The object for which the selection shape must be drawn
  5514. :param color: The color for the selection shape.
  5515. :return: None
  5516. """
  5517. if sel_obj is None:
  5518. return
  5519. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5520. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5521. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5522. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5523. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5524. if self.defaults['units'].upper() == 'MM':
  5525. sel_rect = sel_rect.buffer(-0.1)
  5526. sel_rect = sel_rect.buffer(0.2)
  5527. else:
  5528. sel_rect = sel_rect.buffer(-0.00393)
  5529. sel_rect = sel_rect.buffer(0.00787)
  5530. if color:
  5531. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5532. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5533. else:
  5534. if self.is_legacy is False:
  5535. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5536. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5537. else:
  5538. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5539. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5540. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5541. color=outline,
  5542. face_color=face,
  5543. update=True,
  5544. layer=0,
  5545. tolerance=None))
  5546. if self.is_legacy is True:
  5547. self.move_tool.sel_shapes.redraw()
  5548. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5549. """
  5550. Will draw a selection shape when dragging mouse on canvas.
  5551. :param old_coords: Old coordinates
  5552. :param coords: New coordinates
  5553. :param kwargs: Keyword arguments
  5554. :return:
  5555. """
  5556. if 'color' in kwargs:
  5557. color = kwargs['color']
  5558. else:
  5559. color = self.defaults['global_sel_line']
  5560. if 'face_color' in kwargs:
  5561. face_color = kwargs['face_color']
  5562. else:
  5563. face_color = self.defaults['global_sel_fill']
  5564. if 'face_alpha' in kwargs:
  5565. face_alpha = kwargs['face_alpha']
  5566. else:
  5567. face_alpha = 0.3
  5568. x0, y0 = old_coords
  5569. x1, y1 = coords
  5570. pt1 = (x0, y0)
  5571. pt2 = (x1, y0)
  5572. pt3 = (x1, y1)
  5573. pt4 = (x0, y1)
  5574. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5575. # color_t = Color(face_color)
  5576. # color_t.alpha = face_alpha
  5577. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5578. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5579. layer=0, tolerance=None)
  5580. if self.is_legacy is True:
  5581. self.move_tool.sel_shapes.redraw()
  5582. def on_file_new_click(self):
  5583. """
  5584. Callback for menu item File -> New.
  5585. Executed on clicking the Menu -> File -> New Project
  5586. :return:
  5587. """
  5588. if self.collection.get_list() and self.should_we_save:
  5589. msgbox = QtWidgets.QMessageBox()
  5590. # msgbox.setText("<B>Save changes ...</B>")
  5591. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5592. "Creating a New project will delete them.\n"
  5593. "Do you want to Save the project?"))
  5594. msgbox.setWindowTitle(_("Save changes"))
  5595. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5596. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5597. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5598. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5599. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5600. msgbox.setDefaultButton(bt_yes)
  5601. msgbox.exec_()
  5602. response = msgbox.clickedButton()
  5603. if response == bt_yes:
  5604. self.on_file_saveprojectas()
  5605. elif response == bt_cancel:
  5606. return
  5607. elif response == bt_no:
  5608. self.on_file_new()
  5609. else:
  5610. self.on_file_new()
  5611. self.inform.emit('[success] %s...' % _("New Project created"))
  5612. def on_file_new(self, cli=None):
  5613. """
  5614. Returns the application to its startup state. This method is thread-safe.
  5615. :param cli: Boolean. If True this method was run from command line
  5616. :return: None
  5617. """
  5618. self.defaults.report_usage("on_file_new")
  5619. # Remove everything from memory
  5620. App.log.debug("on_file_new()")
  5621. # close any editor that might be open
  5622. if self.call_source != 'app':
  5623. self.editor2object(cleanup=True)
  5624. # ## EDITOR section
  5625. self.geo_editor = AppGeoEditor(self)
  5626. self.exc_editor = AppExcEditor(self)
  5627. self.grb_editor = AppGerberEditor(self)
  5628. # Clear pool
  5629. self.clear_pool()
  5630. for obj in self.collection.get_list():
  5631. # delete shapes left drawn from mark shape_collections, if any
  5632. if isinstance(obj, GerberObject):
  5633. try:
  5634. obj.mark_shapes_storage.clear()
  5635. obj.mark_shapes.clear(update=True)
  5636. obj.mark_shapes.enabled = False
  5637. except AttributeError:
  5638. pass
  5639. # also delete annotation shapes, if any
  5640. elif isinstance(obj, CNCJobObject):
  5641. try:
  5642. obj.text_col.enabled = False
  5643. del obj.text_col
  5644. obj.annotation.clear(update=True)
  5645. del obj.annotation
  5646. except AttributeError:
  5647. pass
  5648. # delete the exclusion areas
  5649. self.exc_areas.clear_shapes()
  5650. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5651. self.shell.init_tcl()
  5652. # delete any selection shape on canvas
  5653. self.delete_selection_shape()
  5654. # delete all FlatCAM objects
  5655. self.collection.delete_all()
  5656. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5657. self.setup_component_editor()
  5658. # Clear project filename
  5659. self.project_filename = None
  5660. # Load the application defaults
  5661. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5662. # Re-fresh project options
  5663. self.on_options_app2project()
  5664. # Init FlatCAMTools
  5665. self.init_tools()
  5666. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  5667. if cli is None:
  5668. # we need to go in reverse because once we remove a tab then the index changes
  5669. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5670. # and so on. Therefore the deletion should be done in reverse
  5671. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5672. for index in range(wdg_count, -1, -1):
  5673. try:
  5674. self.ui.plot_tab_area.closeTab(index)
  5675. except Exception as e:
  5676. log.debug("App.on_file_new() --> %s" % str(e))
  5677. # # And then add again the Plot Area
  5678. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5679. self.ui.plot_tab_area.protectTab(0)
  5680. # take the focus of the Notebook on Project Tab.
  5681. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5682. self.set_ui_title(name=_("New Project - Not saved"))
  5683. def obj_properties(self):
  5684. """
  5685. Will launch the object Properties Tool
  5686. :return:
  5687. """
  5688. self.defaults.report_usage("obj_properties()")
  5689. self.properties_tool.run(toggle=False)
  5690. def on_project_context_save(self):
  5691. """
  5692. Wrapper, will save the object function of it's type
  5693. :return:
  5694. """
  5695. sel_objects = self.collection.get_selected()
  5696. len_objects = len(sel_objects)
  5697. cnt = 0
  5698. if len_objects > 1:
  5699. for o in sel_objects:
  5700. if o.kind == 'cncjob':
  5701. cnt += 1
  5702. if len_objects == cnt:
  5703. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5704. _filter_ = self.defaults['cncjob_save_filters'] + \
  5705. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5706. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5707. try:
  5708. filename, _f = FCFileSaveDialog.get_saved_filename(
  5709. caption=_("Export Code ..."),
  5710. directory=dir_file_to_save,
  5711. ext_filter=_filter_
  5712. )
  5713. except TypeError:
  5714. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."),
  5715. ext_filter=_filter_)
  5716. filename = filename.rpartition('/')[0]
  5717. for ob in sel_objects:
  5718. ob.read_form()
  5719. fname = '%s/%s' % (filename, ob.options['name'])
  5720. ob.export_gcode_handler(fname, is_gcode=True)
  5721. return
  5722. obj = self.collection.get_active()
  5723. if type(obj) == GeometryObject:
  5724. self.on_file_exportdxf()
  5725. elif type(obj) == ExcellonObject:
  5726. self.on_file_saveexcellon()
  5727. elif type(obj) == CNCJobObject:
  5728. obj.on_exportgcode_button_click()
  5729. elif type(obj) == GerberObject:
  5730. self.on_file_savegerber()
  5731. elif type(obj) == ScriptObject:
  5732. self.on_file_savescript()
  5733. elif type(obj) == DocumentObject:
  5734. self.on_file_savedocument()
  5735. def obj_move(self):
  5736. """
  5737. Callback for the Move menu entry in various Context Menu's.
  5738. :return:
  5739. """
  5740. self.defaults.report_usage("obj_move()")
  5741. self.move_tool.run(toggle=False)
  5742. def on_fileopengerber(self, signal, name=None):
  5743. """
  5744. File menu callback for opening a Gerber.
  5745. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5746. :param name:
  5747. :return: None
  5748. """
  5749. self.defaults.report_usage("on_fileopengerber")
  5750. App.log.debug("on_fileopengerber()")
  5751. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  5752. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  5753. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  5754. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  5755. "*.outline);;" \
  5756. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5757. "*.mil);;" \
  5758. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5759. "Allegro Files (*.art);;" \
  5760. "Mentor Files (*.pho *.gdo);;" \
  5761. "All Files (*.*)"
  5762. if name is None:
  5763. try:
  5764. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5765. directory=self.get_last_folder(),
  5766. filter=_filter_,
  5767. initialFilter=self.last_op_gerber_filter)
  5768. except TypeError:
  5769. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5770. filenames = [str(filename) for filename in filenames]
  5771. self.last_op_gerber_filter = _f
  5772. else:
  5773. filenames = [name]
  5774. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5775. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5776. _("Opening Gerber file.")),
  5777. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5778. color=QtGui.QColor("gray"))
  5779. if len(filenames) == 0:
  5780. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5781. else:
  5782. for filename in filenames:
  5783. if filename != '':
  5784. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5785. def on_fileopenexcellon(self, signal, name=None):
  5786. """
  5787. File menu callback for opening an Excellon file.
  5788. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5789. :param name:
  5790. :return: None
  5791. """
  5792. self.defaults.report_usage("on_fileopenexcellon")
  5793. App.log.debug("on_fileopenexcellon()")
  5794. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5795. "All Files (*.*)"
  5796. if name is None:
  5797. try:
  5798. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5799. directory=self.get_last_folder(),
  5800. filter=_filter_,
  5801. initialFilter=self.last_op_excellon_filter)
  5802. except TypeError:
  5803. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5804. filenames = [str(filename) for filename in filenames]
  5805. self.last_op_excellon_filter = _f
  5806. else:
  5807. filenames = [str(name)]
  5808. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5809. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5810. _("Opening Excellon file.")),
  5811. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5812. color=QtGui.QColor("gray"))
  5813. if len(filenames) == 0:
  5814. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5815. else:
  5816. for filename in filenames:
  5817. if filename != '':
  5818. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5819. def on_fileopengcode(self, signal, name=None):
  5820. """
  5821. File menu call back for opening gcode.
  5822. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5823. :param name:
  5824. :return:
  5825. """
  5826. self.defaults.report_usage("on_fileopengcode")
  5827. App.log.debug("on_fileopengcode()")
  5828. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5829. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5830. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5831. "All Files (*.*)"
  5832. if name is None:
  5833. try:
  5834. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5835. directory=self.get_last_folder(),
  5836. filter=_filter_,
  5837. initialFilter=self.last_op_gcode_filter)
  5838. except TypeError:
  5839. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5840. filenames = [str(filename) for filename in filenames]
  5841. self.last_op_gcode_filter = _f
  5842. else:
  5843. filenames = [name]
  5844. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5845. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5846. _("Opening G-Code file.")),
  5847. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5848. color=QtGui.QColor("gray"))
  5849. if len(filenames) == 0:
  5850. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5851. else:
  5852. for filename in filenames:
  5853. if filename != '':
  5854. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5855. def on_file_openproject(self, signal):
  5856. """
  5857. File menu callback for opening a project.
  5858. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5859. :return: None
  5860. """
  5861. self.defaults.report_usage("on_file_openproject")
  5862. App.log.debug("on_file_openproject()")
  5863. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5864. try:
  5865. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5866. directory=self.get_last_folder(), filter=_filter_)
  5867. except TypeError:
  5868. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5869. # The Qt methods above will return a QString which can cause problems later.
  5870. # So far json.dump() will fail to serialize it.
  5871. # TODO: Improve the serialization methods and remove this fix.
  5872. filename = str(filename)
  5873. if filename == "":
  5874. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5875. else:
  5876. # self.worker_task.emit({'fcn': self.open_project,
  5877. # 'params': [filename]})
  5878. # The above was failing because open_project() is not
  5879. # thread safe. The new_project()
  5880. self.open_project(filename)
  5881. def on_fileopenhpgl2(self, signal, name=None):
  5882. """
  5883. File menu callback for opening a HPGL2.
  5884. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5885. :param name:
  5886. :return: None
  5887. """
  5888. self.defaults.report_usage("on_fileopenhpgl2")
  5889. App.log.debug("on_fileopenhpgl2()")
  5890. _filter_ = "HPGL2 Files (*.plt);;" \
  5891. "All Files (*.*)"
  5892. if name is None:
  5893. try:
  5894. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5895. directory=self.get_last_folder(),
  5896. filter=_filter_)
  5897. except TypeError:
  5898. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5899. filenames = [str(filename) for filename in filenames]
  5900. else:
  5901. filenames = [name]
  5902. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5903. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5904. _("Opening HPGL2 file.")),
  5905. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5906. color=QtGui.QColor("gray"))
  5907. if len(filenames) == 0:
  5908. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5909. else:
  5910. for filename in filenames:
  5911. if filename != '':
  5912. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5913. def on_file_openconfig(self, signal):
  5914. """
  5915. File menu callback for opening a config file.
  5916. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5917. :return: None
  5918. """
  5919. self.defaults.report_usage("on_file_openconfig")
  5920. App.log.debug("on_file_openconfig()")
  5921. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5922. try:
  5923. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5924. directory=self.data_path, filter=_filter_)
  5925. except TypeError:
  5926. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5927. filter=_filter_)
  5928. if filename == "":
  5929. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5930. else:
  5931. self.open_config_file(filename)
  5932. def on_file_exportsvg(self):
  5933. """
  5934. Callback for menu item File->Export SVG.
  5935. :return: None
  5936. """
  5937. self.defaults.report_usage("on_file_exportsvg")
  5938. App.log.debug("on_file_exportsvg()")
  5939. obj = self.collection.get_active()
  5940. if obj is None:
  5941. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5942. msg = _("Please Select a Geometry object to export")
  5943. msgbox = QtWidgets.QMessageBox()
  5944. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5945. msgbox.setInformativeText(msg)
  5946. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5947. msgbox.setDefaultButton(bt_ok)
  5948. msgbox.exec_()
  5949. return
  5950. # Check for more compatible types and add as required
  5951. if (not isinstance(obj, GeometryObject)
  5952. and not isinstance(obj, GerberObject)
  5953. and not isinstance(obj, CNCJobObject)
  5954. and not isinstance(obj, ExcellonObject)):
  5955. msg = '[ERROR_NOTCL] %s' % \
  5956. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5957. msgbox = QtWidgets.QMessageBox()
  5958. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5959. msgbox.setInformativeText(msg)
  5960. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5961. msgbox.setDefaultButton(bt_ok)
  5962. msgbox.exec_()
  5963. return
  5964. name = obj.options["name"]
  5965. _filter = "SVG File (*.svg);;All Files (*.*)"
  5966. try:
  5967. filename, _f = FCFileSaveDialog.get_saved_filename(
  5968. caption=_("Export SVG"),
  5969. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5970. ext_filter=_filter)
  5971. except TypeError:
  5972. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5973. filename = str(filename)
  5974. if filename == "":
  5975. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5976. return
  5977. else:
  5978. self.export_svg(name, filename)
  5979. if self.defaults["global_open_style"] is False:
  5980. self.file_opened.emit("SVG", filename)
  5981. self.file_saved.emit("SVG", filename)
  5982. def on_file_exportpng(self):
  5983. self.defaults.report_usage("on_file_exportpng")
  5984. App.log.debug("on_file_exportpng()")
  5985. self.date = str(datetime.today()).rpartition('.')[0]
  5986. self.date = ''.join(c for c in self.date if c not in ':-')
  5987. self.date = self.date.replace(' ', '_')
  5988. data = None
  5989. if self.is_legacy is False:
  5990. image = _screenshot(alpha=False)
  5991. data = np.asarray(image)
  5992. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5993. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5994. return
  5995. filter_ = "PNG File (*.png);;All Files (*.*)"
  5996. try:
  5997. filename, _f = FCFileSaveDialog.get_saved_filename(
  5998. caption=_("Export PNG Image"),
  5999. directory=self.get_last_save_folder() + '/png_' + self.date,
  6000. ext_filter=filter_)
  6001. except TypeError:
  6002. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  6003. filename = str(filename)
  6004. if filename == "":
  6005. self.inform.emit(_("Cancelled."))
  6006. return
  6007. else:
  6008. if self.is_legacy is False:
  6009. write_png(filename, data)
  6010. else:
  6011. self.plotcanvas.figure.savefig(filename)
  6012. if self.defaults["global_open_style"] is False:
  6013. self.file_opened.emit("png", filename)
  6014. self.file_saved.emit("png", filename)
  6015. def on_file_savegerber(self):
  6016. """
  6017. Callback for menu item in Project context menu.
  6018. :return: None
  6019. """
  6020. self.defaults.report_usage("on_file_savegerber")
  6021. App.log.debug("on_file_savegerber()")
  6022. obj = self.collection.get_active()
  6023. if obj is None:
  6024. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6025. return
  6026. # Check for more compatible types and add as required
  6027. if not isinstance(obj, GerberObject):
  6028. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6029. return
  6030. name = self.collection.get_active().options["name"]
  6031. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6032. try:
  6033. filename, _f = FCFileSaveDialog.get_saved_filename(
  6034. caption="Save Gerber source file",
  6035. directory=self.get_last_save_folder() + '/' + name,
  6036. ext_filter=_filter)
  6037. except TypeError:
  6038. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  6039. filename = str(filename)
  6040. if filename == "":
  6041. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6042. return
  6043. else:
  6044. self.save_source_file(name, filename)
  6045. if self.defaults["global_open_style"] is False:
  6046. self.file_opened.emit("Gerber", filename)
  6047. self.file_saved.emit("Gerber", filename)
  6048. def on_file_savescript(self):
  6049. """
  6050. Callback for menu item in Project context menu.
  6051. :return: None
  6052. """
  6053. self.defaults.report_usage("on_file_savescript")
  6054. App.log.debug("on_file_savescript()")
  6055. obj = self.collection.get_active()
  6056. if obj is None:
  6057. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6058. return
  6059. # Check for more compatible types and add as required
  6060. if not isinstance(obj, ScriptObject):
  6061. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6062. return
  6063. name = self.collection.get_active().options["name"]
  6064. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6065. try:
  6066. filename, _f = FCFileSaveDialog.get_saved_filename(
  6067. caption="Save Script source file",
  6068. directory=self.get_last_save_folder() + '/' + name,
  6069. ext_filter=_filter)
  6070. except TypeError:
  6071. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  6072. filename = str(filename)
  6073. if filename == "":
  6074. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6075. return
  6076. else:
  6077. self.save_source_file(name, filename)
  6078. if self.defaults["global_open_style"] is False:
  6079. self.file_opened.emit("Script", filename)
  6080. self.file_saved.emit("Script", filename)
  6081. def on_file_savedocument(self):
  6082. """
  6083. Callback for menu item in Project context menu.
  6084. :return: None
  6085. """
  6086. self.defaults.report_usage("on_file_savedocument")
  6087. App.log.debug("on_file_savedocument()")
  6088. obj = self.collection.get_active()
  6089. if obj is None:
  6090. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6091. return
  6092. # Check for more compatible types and add as required
  6093. if not isinstance(obj, ScriptObject):
  6094. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6095. return
  6096. name = self.collection.get_active().options["name"]
  6097. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6098. try:
  6099. filename, _f = FCFileSaveDialog.get_saved_filename(
  6100. caption="Save Document source file",
  6101. directory=self.get_last_save_folder() + '/' + name,
  6102. ext_filter=_filter)
  6103. except TypeError:
  6104. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  6105. ext_filter=_filter)
  6106. filename = str(filename)
  6107. if filename == "":
  6108. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6109. return
  6110. else:
  6111. self.save_source_file(name, filename)
  6112. if self.defaults["global_open_style"] is False:
  6113. self.file_opened.emit("Document", filename)
  6114. self.file_saved.emit("Document", filename)
  6115. def on_file_saveexcellon(self):
  6116. """
  6117. Callback for menu item in project context menu.
  6118. :return: None
  6119. """
  6120. self.defaults.report_usage("on_file_saveexcellon")
  6121. App.log.debug("on_file_saveexcellon()")
  6122. obj = self.collection.get_active()
  6123. if obj is None:
  6124. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6125. return
  6126. # Check for more compatible types and add as required
  6127. if not isinstance(obj, ExcellonObject):
  6128. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6129. return
  6130. name = self.collection.get_active().options["name"]
  6131. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6132. try:
  6133. filename, _f = FCFileSaveDialog.get_saved_filename(
  6134. caption=_("Save Excellon source file"),
  6135. directory=self.get_last_save_folder() + '/' + name,
  6136. ext_filter=_filter)
  6137. except TypeError:
  6138. filename, _f = FCFileSaveDialog.get_saved_filename(
  6139. caption=_("Save Excellon source file"), ext_filter=_filter)
  6140. filename = str(filename)
  6141. if filename == "":
  6142. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6143. return
  6144. else:
  6145. self.save_source_file(name, filename)
  6146. if self.defaults["global_open_style"] is False:
  6147. self.file_opened.emit("Excellon", filename)
  6148. self.file_saved.emit("Excellon", filename)
  6149. def on_file_exportexcellon(self):
  6150. """
  6151. Callback for menu item File->Export->Excellon.
  6152. :return: None
  6153. """
  6154. self.defaults.report_usage("on_file_exportexcellon")
  6155. App.log.debug("on_file_exportexcellon()")
  6156. obj = self.collection.get_active()
  6157. if obj is None:
  6158. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6159. return
  6160. # Check for more compatible types and add as required
  6161. if not isinstance(obj, ExcellonObject):
  6162. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6163. return
  6164. name = self.collection.get_active().options["name"]
  6165. _filter = self.defaults["excellon_save_filters"]
  6166. try:
  6167. filename, _f = FCFileSaveDialog.get_saved_filename(
  6168. caption=_("Export Excellon"),
  6169. directory=self.get_last_save_folder() + '/' + name,
  6170. ext_filter=_filter)
  6171. except TypeError:
  6172. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  6173. filename = str(filename)
  6174. if filename == "":
  6175. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6176. return
  6177. else:
  6178. used_extension = filename.rpartition('.')[2]
  6179. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6180. self.export_excellon(name, filename)
  6181. if self.defaults["global_open_style"] is False:
  6182. self.file_opened.emit("Excellon", filename)
  6183. self.file_saved.emit("Excellon", filename)
  6184. def on_file_exportgerber(self):
  6185. """
  6186. Callback for menu item File->Export->Gerber.
  6187. :return: None
  6188. """
  6189. self.defaults.report_usage("on_file_exportgerber")
  6190. App.log.debug("on_file_exportgerber()")
  6191. obj = self.collection.get_active()
  6192. if obj is None:
  6193. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6194. return
  6195. # Check for more compatible types and add as required
  6196. if not isinstance(obj, GerberObject):
  6197. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6198. return
  6199. name = self.collection.get_active().options["name"]
  6200. _filter_ = self.defaults['gerber_save_filters']
  6201. try:
  6202. filename, _f = FCFileSaveDialog.get_saved_filename(
  6203. caption=_("Export Gerber"),
  6204. directory=self.get_last_save_folder() + '/' + name,
  6205. ext_filter=_filter_)
  6206. except TypeError:
  6207. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  6208. filename = str(filename)
  6209. if filename == "":
  6210. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6211. return
  6212. else:
  6213. used_extension = filename.rpartition('.')[2]
  6214. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6215. self.export_gerber(name, filename)
  6216. if self.defaults["global_open_style"] is False:
  6217. self.file_opened.emit("Gerber", filename)
  6218. self.file_saved.emit("Gerber", filename)
  6219. def on_file_exportdxf(self):
  6220. """
  6221. Callback for menu item File->Export DXF.
  6222. :return: None
  6223. """
  6224. self.defaults.report_usage("on_file_exportdxf")
  6225. App.log.debug("on_file_exportdxf()")
  6226. obj = self.collection.get_active()
  6227. if obj is None:
  6228. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6229. msg = _("Please Select a Geometry object to export")
  6230. msgbox = QtWidgets.QMessageBox()
  6231. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6232. msgbox.setInformativeText(msg)
  6233. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6234. msgbox.setDefaultButton(bt_ok)
  6235. msgbox.exec_()
  6236. return
  6237. # Check for more compatible types and add as required
  6238. if not isinstance(obj, GeometryObject):
  6239. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6240. msgbox = QtWidgets.QMessageBox()
  6241. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6242. msgbox.setInformativeText(msg)
  6243. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6244. msgbox.setDefaultButton(bt_ok)
  6245. msgbox.exec_()
  6246. return
  6247. name = self.collection.get_active().options["name"]
  6248. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6249. try:
  6250. filename, _f = FCFileSaveDialog.get_saved_filename(
  6251. caption=_("Export DXF"),
  6252. directory=self.get_last_save_folder() + '/' + name,
  6253. ext_filter=_filter_)
  6254. except TypeError:
  6255. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  6256. filename = str(filename)
  6257. if filename == "":
  6258. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6259. return
  6260. else:
  6261. self.export_dxf(name, filename)
  6262. if self.defaults["global_open_style"] is False:
  6263. self.file_opened.emit("DXF", filename)
  6264. self.file_saved.emit("DXF", filename)
  6265. def on_file_importsvg(self, type_of_obj):
  6266. """
  6267. Callback for menu item File->Import SVG.
  6268. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6269. :type type_of_obj: str
  6270. :return: None
  6271. """
  6272. self.defaults.report_usage("on_file_importsvg")
  6273. App.log.debug("on_file_importsvg()")
  6274. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6275. try:
  6276. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6277. directory=self.get_last_folder(), filter=_filter_)
  6278. except TypeError:
  6279. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6280. filter=_filter_)
  6281. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6282. type_of_obj = "geometry"
  6283. filenames = [str(filename) for filename in filenames]
  6284. if len(filenames) == 0:
  6285. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6286. else:
  6287. for filename in filenames:
  6288. if filename != '':
  6289. self.worker_task.emit({'fcn': self.import_svg,
  6290. 'params': [filename, type_of_obj]})
  6291. def on_file_importdxf(self, type_of_obj):
  6292. """
  6293. Callback for menu item File->Import DXF.
  6294. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6295. :type type_of_obj: str
  6296. :return: None
  6297. """
  6298. self.defaults.report_usage("on_file_importdxf")
  6299. App.log.debug("on_file_importdxf()")
  6300. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6301. try:
  6302. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6303. directory=self.get_last_folder(),
  6304. filter=_filter_)
  6305. except TypeError:
  6306. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6307. filter=_filter_)
  6308. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6309. type_of_obj = "geometry"
  6310. filenames = [str(filename) for filename in filenames]
  6311. if len(filenames) == 0:
  6312. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6313. else:
  6314. for filename in filenames:
  6315. if filename != '':
  6316. self.worker_task.emit({'fcn': self.import_dxf,
  6317. 'params': [filename, type_of_obj]})
  6318. # ###############################################################################################################
  6319. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6320. # ###############################################################################################################
  6321. def init_code_editor(self, name):
  6322. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  6323. # add the tab if it was closed
  6324. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6325. self.text_editor_tab.setObjectName('text_editor_tab')
  6326. # delete the absolute and relative position and messages in the infobar
  6327. # self.ui.position_label.setText("")
  6328. # self.ui.rel_position_label.setText("")
  6329. # hide coordinates toolbars in the infobar while in DB
  6330. self.ui.coords_toolbar.hide()
  6331. self.ui.delta_coords_toolbar.hide()
  6332. self.toggle_codeeditor = True
  6333. self.text_editor_tab.code_editor.completer_enable = False
  6334. self.text_editor_tab.buttonRun.hide()
  6335. # make sure to keep a reference to the code editor
  6336. self.reference_code_editor = self.text_editor_tab.code_editor
  6337. # Switch plot_area to CNCJob tab
  6338. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6339. def on_view_source(self):
  6340. """
  6341. Called when the user wants to see the source file of the selected object
  6342. :return:
  6343. """
  6344. try:
  6345. obj = self.collection.get_active()
  6346. except Exception as e:
  6347. log.debug("App.on_view_source() --> %s" % str(e))
  6348. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6349. return 'fail'
  6350. if obj is None:
  6351. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6352. return 'fail'
  6353. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6354. self.proc_container.view.set_busy(_("Loading..."))
  6355. flt = "All Files (*.*)"
  6356. if obj.kind == 'gerber':
  6357. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6358. elif obj.kind == 'excellon':
  6359. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6360. elif obj.kind == 'cncjob':
  6361. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6362. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  6363. # add the tab if it was closed
  6364. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6365. self.source_editor_tab.setObjectName('source_editor_tab')
  6366. # delete the absolute and relative position and messages in the infobar
  6367. # self.ui.position_label.setText("")
  6368. # self.ui.rel_position_label.setText("")
  6369. # hide coordinates toolbars in the infobar while in DB
  6370. self.ui.coords_toolbar.hide()
  6371. self.ui.delta_coords_toolbar.hide()
  6372. self.source_editor_tab.code_editor.completer_enable = False
  6373. self.source_editor_tab.buttonRun.hide()
  6374. # Switch plot_area to CNCJob tab
  6375. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6376. try:
  6377. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6378. except TypeError:
  6379. pass
  6380. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6381. try:
  6382. self.source_editor_tab.buttonSave.clicked.disconnect()
  6383. except TypeError:
  6384. pass
  6385. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6386. # then append the text from GCode to the text editor
  6387. if obj.kind == 'cncjob':
  6388. try:
  6389. file = obj.export_gcode(to_file=True)
  6390. if file == 'fail':
  6391. return 'fail'
  6392. except AttributeError:
  6393. self.inform.emit('[WARNING_NOTCL] %s' %
  6394. _("There is no selected object for which to see it's source file code."))
  6395. return 'fail'
  6396. else:
  6397. try:
  6398. file = StringIO(obj.source_file)
  6399. except (AttributeError, TypeError):
  6400. self.inform.emit('[WARNING_NOTCL] %s' %
  6401. _("There is no selected object for which to see it's source file code."))
  6402. return 'fail'
  6403. self.source_editor_tab.t_frame.hide()
  6404. try:
  6405. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  6406. except Exception as e:
  6407. log.debug('App.on_view_source() -->%s' % str(e))
  6408. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6409. return
  6410. self.source_editor_tab.t_frame.show()
  6411. self.proc_container.view.set_idle()
  6412. # self.ui.show()
  6413. def on_toggle_code_editor(self):
  6414. self.defaults.report_usage("on_toggle_code_editor()")
  6415. if self.toggle_codeeditor is False:
  6416. self.init_code_editor(name=_("Code Editor"))
  6417. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6418. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6419. self.text_editor_tab.buttonSave.clicked.disconnect()
  6420. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6421. else:
  6422. for idx in range(self.ui.plot_tab_area.count()):
  6423. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6424. self.ui.plot_tab_area.closeTab(idx)
  6425. break
  6426. self.toggle_codeeditor = False
  6427. def on_code_editor_close(self):
  6428. self.toggle_codeeditor = False
  6429. def goto_text_line(self):
  6430. """
  6431. Will scroll a text to the specified text line.
  6432. :return: None
  6433. """
  6434. dia_box = Dialog_box(title=_("Go to Line ..."),
  6435. label=_("Line:"),
  6436. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6437. initial_text='')
  6438. try:
  6439. line = int(dia_box.location) - 1
  6440. except (ValueError, TypeError):
  6441. line = 0
  6442. if dia_box.ok:
  6443. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6444. # at the top of the window
  6445. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6446. # get the document() of the AppTextEditor
  6447. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6448. # create a Text Cursor based on the searched line
  6449. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6450. # set cursor of the code editor with the cursor at the searcehd line
  6451. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6452. def on_filenewscript(self, silent=False):
  6453. """
  6454. Will create a new script file and open it in the Code Editor
  6455. :param silent: if True will not display status messages
  6456. :return: None
  6457. """
  6458. if silent is False:
  6459. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6460. # delete the absolute and relative position and messages in the infobar
  6461. # self.ui.position_label.setText("")
  6462. # self.ui.rel_position_label.setText("")
  6463. # hide coordinates toolbars in the infobar while in DB
  6464. self.ui.coords_toolbar.hide()
  6465. self.ui.delta_coords_toolbar.hide()
  6466. self.app_obj.new_script_object()
  6467. # script_text = script_obj.source_file
  6468. #
  6469. # self.proc_container.view.set_busy(_("Loading..."))
  6470. # script_obj.script_editor_tab.t_frame.hide()
  6471. #
  6472. # script_obj.script_editor_tab.t_frame.show()
  6473. # self.proc_container.view.set_idle()
  6474. def on_fileopenscript(self, name=None, silent=False):
  6475. """
  6476. Will open a Tcl script file into the Code Editor
  6477. :param silent: if True will not display status messages
  6478. :param name: name of a Tcl script file to open
  6479. :return: None
  6480. """
  6481. self.defaults.report_usage("on_fileopenscript")
  6482. App.log.debug("on_fileopenscript()")
  6483. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6484. "All Files (*.*)"
  6485. if name:
  6486. filenames = [name]
  6487. else:
  6488. try:
  6489. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6490. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6491. except TypeError:
  6492. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6493. if len(filenames) == 0:
  6494. if silent is False:
  6495. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6496. else:
  6497. for filename in filenames:
  6498. if filename != '':
  6499. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6500. def on_fileopenscript_example(self, name=None, silent=False):
  6501. """
  6502. Will open a Tcl script file into the Code Editor
  6503. :param silent: if True will not display status messages
  6504. :param name: name of a Tcl script file to open
  6505. :return:
  6506. """
  6507. self.defaults.report_usage("on_fileopenscript_example")
  6508. log.debug("on_fileopenscript_example()")
  6509. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6510. "All Files (*.*)"
  6511. # test if the app was frozen and choose the path for the configuration file
  6512. if getattr(sys, "frozen", False) is True:
  6513. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6514. else:
  6515. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6516. if name:
  6517. filenames = [name]
  6518. else:
  6519. try:
  6520. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6521. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6522. except TypeError:
  6523. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6524. if len(filenames) == 0:
  6525. if silent is False:
  6526. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6527. else:
  6528. for filename in filenames:
  6529. if filename != '':
  6530. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6531. def on_filerunscript(self, name=None, silent=False):
  6532. """
  6533. File menu callback for loading and running a TCL script.
  6534. :param silent: if True will not display status messages
  6535. :param name: name of a Tcl script file to be run by FlatCAM
  6536. :return: None
  6537. """
  6538. self.defaults.report_usage("on_filerunscript")
  6539. App.log.debug("on_file_runscript()")
  6540. if name:
  6541. filename = name
  6542. if self.cmd_line_headless != 1:
  6543. self.splash.showMessage('%s: %ssec\n%s' %
  6544. (_("Canvas initialization started.\n"
  6545. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6546. _("Executing ScriptObject file.")
  6547. ),
  6548. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6549. color=QtGui.QColor("gray"))
  6550. else:
  6551. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6552. "All Files (*.*)"
  6553. try:
  6554. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6555. directory=self.get_last_folder(), filter=_filter_)
  6556. except TypeError:
  6557. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6558. # The Qt methods above will return a QString which can cause problems later.
  6559. # So far json.dump() will fail to serialize it.
  6560. filename = str(filename)
  6561. if filename == "":
  6562. if silent is False:
  6563. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6564. else:
  6565. if self.cmd_line_headless != 1:
  6566. if self.ui.shell_dock.isHidden():
  6567. self.ui.shell_dock.show()
  6568. try:
  6569. with open(filename, "r") as tcl_script:
  6570. cmd_line_shellfile_content = tcl_script.read()
  6571. if self.cmd_line_headless != 1:
  6572. self.shell.exec_command(cmd_line_shellfile_content)
  6573. else:
  6574. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6575. if silent is False:
  6576. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6577. except Exception as e:
  6578. log.debug("App.on_filerunscript() -> %s" % str(e))
  6579. sys.exit(2)
  6580. def on_file_saveproject(self, silent=False):
  6581. """
  6582. Callback for menu item File->Save Project. Saves the project to
  6583. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6584. if set to None. The project is saved by calling ``self.save_project()``.
  6585. :param silent: if True will not display status messages
  6586. :return: None
  6587. """
  6588. self.defaults.report_usage("on_file_saveproject")
  6589. if self.project_filename is None:
  6590. self.on_file_saveprojectas()
  6591. else:
  6592. self.worker_task.emit({'fcn': self.save_project,
  6593. 'params': [self.project_filename, silent]})
  6594. if self.defaults["global_open_style"] is False:
  6595. self.file_opened.emit("project", self.project_filename)
  6596. self.file_saved.emit("project", self.project_filename)
  6597. self.set_ui_title(name=self.project_filename)
  6598. self.should_we_save = False
  6599. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6600. """
  6601. Callback for menu item File->Save Project As... Opens a file
  6602. chooser and saves the project to the given file via
  6603. ``self.save_project()``.
  6604. :param make_copy if to be create a copy of the project; boolean
  6605. :param use_thread: if to be run in a separate thread; boolean
  6606. :param quit_action: if to be followed by quiting the application; boolean
  6607. :return: None
  6608. """
  6609. self.defaults.report_usage("on_file_saveprojectas")
  6610. self.date = str(datetime.today()).rpartition('.')[0]
  6611. self.date = ''.join(c for c in self.date if c not in ':-')
  6612. self.date = self.date.replace(' ', '_')
  6613. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6614. try:
  6615. filename, _f = FCFileSaveDialog.get_saved_filename(
  6616. caption=_("Save Project As ..."),
  6617. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6618. proj=_("Project")),
  6619. ext_filter=filter_
  6620. )
  6621. except TypeError:
  6622. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6623. filename = str(filename)
  6624. if filename == '':
  6625. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6626. return
  6627. if use_thread is True:
  6628. self.worker_task.emit({'fcn': self.save_project,
  6629. 'params': [filename, quit_action]})
  6630. else:
  6631. self.save_project(filename, quit_action)
  6632. # self.save_project(filename)
  6633. if self.defaults["global_open_style"] is False:
  6634. self.file_opened.emit("project", filename)
  6635. self.file_saved.emit("project", filename)
  6636. if not make_copy:
  6637. self.project_filename = filename
  6638. self.set_ui_title(name=self.project_filename)
  6639. self.should_we_save = False
  6640. def on_file_save_objects_pdf(self, use_thread=True):
  6641. self.date = str(datetime.today()).rpartition('.')[0]
  6642. self.date = ''.join(c for c in self.date if c not in ':-')
  6643. self.date = self.date.replace(' ', '_')
  6644. try:
  6645. obj_selection = self.collection.get_selected()
  6646. if len(obj_selection) == 1:
  6647. obj_name = str(obj_selection[0].options['name'])
  6648. else:
  6649. obj_name = _("FlatCAM objects print")
  6650. except AttributeError as err:
  6651. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6652. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6653. return
  6654. if not obj_selection:
  6655. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6656. return
  6657. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6658. try:
  6659. filename, _f = FCFileSaveDialog.get_saved_filename(
  6660. caption=_("Save Object as PDF ..."),
  6661. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6662. obj_name=obj_name,
  6663. date=self.date),
  6664. ext_filter=filter_
  6665. )
  6666. except TypeError:
  6667. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6668. filename = str(filename)
  6669. if filename == '':
  6670. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6671. return
  6672. if use_thread is True:
  6673. self.proc_container.new(_("Printing PDF ... Please wait."))
  6674. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6675. else:
  6676. self.save_pdf(filename, obj_selection)
  6677. # self.save_project(filename)
  6678. if self.defaults["global_open_style"] is False:
  6679. self.file_opened.emit("pdf", filename)
  6680. self.file_saved.emit("pdf", filename)
  6681. def save_pdf(self, file_name, obj_selection):
  6682. p_size = self.defaults['global_workspaceT']
  6683. orientation = self.defaults['global_workspace_orientation']
  6684. color = 'black'
  6685. transparency_level = 1.0
  6686. self.pagesize = {}
  6687. self.pagesize.update(
  6688. {
  6689. 'Bounds': None,
  6690. 'A0': (841 * mm, 1189 * mm),
  6691. 'A1': (594 * mm, 841 * mm),
  6692. 'A2': (420 * mm, 594 * mm),
  6693. 'A3': (297 * mm, 420 * mm),
  6694. 'A4': (210 * mm, 297 * mm),
  6695. 'A5': (148 * mm, 210 * mm),
  6696. 'A6': (105 * mm, 148 * mm),
  6697. 'A7': (74 * mm, 105 * mm),
  6698. 'A8': (52 * mm, 74 * mm),
  6699. 'A9': (37 * mm, 52 * mm),
  6700. 'A10': (26 * mm, 37 * mm),
  6701. 'B0': (1000 * mm, 1414 * mm),
  6702. 'B1': (707 * mm, 1000 * mm),
  6703. 'B2': (500 * mm, 707 * mm),
  6704. 'B3': (353 * mm, 500 * mm),
  6705. 'B4': (250 * mm, 353 * mm),
  6706. 'B5': (176 * mm, 250 * mm),
  6707. 'B6': (125 * mm, 176 * mm),
  6708. 'B7': (88 * mm, 125 * mm),
  6709. 'B8': (62 * mm, 88 * mm),
  6710. 'B9': (44 * mm, 62 * mm),
  6711. 'B10': (31 * mm, 44 * mm),
  6712. 'C0': (917 * mm, 1297 * mm),
  6713. 'C1': (648 * mm, 917 * mm),
  6714. 'C2': (458 * mm, 648 * mm),
  6715. 'C3': (324 * mm, 458 * mm),
  6716. 'C4': (229 * mm, 324 * mm),
  6717. 'C5': (162 * mm, 229 * mm),
  6718. 'C6': (114 * mm, 162 * mm),
  6719. 'C7': (81 * mm, 114 * mm),
  6720. 'C8': (57 * mm, 81 * mm),
  6721. 'C9': (40 * mm, 57 * mm),
  6722. 'C10': (28 * mm, 40 * mm),
  6723. # American paper sizes
  6724. 'LETTER': (8.5 * inch, 11 * inch),
  6725. 'LEGAL': (8.5 * inch, 14 * inch),
  6726. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6727. # From https://en.wikipedia.org/wiki/Paper_size
  6728. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6729. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6730. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6731. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6732. 'LEDGER': (17 * inch, 11 * inch),
  6733. }
  6734. )
  6735. exported_svg = []
  6736. for obj in obj_selection:
  6737. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6738. scale_factor_x=None, scale_factor_y=None,
  6739. skew_factor_x=None, skew_factor_y=None,
  6740. mirror=None)
  6741. if obj.kind.lower() == 'gerber':
  6742. # color = self.defaults["gerber_plot_fill"][:-2]
  6743. color = obj.fill_color[:-2]
  6744. elif obj.kind.lower() == 'excellon':
  6745. color = '#C40000'
  6746. elif obj.kind.lower() == 'geometry':
  6747. color = self.defaults["global_draw_color"]
  6748. # Change the attributes of the exported SVG
  6749. # We don't need stroke-width
  6750. # We set opacity to maximum
  6751. # We set the colour to WHITE
  6752. root = ET.fromstring(svg_obj)
  6753. for child in root:
  6754. child.set('fill', str(color))
  6755. child.set('opacity', str(transparency_level))
  6756. child.set('stroke', str(color))
  6757. exported_svg.append(ET.tostring(root))
  6758. xmin = Inf
  6759. ymin = Inf
  6760. xmax = -Inf
  6761. ymax = -Inf
  6762. for obj in obj_selection:
  6763. try:
  6764. gxmin, gymin, gxmax, gymax = obj.bounds()
  6765. xmin = min([xmin, gxmin])
  6766. ymin = min([ymin, gymin])
  6767. xmax = max([xmax, gxmax])
  6768. ymax = max([ymax, gymax])
  6769. except Exception as e:
  6770. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6771. # Determine bounding area for svg export
  6772. bounds = [xmin, ymin, xmax, ymax]
  6773. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6774. # This contain the measure units
  6775. uom = obj_selection[0].units.lower()
  6776. # Define a boundary around SVG of about 1.0mm (~39mils)
  6777. if uom in "mm":
  6778. boundary = 1.0
  6779. else:
  6780. boundary = 0.0393701
  6781. # Convert everything to strings for use in the xml doc
  6782. svgwidth = str(size[0] + (2 * boundary))
  6783. svgheight = str(size[1] + (2 * boundary))
  6784. minx = str(bounds[0] - boundary)
  6785. miny = str(bounds[1] + boundary + size[1])
  6786. # Add a SVG Header and footer to the svg output from shapely
  6787. # The transform flips the Y Axis so that everything renders
  6788. # properly within svg apps such as inkscape
  6789. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6790. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6791. svg_header += 'width="' + svgwidth + uom + '" '
  6792. svg_header += 'height="' + svgheight + uom + '" '
  6793. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6794. svg_header += '>'
  6795. svg_header += '<g transform="scale(1,-1)">'
  6796. svg_footer = '</g> </svg>'
  6797. svg_elem = str(svg_header)
  6798. for svg_item in exported_svg:
  6799. svg_elem += str(svg_item)
  6800. svg_elem += str(svg_footer)
  6801. # Parse the xml through a xml parser just to add line feeds
  6802. # and to make it look more pretty for the output
  6803. doc = parse_xml_string(svg_elem)
  6804. doc_final = doc.toprettyxml()
  6805. try:
  6806. if self.defaults['units'].upper() == 'IN':
  6807. unit = inch
  6808. else:
  6809. unit = mm
  6810. doc_final = StringIO(doc_final)
  6811. drawing = svg2rlg(doc_final)
  6812. if p_size == 'Bounds':
  6813. renderPDF.drawToFile(drawing, file_name)
  6814. else:
  6815. if orientation == 'p':
  6816. page_size = portrait(self.pagesize[p_size])
  6817. else:
  6818. page_size = landscape(self.pagesize[p_size])
  6819. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6820. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6821. renderPDF.draw(drawing, my_canvas, 0, 0)
  6822. my_canvas.save()
  6823. except Exception as e:
  6824. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6825. return 'fail'
  6826. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6827. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6828. """
  6829. Exports a Geometry Object to an SVG file.
  6830. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6831. :param filename: Path to the SVG file to save to.
  6832. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6833. :return:
  6834. """
  6835. self.defaults.report_usage("export_svg()")
  6836. if filename is None:
  6837. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6838. is not None else self.defaults["global_last_folder"]
  6839. self.log.debug("export_svg()")
  6840. try:
  6841. obj = self.collection.get_by_name(str(obj_name))
  6842. except Exception:
  6843. # TODO: The return behavior has not been established... should raise exception?
  6844. return "Could not retrieve object: %s" % obj_name
  6845. with self.proc_container.new(_("Exporting SVG")) as proc:
  6846. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6847. # Determine bounding area for svg export
  6848. bounds = obj.bounds()
  6849. size = obj.size()
  6850. # Convert everything to strings for use in the xml doc
  6851. svgwidth = str(size[0])
  6852. svgheight = str(size[1])
  6853. minx = str(bounds[0])
  6854. miny = str(bounds[1] - size[1])
  6855. uom = obj.units.lower()
  6856. # Add a SVG Header and footer to the svg output from shapely
  6857. # The transform flips the Y Axis so that everything renders
  6858. # properly within svg apps such as inkscape
  6859. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6860. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6861. svg_header += 'width="' + svgwidth + uom + '" '
  6862. svg_header += 'height="' + svgheight + uom + '" '
  6863. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6864. svg_header += '<g transform="scale(1,-1)">'
  6865. svg_footer = '</g> </svg>'
  6866. svg_elem = svg_header + exported_svg + svg_footer
  6867. # Parse the xml through a xml parser just to add line feeds
  6868. # and to make it look more pretty for the output
  6869. svgcode = parse_xml_string(svg_elem)
  6870. svgcode = svgcode.toprettyxml()
  6871. try:
  6872. with open(filename, 'w') as fp:
  6873. fp.write(svgcode)
  6874. except PermissionError:
  6875. self.inform.emit('[WARNING] %s' %
  6876. _("Permission denied, saving not possible.\n"
  6877. "Most likely another app is holding the file open and not accessible."))
  6878. return 'fail'
  6879. if self.defaults["global_open_style"] is False:
  6880. self.file_opened.emit("SVG", filename)
  6881. self.file_saved.emit("SVG", filename)
  6882. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6883. def save_source_file(self, obj_name, filename, use_thread=True):
  6884. """
  6885. Exports a FlatCAM Object to an Gerber/Excellon file.
  6886. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6887. :param filename: Path to the Gerber file to save to.
  6888. :param use_thread: if to be run in a separate thread
  6889. :return:
  6890. """
  6891. self.defaults.report_usage("save source file()")
  6892. if filename is None:
  6893. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6894. is not None else self.defaults["global_last_folder"]
  6895. self.log.debug("save source file()")
  6896. obj = self.collection.get_by_name(obj_name)
  6897. file_string = StringIO(obj.source_file)
  6898. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6899. if file_string.getvalue() == '':
  6900. self.inform.emit('[ERROR_NOTCL] %s' %
  6901. _("Save cancelled because source file is empty. Try to export the file."))
  6902. return 'fail'
  6903. try:
  6904. with open(filename, 'w') as file:
  6905. file.writelines('G04*\n')
  6906. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6907. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6908. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6909. file.writelines('G04 Created on : %s*\n' % time_string)
  6910. for line in file_string:
  6911. file.writelines(line)
  6912. except PermissionError:
  6913. self.inform.emit('[WARNING] %s' %
  6914. _("Permission denied, saving not possible.\n"
  6915. "Most likely another app is holding the file open and not accessible."))
  6916. return 'fail'
  6917. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6918. """
  6919. Exports a Excellon Object to an Excellon file.
  6920. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6921. :param filename: Path to the Excellon file to save to.
  6922. :param local_use:
  6923. :param use_thread: if to be run in a separate thread
  6924. :return:
  6925. """
  6926. self.defaults.report_usage("export_excellon()")
  6927. if filename is None:
  6928. if self.defaults["global_last_save_folder"]:
  6929. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6930. else:
  6931. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6932. self.log.debug("export_excellon()")
  6933. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6934. self.defaults["excellon_exp_decimals"]
  6935. )
  6936. if local_use is None:
  6937. try:
  6938. obj = self.collection.get_by_name(str(obj_name))
  6939. except Exception:
  6940. return "Could not retrieve object: %s" % obj_name
  6941. else:
  6942. obj = local_use
  6943. if not isinstance(obj, ExcellonObject):
  6944. self.inform.emit('[ERROR_NOTCL] %s' %
  6945. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6946. return
  6947. # updated units
  6948. eunits = self.defaults["excellon_exp_units"]
  6949. ewhole = self.defaults["excellon_exp_integer"]
  6950. efract = self.defaults["excellon_exp_decimals"]
  6951. ezeros = self.defaults["excellon_exp_zeros"]
  6952. eformat = self.defaults["excellon_exp_format"]
  6953. slot_type = self.defaults["excellon_exp_slot_type"]
  6954. fc_units = self.defaults['units'].upper()
  6955. if fc_units == 'MM':
  6956. factor = 1 if eunits == 'METRIC' else 0.03937
  6957. else:
  6958. factor = 25.4 if eunits == 'METRIC' else 1
  6959. def make_excellon():
  6960. try:
  6961. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6962. header = 'M48\n'
  6963. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6964. (str(self.version), str(self.version_date))
  6965. header += ';Filename: %s' % str(obj_name) + '\n'
  6966. header += ';Created on : %s' % time_str + '\n'
  6967. if eformat == 'dec':
  6968. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6969. header += eunits + '\n'
  6970. for tool in obj.tools:
  6971. if eunits == 'METRIC':
  6972. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6973. tool=str(tool),
  6974. dec=2)
  6975. else:
  6976. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6977. tool=str(tool),
  6978. dec=4)
  6979. else:
  6980. if ezeros == 'LZ':
  6981. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6982. form='ndec', e_zeros='LZ', factor=factor,
  6983. slot_type=slot_type)
  6984. header += '%s,%s\n' % (eunits, 'LZ')
  6985. header += format_exc
  6986. for tool in obj.tools:
  6987. if eunits == 'METRIC':
  6988. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6989. float(obj.tools[tool]['tooldia']) * factor,
  6990. tool=str(tool),
  6991. dec=2)
  6992. else:
  6993. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6994. float(obj.tools[tool]['tooldia']) * factor,
  6995. tool=str(tool),
  6996. dec=4)
  6997. else:
  6998. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6999. form='ndec', e_zeros='TZ', factor=factor,
  7000. slot_type=slot_type)
  7001. header += '%s,%s\n' % (eunits, 'TZ')
  7002. header += format_exc
  7003. for tool in obj.tools:
  7004. if eunits == 'METRIC':
  7005. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7006. float(obj.tools[tool]['tooldia']) * factor,
  7007. tool=str(tool),
  7008. dec=2)
  7009. else:
  7010. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7011. float(obj.tools[tool]['tooldia']) * factor,
  7012. tool=str(tool),
  7013. dec=4)
  7014. header += '%\n'
  7015. footer = 'M30\n'
  7016. exported_excellon = header
  7017. exported_excellon += excellon_code
  7018. exported_excellon += footer
  7019. if local_use is None:
  7020. try:
  7021. with open(filename, 'w') as fp:
  7022. fp.write(exported_excellon)
  7023. except PermissionError:
  7024. self.inform.emit('[WARNING] %s' %
  7025. _("Permission denied, saving not possible.\n"
  7026. "Most likely another app is holding the file open and not accessible."))
  7027. return 'fail'
  7028. if self.defaults["global_open_style"] is False:
  7029. self.file_opened.emit("Excellon", filename)
  7030. self.file_saved.emit("Excellon", filename)
  7031. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7032. else:
  7033. return exported_excellon
  7034. except Exception as e:
  7035. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7036. return 'fail'
  7037. if use_thread is True:
  7038. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7039. def job_thread_exc(app_obj):
  7040. ret = make_excellon()
  7041. if ret == 'fail':
  7042. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7043. return
  7044. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7045. else:
  7046. eret = make_excellon()
  7047. if eret == 'fail':
  7048. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7049. return 'fail'
  7050. if local_use is not None:
  7051. return eret
  7052. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7053. """
  7054. Exports a Gerber Object to an Gerber file.
  7055. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7056. :param filename: Path to the Gerber file to save to.
  7057. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7058. When not None, the value will be the actual Gerber object for which to create
  7059. the Gerber code
  7060. :param use_thread: if to be run in a separate thread
  7061. :return:
  7062. """
  7063. self.defaults.report_usage("export_gerber()")
  7064. if filename is None:
  7065. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7066. is not None else self.defaults["global_last_folder"]
  7067. self.log.debug("export_gerber()")
  7068. if local_use is None:
  7069. try:
  7070. obj = self.collection.get_by_name(str(obj_name))
  7071. except Exception:
  7072. return 'fail'
  7073. else:
  7074. obj = local_use
  7075. # updated units
  7076. gunits = self.defaults["gerber_exp_units"]
  7077. gwhole = self.defaults["gerber_exp_integer"]
  7078. gfract = self.defaults["gerber_exp_decimals"]
  7079. gzeros = self.defaults["gerber_exp_zeros"]
  7080. fc_units = self.defaults['units'].upper()
  7081. if fc_units == 'MM':
  7082. factor = 1 if gunits == 'MM' else 0.03937
  7083. else:
  7084. factor = 25.4 if gunits == 'MM' else 1
  7085. def make_gerber():
  7086. try:
  7087. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7088. header = 'G04*\n'
  7089. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7090. (str(self.version), str(self.version_date))
  7091. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7092. header += 'G04 Created on : %s*' % time_str + '\n'
  7093. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7094. header += "%MO{units}*%\n".format(units=gunits)
  7095. for apid in obj.apertures:
  7096. if obj.apertures[apid]['type'] == 'C':
  7097. header += "%ADD{apid}{type},{size}*%\n".format(
  7098. apid=str(apid),
  7099. type='C',
  7100. size=(factor * obj.apertures[apid]['size'])
  7101. )
  7102. elif obj.apertures[apid]['type'] == 'R':
  7103. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7104. apid=str(apid),
  7105. type='R',
  7106. width=(factor * obj.apertures[apid]['width']),
  7107. height=(factor * obj.apertures[apid]['height'])
  7108. )
  7109. elif obj.apertures[apid]['type'] == 'O':
  7110. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7111. apid=str(apid),
  7112. type='O',
  7113. width=(factor * obj.apertures[apid]['width']),
  7114. height=(factor * obj.apertures[apid]['height'])
  7115. )
  7116. header += '\n'
  7117. # obsolete units but some software may need it
  7118. if gunits == 'IN':
  7119. header += 'G70*\n'
  7120. else:
  7121. header += 'G71*\n'
  7122. # Absolute Mode
  7123. header += 'G90*\n'
  7124. header += 'G01*\n'
  7125. # positive polarity
  7126. header += '%LPD*%\n'
  7127. footer = 'M02*\n'
  7128. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7129. exported_gerber = header
  7130. exported_gerber += gerber_code
  7131. exported_gerber += footer
  7132. if local_use is None:
  7133. try:
  7134. with open(filename, 'w') as fp:
  7135. fp.write(exported_gerber)
  7136. except PermissionError:
  7137. self.inform.emit('[WARNING] %s' %
  7138. _("Permission denied, saving not possible.\n"
  7139. "Most likely another app is holding the file open and not accessible."))
  7140. return 'fail'
  7141. if self.defaults["global_open_style"] is False:
  7142. self.file_opened.emit("Gerber", filename)
  7143. self.file_saved.emit("Gerber", filename)
  7144. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7145. else:
  7146. return exported_gerber
  7147. except Exception as e:
  7148. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7149. return 'fail'
  7150. if use_thread is True:
  7151. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7152. def job_thread_grb(app_obj):
  7153. ret = make_gerber()
  7154. if ret == 'fail':
  7155. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7156. return
  7157. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7158. else:
  7159. gret = make_gerber()
  7160. if gret == 'fail':
  7161. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7162. return 'fail'
  7163. if local_use is not None:
  7164. return gret
  7165. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  7166. """
  7167. Exports a Geometry Object to an DXF file.
  7168. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7169. :param filename: Path to the DXF file to save to.
  7170. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7171. When not None, the value will be the actual Geometry object for which to create
  7172. the Geometry/DXF code
  7173. :param use_thread: if to be run in a separate thread
  7174. :return:
  7175. """
  7176. self.defaults.report_usage("export_dxf()")
  7177. if filename is None:
  7178. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7179. is not None else self.defaults["global_last_folder"]
  7180. self.log.debug("export_dxf()")
  7181. if local_use is None:
  7182. try:
  7183. obj = self.collection.get_by_name(str(obj_name))
  7184. except Exception:
  7185. return 'fail'
  7186. else:
  7187. obj = local_use
  7188. def make_dxf():
  7189. try:
  7190. dxf_code = obj.export_dxf()
  7191. if local_use is None:
  7192. try:
  7193. dxf_code.saveas(filename)
  7194. except PermissionError:
  7195. self.inform.emit('[WARNING] %s' %
  7196. _("Permission denied, saving not possible.\n"
  7197. "Most likely another app is holding the file open and not accessible."))
  7198. return 'fail'
  7199. if self.defaults["global_open_style"] is False:
  7200. self.file_opened.emit("DXF", filename)
  7201. self.file_saved.emit("DXF", filename)
  7202. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7203. else:
  7204. return dxf_code
  7205. except Exception as e:
  7206. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  7207. return 'fail'
  7208. if use_thread is True:
  7209. with self.proc_container.new(_("Exporting DXF")) as proc:
  7210. def job_thread_exc(app_obj):
  7211. ret_dxf_val = make_dxf()
  7212. if ret_dxf_val == 'fail':
  7213. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7214. return
  7215. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7216. else:
  7217. ret = make_dxf()
  7218. if ret == 'fail':
  7219. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7220. return
  7221. if local_use is not None:
  7222. return ret
  7223. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7224. """
  7225. Adds a new Geometry Object to the projects and populates
  7226. it with shapes extracted from the SVG file.
  7227. :param plot: If True then the resulting object will be plotted on canvas
  7228. :param filename: Path to the SVG file.
  7229. :param geo_type: Type of FlatCAM object that will be created from SVG
  7230. :param outname: The name given to the resulting FlatCAM object
  7231. :return:
  7232. """
  7233. self.defaults.report_usage("import_svg()")
  7234. log.debug("App.import_svg()")
  7235. obj_type = ""
  7236. if geo_type is None or geo_type == "geometry":
  7237. obj_type = "geometry"
  7238. elif geo_type == "gerber":
  7239. obj_type = "gerber"
  7240. else:
  7241. self.inform.emit('[ERROR_NOTCL] %s' %
  7242. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7243. return
  7244. units = self.defaults['units'].upper()
  7245. def obj_init(geo_obj, app_obj):
  7246. if obj_type == "geometry":
  7247. geo_obj.import_svg(filename, obj_type, units=units)
  7248. elif obj_type == "gerber":
  7249. geo_obj.import_svg(filename, obj_type, units=units)
  7250. geo_obj.multigeo = True
  7251. with open(filename) as f:
  7252. file_content = f.read()
  7253. geo_obj.source_file = file_content
  7254. with self.proc_container.new(_("Importing SVG")) as proc:
  7255. # Object name
  7256. name = outname or filename.split('/')[-1].split('\\')[-1]
  7257. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7258. if ret == 'fail':
  7259. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7260. return 'fail'
  7261. # Register recent file
  7262. self.file_opened.emit("svg", filename)
  7263. # appGUI feedback
  7264. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7265. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7266. """
  7267. Adds a new Geometry Object to the projects and populates
  7268. it with shapes extracted from the DXF file.
  7269. :param filename: Path to the DXF file.
  7270. :param geo_type: Type of FlatCAM object that will be created from DXF
  7271. :param outname: Name for the imported Geometry
  7272. :param plot: If True then the resulting object will be plotted on canvas
  7273. :return:
  7274. """
  7275. log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  7276. obj_type = ""
  7277. if geo_type is None or geo_type == "geometry":
  7278. obj_type = "geometry"
  7279. elif geo_type == "gerber":
  7280. obj_type = geo_type
  7281. else:
  7282. self.inform.emit('[ERROR_NOTCL] %s' %
  7283. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7284. return
  7285. units = self.defaults['units'].upper()
  7286. def obj_init(geo_obj, app_obj):
  7287. if obj_type == "geometry":
  7288. geo_obj.import_dxf_as_geo(filename, units=units)
  7289. elif obj_type == "gerber":
  7290. geo_obj.import_dxf_as_gerber(filename, units=units)
  7291. else:
  7292. return "fail"
  7293. geo_obj.multigeo = True
  7294. with open(filename) as f:
  7295. file_content = f.read()
  7296. geo_obj.source_file = file_content
  7297. with self.proc_container.new(_("Importing DXF")):
  7298. # Object name
  7299. name = outname or filename.split('/')[-1].split('\\')[-1]
  7300. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7301. if ret == 'fail':
  7302. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7303. return 'fail'
  7304. # Register recent file
  7305. self.file_opened.emit("dxf", filename)
  7306. # appGUI feedback
  7307. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7308. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7309. """
  7310. Opens a Gerber file, parses it and creates a new object for
  7311. it in the program. Thread-safe.
  7312. :param outname: Name of the resulting object. None causes the
  7313. name to be that of the file. Str.
  7314. :param filename: Gerber file filename
  7315. :type filename: str
  7316. :param plot: boolean, to plot or not the resulting object
  7317. :param from_tcl: True if run from Tcl Shell
  7318. :return: None
  7319. """
  7320. # How the object should be initialized
  7321. def obj_init(gerber_obj, app_obj):
  7322. assert isinstance(gerber_obj, GerberObject), \
  7323. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7324. # Opening the file happens here
  7325. try:
  7326. gerber_obj.parse_file(filename)
  7327. except IOError:
  7328. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7329. return "fail"
  7330. except ParseError as err:
  7331. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7332. app_obj.log.error(str(err))
  7333. return "fail"
  7334. except Exception as e:
  7335. log.debug("App.open_gerber() --> %s" % str(e))
  7336. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7337. msg += traceback.format_exc()
  7338. app_obj.inform.emit(msg)
  7339. return "fail"
  7340. if gerber_obj.is_empty():
  7341. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7342. _("Object is not Gerber file or empty. Aborting object creation."))
  7343. return "fail"
  7344. App.log.debug("open_gerber()")
  7345. with self.proc_container.new(_("Opening Gerber")):
  7346. # Object name
  7347. name = outname or filename.split('/')[-1].split('\\')[-1]
  7348. # # ## Object creation # ##
  7349. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7350. if ret_val == 'fail':
  7351. if from_tcl:
  7352. filename = self.defaults['global_tcl_path'] + '/' + name
  7353. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7354. if ret_val == 'fail':
  7355. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7356. return 'fail'
  7357. # Register recent file
  7358. self.file_opened.emit("gerber", filename)
  7359. # appGUI feedback
  7360. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7361. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7362. """
  7363. Opens an Excellon file, parses it and creates a new object for
  7364. it in the program. Thread-safe.
  7365. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7366. :param filename: Excellon file filename
  7367. :type filename: str
  7368. :param plot: boolean, to plot or not the resulting object
  7369. :param from_tcl: True if run from Tcl Shell
  7370. :return: None
  7371. """
  7372. App.log.debug("open_excellon()")
  7373. # How the object should be initialized
  7374. def obj_init(excellon_obj, app_obj):
  7375. try:
  7376. ret = excellon_obj.parse_file(filename=filename)
  7377. if ret == "fail":
  7378. log.debug("Excellon parsing failed.")
  7379. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  7380. return "fail"
  7381. except IOError:
  7382. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  7383. log.debug("Could not open Excellon object.")
  7384. return "fail"
  7385. except Exception:
  7386. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7387. msg += traceback.format_exc()
  7388. app_obj.inform.emit(msg)
  7389. return "fail"
  7390. ret = excellon_obj.create_geometry()
  7391. if ret == 'fail':
  7392. log.debug("Could not create geometry for Excellon object.")
  7393. return "fail"
  7394. for tool in excellon_obj.tools:
  7395. if excellon_obj.tools[tool]['solid_geometry']:
  7396. return
  7397. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7398. return "fail"
  7399. with self.proc_container.new(_("Opening Excellon.")):
  7400. # Object name
  7401. name = outname or filename.split('/')[-1].split('\\')[-1]
  7402. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7403. if ret_val == 'fail':
  7404. if from_tcl:
  7405. filename = self.defaults['global_tcl_path'] + '/' + name
  7406. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7407. if ret_val == 'fail':
  7408. self.inform.emit('[ERROR_NOTCL] %s' %
  7409. _('Open Excellon file failed. Probable not an Excellon file.'))
  7410. return
  7411. # Register recent file
  7412. self.file_opened.emit("excellon", filename)
  7413. # appGUI feedback
  7414. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7415. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7416. """
  7417. Opens a G-gcode file, parses it and creates a new object for
  7418. it in the program. Thread-safe.
  7419. :param filename: G-code file filename
  7420. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7421. :param force_parsing:
  7422. :param plot: If True plot the object on canvas
  7423. :param from_tcl: True if run from Tcl Shell
  7424. :return: None
  7425. """
  7426. App.log.debug("open_gcode()")
  7427. # How the object should be initialized
  7428. def obj_init(job_obj, app_obj_):
  7429. """
  7430. :param job_obj: the resulting object
  7431. :type app_obj_: App
  7432. """
  7433. assert isinstance(app_obj_, App), \
  7434. "Initializer expected App, got %s" % type(app_obj_)
  7435. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7436. try:
  7437. f = open(filename)
  7438. gcode = f.read()
  7439. f.close()
  7440. except IOError:
  7441. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7442. return "fail"
  7443. job_obj.gcode = gcode
  7444. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7445. if gcode_ret == "fail":
  7446. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7447. return "fail"
  7448. job_obj.create_geometry()
  7449. with self.proc_container.new(_("Opening G-Code.")):
  7450. # Object name
  7451. name = outname or filename.split('/')[-1].split('\\')[-1]
  7452. # New object creation and file processing
  7453. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7454. if ret_val == 'fail':
  7455. if from_tcl:
  7456. filename = self.defaults['global_tcl_path'] + '/' + name
  7457. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7458. if ret_val == 'fail':
  7459. self.inform.emit('[ERROR_NOTCL] %s' %
  7460. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7461. "Try to load it from File menu.\n "
  7462. "Attempting to create a FlatCAM CNCJob Object from "
  7463. "G-Code file failed during processing"))
  7464. return "fail"
  7465. # Register recent file
  7466. self.file_opened.emit("cncjob", filename)
  7467. # appGUI feedback
  7468. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7469. def open_hpgl2(self, filename, outname=None):
  7470. """
  7471. Opens a HPGL2 file, parses it and creates a new object for
  7472. it in the program. Thread-safe.
  7473. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7474. :param filename: HPGL2 file filename
  7475. :return: None
  7476. """
  7477. filename = filename
  7478. # How the object should be initialized
  7479. def obj_init(geo_obj, app_obj):
  7480. assert isinstance(geo_obj, GeometryObject), \
  7481. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7482. # Opening the file happens here
  7483. obj = HPGL2(self)
  7484. try:
  7485. HPGL2.parse_file(obj, filename)
  7486. except IOError:
  7487. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7488. return "fail"
  7489. except ParseError as err:
  7490. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7491. app_obj.log.error(str(err))
  7492. return "fail"
  7493. except Exception as e:
  7494. log.debug("App.open_hpgl2() --> %s" % str(e))
  7495. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7496. msg += traceback.format_exc()
  7497. app_obj.inform.emit(msg)
  7498. return "fail"
  7499. geo_obj.multigeo = True
  7500. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7501. geo_obj.tools = deepcopy(obj.tools)
  7502. geo_obj.source_file = deepcopy(obj.source_file)
  7503. del obj
  7504. if not geo_obj.solid_geometry:
  7505. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7506. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7507. return "fail"
  7508. App.log.debug("open_hpgl2()")
  7509. with self.proc_container.new(_("Opening HPGL2")):
  7510. # Object name
  7511. name = outname or filename.split('/')[-1].split('\\')[-1]
  7512. # # ## Object creation # ##
  7513. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7514. if ret == 'fail':
  7515. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7516. return 'fail'
  7517. # Register recent file
  7518. self.file_opened.emit("geometry", filename)
  7519. # appGUI feedback
  7520. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7521. def open_script(self, filename, outname=None, silent=False):
  7522. """
  7523. Opens a Script file, parses it and creates a new object for
  7524. it in the program. Thread-safe.
  7525. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7526. :param filename: Script file filename
  7527. :param silent: If True there will be no messages printed to StatusBar
  7528. :return: None
  7529. """
  7530. def obj_init(script_obj, app_obj):
  7531. assert isinstance(script_obj, ScriptObject), \
  7532. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7533. if silent is False:
  7534. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7535. try:
  7536. script_obj.parse_file(filename)
  7537. except IOError:
  7538. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7539. return "fail"
  7540. except ParseError as err:
  7541. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7542. app_obj.log.error(str(err))
  7543. return "fail"
  7544. except Exception as e:
  7545. log.debug("App.open_script() -> %s" % str(e))
  7546. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7547. msg += traceback.format_exc()
  7548. app_obj.inform.emit(msg)
  7549. return "fail"
  7550. App.log.debug("open_script()")
  7551. with self.proc_container.new(_("Opening TCL Script...")):
  7552. # Object name
  7553. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7554. # Object creation
  7555. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7556. if ret_val == 'fail':
  7557. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7558. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7559. if ret_val == 'fail':
  7560. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7561. return 'fail'
  7562. # Register recent file
  7563. self.file_opened.emit("script", filename)
  7564. # appGUI feedback
  7565. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7566. def open_config_file(self, filename, run_from_arg=None):
  7567. """
  7568. Loads a config file from the specified file.
  7569. :param filename: Name of the file from which to load.
  7570. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7571. :return: None
  7572. """
  7573. App.log.debug("Opening config file: " + filename)
  7574. if run_from_arg:
  7575. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7576. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7577. _("Opening FlatCAM Config file.")),
  7578. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7579. color=QtGui.QColor("gray"))
  7580. # # add the tab if it was closed
  7581. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7582. # # first clear previous text in text editor (if any)
  7583. # self.ui.text_editor_tab.code_editor.clear()
  7584. #
  7585. # # Switch plot_area to CNCJob tab
  7586. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7587. # close the Code editor if already open
  7588. if self.toggle_codeeditor:
  7589. self.on_toggle_code_editor()
  7590. self.on_toggle_code_editor()
  7591. try:
  7592. if filename:
  7593. f = QtCore.QFile(filename)
  7594. if f.open(QtCore.QIODevice.ReadOnly):
  7595. stream = QtCore.QTextStream(f)
  7596. code_edited = stream.readAll()
  7597. self.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  7598. f.close()
  7599. except IOError:
  7600. App.log.error("Failed to open config file: %s" % filename)
  7601. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7602. (_("Failed to open config file"), filename))
  7603. return
  7604. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7605. """
  7606. Loads a project from the specified file.
  7607. 1) Loads and parses file
  7608. 2) Registers the file as recently opened.
  7609. 3) Calls on_file_new()
  7610. 4) Updates options
  7611. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7612. 6) Calls plot_all() if plot=True
  7613. :param filename: Name of the file from which to load.
  7614. :param run_from_arg: True if run for arguments
  7615. :param plot: If True plot all objects in the project
  7616. :param cli: Run from command line
  7617. :param from_tcl: True if run from Tcl Sehll
  7618. :return: None
  7619. """
  7620. App.log.debug("Opening project: " + filename)
  7621. # block autosaving while a project is loaded
  7622. self.block_autosave = True
  7623. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7624. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7625. if cli is None:
  7626. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7627. if run_from_arg:
  7628. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7629. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7630. _("Opening FlatCAM Project file.")),
  7631. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7632. color=QtGui.QColor("gray"))
  7633. # Open and parse an uncompressed Project file
  7634. try:
  7635. f = open(filename, 'r')
  7636. except IOError:
  7637. if from_tcl:
  7638. name = filename.split('/')[-1].split('\\')[-1]
  7639. filename = self.defaults['global_tcl_path'] + '/' + name
  7640. try:
  7641. f = open(filename, 'r')
  7642. except IOError:
  7643. log.error("Failed to open project file: %s" % filename)
  7644. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7645. return
  7646. else:
  7647. log.error("Failed to open project file: %s" % filename)
  7648. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7649. return
  7650. try:
  7651. d = json.load(f, object_hook=dict2obj)
  7652. except Exception as e:
  7653. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7654. (filename, str(e)))
  7655. f.close()
  7656. # Open and parse a compressed Project file
  7657. try:
  7658. with lzma.open(filename) as f:
  7659. file_content = f.read().decode('utf-8')
  7660. d = json.loads(file_content, object_hook=dict2obj)
  7661. except Exception as e:
  7662. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7663. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7664. return
  7665. # Clear the current project
  7666. # # NOT THREAD SAFE # ##
  7667. if run_from_arg is True:
  7668. pass
  7669. elif cli is True:
  7670. self.delete_selection_shape()
  7671. else:
  7672. self.on_file_new()
  7673. # Project options
  7674. self.options.update(d['options'])
  7675. self.project_filename = filename
  7676. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7677. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7678. if cli is None:
  7679. self.set_screen_units(self.options["units"])
  7680. # Re create objects
  7681. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7682. for obj in d['objs']:
  7683. def obj_init(obj_inst, app_inst):
  7684. try:
  7685. obj_inst.from_dict(obj)
  7686. except Exception as e:
  7687. print('App.open_project() --> ' + str(e))
  7688. return 'fail'
  7689. App.log.debug("Recreating from opened project an %s object: %s" %
  7690. (obj['kind'].capitalize(), obj['options']['name']))
  7691. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7692. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7693. if cli is None:
  7694. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7695. obj['kind'].upper(),
  7696. obj['options']['name']
  7697. )
  7698. )
  7699. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7700. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7701. self.should_we_save = False
  7702. self.file_opened.emit("project", filename)
  7703. # restore autosaving after a project was loaded
  7704. self.block_autosave = False
  7705. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7706. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7707. if cli is None:
  7708. self.set_ui_title(name=self.project_filename)
  7709. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7710. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7711. """
  7712. Re-generates all plots from all objects.
  7713. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7714. :param muted: if True don't print messages
  7715. :param use_thread: if True will use threading for plotting the objects
  7716. :return: None
  7717. """
  7718. self.log.debug("Plot_all()")
  7719. if muted is not True:
  7720. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  7721. for plot_obj in self.collection.get_list():
  7722. def worker_task(obj):
  7723. with self.proc_container.new("Plotting"):
  7724. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7725. if fit_view is True:
  7726. self.app_obj.object_plotted.emit(obj)
  7727. if use_thread is True:
  7728. # Send to worker
  7729. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7730. else:
  7731. worker_task(plot_obj)
  7732. def register_folder(self, filename):
  7733. """
  7734. Register the last folder used by the app to open something
  7735. :param filename: the last folder is extracted from the filename
  7736. :return: None
  7737. """
  7738. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7739. def register_save_folder(self, filename):
  7740. """
  7741. Register the last folder used by the app to save something
  7742. :param filename: the last folder is extracted from the filename
  7743. :return: None
  7744. """
  7745. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7746. # def set_progress_bar(self, percentage, text=""):
  7747. # """
  7748. # Set a progress bar to a value (percentage)
  7749. #
  7750. # :param percentage: Value set to the progressbar
  7751. # :param text: Not used
  7752. # :return: None
  7753. # """
  7754. # self.ui.progress_bar.setValue(int(percentage))
  7755. def setup_recent_items(self):
  7756. """
  7757. Setup a dictionary with the recent files accessed, organized by type
  7758. :return:
  7759. """
  7760. icons = {
  7761. "gerber": self.resource_location + "/flatcam_icon16.png",
  7762. "excellon": self.resource_location + "/drill16.png",
  7763. 'geometry': self.resource_location + "/geometry16.png",
  7764. "cncjob": self.resource_location + "/cnc16.png",
  7765. "script": self.resource_location + "/script_new24.png",
  7766. "document": self.resource_location + "/notes16_1.png",
  7767. "project": self.resource_location + "/project16.png",
  7768. "svg": self.resource_location + "/geometry16.png",
  7769. "dxf": self.resource_location + "/dxf16.png",
  7770. "pdf": self.resource_location + "/pdf32.png",
  7771. "image": self.resource_location + "/image16.png"
  7772. }
  7773. try:
  7774. image_opener = self.image_tool.import_image
  7775. except AttributeError:
  7776. image_opener = None
  7777. openers = {
  7778. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7779. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7780. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7781. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7782. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7783. "document": None,
  7784. 'project': self.open_project,
  7785. 'svg': self.import_svg,
  7786. 'dxf': self.import_dxf,
  7787. 'image': image_opener,
  7788. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7789. }
  7790. # Open recent file for files
  7791. try:
  7792. f = open(self.data_path + '/recent.json')
  7793. except IOError:
  7794. App.log.error("Failed to load recent item list.")
  7795. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7796. return
  7797. try:
  7798. self.recent = json.load(f)
  7799. except json.errors.JSONDecodeError:
  7800. App.log.error("Failed to parse recent item list.")
  7801. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7802. f.close()
  7803. return
  7804. f.close()
  7805. # Open recent file for projects
  7806. try:
  7807. fp = open(self.data_path + '/recent_projects.json')
  7808. except IOError:
  7809. App.log.error("Failed to load recent project item list.")
  7810. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7811. return
  7812. try:
  7813. self.recent_projects = json.load(fp)
  7814. except json.errors.JSONDecodeError:
  7815. App.log.error("Failed to parse recent project item list.")
  7816. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7817. fp.close()
  7818. return
  7819. fp.close()
  7820. # Closure needed to create callbacks in a loop.
  7821. # Otherwise late binding occurs.
  7822. def make_callback(func, fname):
  7823. def opener():
  7824. func(fname)
  7825. return opener
  7826. def reset_recent_files():
  7827. # Reset menu
  7828. self.ui.recent.clear()
  7829. self.recent = []
  7830. try:
  7831. ff = open(self.data_path + '/recent.json', 'w')
  7832. except IOError:
  7833. App.log.error("Failed to open recent items file for writing.")
  7834. return
  7835. json.dump(self.recent, ff)
  7836. def reset_recent_projects():
  7837. # Reset menu
  7838. self.ui.recent_projects.clear()
  7839. self.recent_projects = []
  7840. try:
  7841. frp = open(self.data_path + '/recent_projects.json', 'w')
  7842. except IOError:
  7843. App.log.error("Failed to open recent projects items file for writing.")
  7844. return
  7845. json.dump(self.recent, frp)
  7846. # Reset menu
  7847. self.ui.recent.clear()
  7848. self.ui.recent_projects.clear()
  7849. # Create menu items for projects
  7850. for recent in self.recent_projects:
  7851. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7852. if recent['kind'] == 'project':
  7853. try:
  7854. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7855. # Attach callback
  7856. o = make_callback(openers[recent["kind"]], recent['filename'])
  7857. action.triggered.connect(o)
  7858. self.ui.recent_projects.addAction(action)
  7859. except KeyError:
  7860. App.log.error("Unsupported file type: %s" % recent["kind"])
  7861. # Last action in Recent Files menu is one that Clear the content
  7862. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7863. (_("Clear Recent projects")), self)
  7864. clear_action_proj.triggered.connect(reset_recent_projects)
  7865. self.ui.recent_projects.addSeparator()
  7866. self.ui.recent_projects.addAction(clear_action_proj)
  7867. # Create menu items for files
  7868. for recent in self.recent:
  7869. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7870. if recent['kind'] != 'project':
  7871. try:
  7872. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7873. # Attach callback
  7874. o = make_callback(openers[recent["kind"]], recent['filename'])
  7875. action.triggered.connect(o)
  7876. self.ui.recent.addAction(action)
  7877. except KeyError:
  7878. App.log.error("Unsupported file type: %s" % recent["kind"])
  7879. # Last action in Recent Files menu is one that Clear the content
  7880. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7881. (_("Clear Recent files")), self)
  7882. clear_action.triggered.connect(reset_recent_files)
  7883. self.ui.recent.addSeparator()
  7884. self.ui.recent.addAction(clear_action)
  7885. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7886. # self.ui.menufilerecent.set_submenu(recent_menu)
  7887. # recent_menu.show_all()
  7888. # self.ui.recent.show()
  7889. self.log.debug("Recent items list has been populated.")
  7890. def setup_component_editor(self):
  7891. """
  7892. Default text for the Selected tab when is not taken by the Object UI.
  7893. :return:
  7894. """
  7895. # label = QtWidgets.QLabel("Choose an item from Project")
  7896. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7897. sel_title = QtWidgets.QTextEdit(
  7898. _('<b>Shortcut Key List</b>'))
  7899. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7900. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7901. f_settings = QSettings("Open Source", "FlatCAM")
  7902. if f_settings.contains("notebook_font_size"):
  7903. fsize = f_settings.value('notebook_font_size', type=int)
  7904. else:
  7905. fsize = 12
  7906. tsize = fsize + int(fsize / 2)
  7907. # selected_text = (_('''
  7908. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7909. # </p>
  7910. #
  7911. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7912. # The normal flow when working in FlatCAM is the following:</span></p>
  7913. #
  7914. # <ol>
  7915. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7916. # file into
  7917. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7918. # even dragging and dropping the files on the appGUI.<br />
  7919. # <br />
  7920. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7921. # drop of the
  7922. # file into the FLATCAM appGUI or through the menu/toolbar links offered within the app.</span><br />
  7923. # &nbsp;</li>
  7924. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7925. # and then
  7926. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7927. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7928. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7929. # <br />
  7930. # If the selection of the object is done on the canvas by single click instead, and the
  7931. # <strong>SELECTED TAB</strong>
  7932. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7933. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7934. # it even if it was out of focus.<br />
  7935. # <br />
  7936. # You can change the parameters in this screen and the flow direction is like this:<br />
  7937. # <br />
  7938. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7939. # <strong> Geometry Object
  7940. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7941. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7942. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7943. # </ol>
  7944. #
  7945. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7946. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7947. # <strong>F3</strong>.</span></p>
  7948. #
  7949. # ''').format(fsize=fsize, tsize=tsize))
  7950. selected_text = '''
  7951. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7952. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7953. {s1}</span></p>
  7954. <ol>
  7955. <li><span style="font-size:{fsize}px">{s2}<br />
  7956. <br />
  7957. {s3}</span><br />
  7958. &nbsp;</li>
  7959. <li><span style="font-size:{fsize}px">{s4}<br />
  7960. &nbsp;</li>
  7961. <br />
  7962. <li><span style="font-size:{fsize}px">{s5}<br />
  7963. &nbsp;</li>
  7964. <br />
  7965. <li><span style="font-size:{fsize}px">{s6}<br />
  7966. <br />
  7967. {s7}</span></li>
  7968. </ol>
  7969. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7970. '''.format(
  7971. title=_("Selected Tab - Choose an Item from Project Tab"),
  7972. subtitle=_("Details"),
  7973. s1=_("The normal flow when working with the application is the following:"),
  7974. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into the application "
  7975. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7976. "files on the GUI."),
  7977. s3=_("You can also load a project by double clicking on the project file, "
  7978. "drag and drop of the file into the GUI or through the menu (or toolbar) "
  7979. "actions offered within the app."),
  7980. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7981. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7982. "SELECTED TAB will be updated with the object properties according to its kind: "
  7983. "Gerber, Excellon, Geometry or CNCJob object."),
  7984. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7985. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7986. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7987. "the SELECTED TAB and populate it even if it was out of focus."),
  7988. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7989. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7990. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7991. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7992. "(again, done in SELECTED TAB) --> Save GCode."),
  7993. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7994. "or through its own key shortcut: <b>F3</b>."),
  7995. tsize=tsize,
  7996. fsize=fsize
  7997. )
  7998. sel_title.setText(selected_text)
  7999. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8000. self.ui.selected_scroll_area.setWidget(sel_title)
  8001. def setup_obj_classes(self):
  8002. """
  8003. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8004. class.
  8005. :return: None
  8006. """
  8007. FlatCAMObj.app = self
  8008. ObjectCollection.app = self
  8009. Gerber.app = self
  8010. Excellon.app = self
  8011. Geometry.app = self
  8012. CNCjob.app = self
  8013. FCProcess.app = self
  8014. FCProcessContainer.app = self
  8015. OptionsGroupUI.app = self
  8016. def version_check(self):
  8017. """
  8018. Checks for the latest version of the program. Alerts the
  8019. user if theirs is outdated. This method is meant to be run
  8020. in a separate thread.
  8021. :return: None
  8022. """
  8023. self.log.debug("version_check()")
  8024. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8025. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8026. App.version_url,
  8027. str(self.defaults['global_serial']),
  8028. str(self.version),
  8029. str(self.os),
  8030. urllib.parse.urlencode(self.defaults["global_stats"])
  8031. )
  8032. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8033. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8034. # urllib.parse.urlencode(self.defaults["global_stats"])
  8035. else:
  8036. # no_stats dict; just so it won't break things on website
  8037. no_ststs_dict = {}
  8038. no_ststs_dict["global_ststs"] = {}
  8039. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  8040. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8041. App.log.debug("Checking for updates @ %s" % full_url)
  8042. # ## Get the data
  8043. try:
  8044. f = urllib.request.urlopen(full_url)
  8045. except Exception:
  8046. # App.log.warning("Failed checking for latest version. Could not connect.")
  8047. self.log.warning("Failed checking for latest version. Could not connect.")
  8048. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8049. return
  8050. try:
  8051. data = json.load(f)
  8052. except Exception as e:
  8053. App.log.error("Could not parse information about latest version.")
  8054. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8055. App.log.debug("json.load(): %s" % str(e))
  8056. f.close()
  8057. return
  8058. f.close()
  8059. # ## Latest version?
  8060. if self.version >= data["version"]:
  8061. App.log.debug("FlatCAM is up to date!")
  8062. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8063. return
  8064. App.log.debug("Newer version available.")
  8065. self.message.emit(
  8066. _("Newer Version Available"),
  8067. '%s<br><br>><b>%s</b><br>%s' % (
  8068. _("There is a newer version of FlatCAM available for download:"),
  8069. str(data["name"]),
  8070. str(data["message"])
  8071. ),
  8072. _("info")
  8073. )
  8074. def on_plotcanvas_setup(self, container=None):
  8075. """
  8076. This is doing the setup for the plot area (canvas).
  8077. :param container: QT Widget where to install the canvas
  8078. :return: None
  8079. """
  8080. if container:
  8081. plot_container = container
  8082. else:
  8083. plot_container = self.ui.right_layout
  8084. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8085. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8086. self.is_legacy = True
  8087. self.defaults["global_graphic_engine"] = "2D"
  8088. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8089. else:
  8090. try:
  8091. self.plotcanvas = PlotCanvas(plot_container, self)
  8092. except Exception as er:
  8093. msg_txt = traceback.format_exc()
  8094. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8095. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8096. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8097. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8098. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8099. msg += msg_txt
  8100. self.inform.emit(msg)
  8101. return 'fail'
  8102. # So it can receive key presses
  8103. self.plotcanvas.native.setFocus()
  8104. if self.is_legacy is False:
  8105. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8106. # Set the mouse button for panning
  8107. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8108. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8109. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8110. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8111. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8112. # Keys over plot enabled
  8113. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8114. if self.defaults['global_cursor_type'] == 'small':
  8115. self.app_cursor = self.plotcanvas.new_cursor()
  8116. else:
  8117. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8118. if self.ui.grid_snap_btn.isChecked():
  8119. self.app_cursor.enabled = True
  8120. else:
  8121. self.app_cursor.enabled = False
  8122. if self.is_legacy is False:
  8123. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8124. else:
  8125. # will use the default Matplotlib axes
  8126. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8127. def on_zoom_fit(self):
  8128. """
  8129. Callback for zoom-fit request. This can be either from the corresponding
  8130. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8131. with axes limits from the geometry bounds of all objects.
  8132. :return: None
  8133. """
  8134. if self.is_legacy is False:
  8135. self.plotcanvas.fit_view()
  8136. else:
  8137. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8138. width = xmax - xmin
  8139. height = ymax - ymin
  8140. xmin -= 0.05 * width
  8141. xmax += 0.05 * width
  8142. ymin -= 0.05 * height
  8143. ymax += 0.05 * height
  8144. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8145. def on_zoom_in(self):
  8146. """
  8147. Callback for zoom-in request.
  8148. :return:
  8149. """
  8150. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8151. def on_zoom_out(self):
  8152. """
  8153. Callback for zoom-out request.
  8154. :return:
  8155. """
  8156. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8157. def disable_all_plots(self):
  8158. self.defaults.report_usage("disable_all_plots()")
  8159. self.disable_plots(self.collection.get_list())
  8160. self.inform.emit('[success] %s' %
  8161. _("All plots disabled."))
  8162. def disable_other_plots(self):
  8163. self.defaults.report_usage("disable_other_plots()")
  8164. self.disable_plots(self.collection.get_non_selected())
  8165. self.inform.emit('[success] %s' %
  8166. _("All non selected plots disabled."))
  8167. def enable_all_plots(self):
  8168. self.defaults.report_usage("enable_all_plots()")
  8169. self.enable_plots(self.collection.get_list())
  8170. self.inform.emit('[success] %s' %
  8171. _("All plots enabled."))
  8172. def on_enable_sel_plots(self):
  8173. log.debug("App.on_enable_sel_plot()")
  8174. object_list = self.collection.get_selected()
  8175. self.enable_plots(objects=object_list)
  8176. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8177. def on_disable_sel_plots(self):
  8178. log.debug("App.on_disable_sel_plot()")
  8179. # self.inform.emit(_("Disabling plots ..."))
  8180. object_list = self.collection.get_selected()
  8181. self.disable_plots(objects=object_list)
  8182. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8183. def enable_plots(self, objects):
  8184. """
  8185. Enable plots
  8186. :param objects: list of Objects to be enabled
  8187. :return:
  8188. """
  8189. log.debug("Enabling plots ...")
  8190. # self.inform.emit(_("Working ..."))
  8191. for obj in objects:
  8192. if obj.options['plot'] is False:
  8193. obj.options.set_change_callback(lambda x: None)
  8194. obj.options['plot'] = True
  8195. try:
  8196. # only the Gerber obj has on_plot_cb_click() method
  8197. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8198. # disable this cb while disconnected,
  8199. # in case the operation takes time the user is not allowed to change it
  8200. obj.ui.plot_cb.setDisabled(True)
  8201. except AttributeError:
  8202. pass
  8203. obj.set_form_item("plot")
  8204. try:
  8205. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8206. obj.ui.plot_cb.setDisabled(False)
  8207. except AttributeError:
  8208. pass
  8209. obj.options.set_change_callback(obj.on_options_change)
  8210. def worker_task(objs):
  8211. with self.proc_container.new(_("Enabling plots ...")):
  8212. for plot_obj in objs:
  8213. # obj.options['plot'] = True
  8214. if isinstance(plot_obj, CNCJobObject):
  8215. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8216. else:
  8217. plot_obj.plot(visible=True)
  8218. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8219. def disable_plots(self, objects):
  8220. """
  8221. Disables plots
  8222. :param objects: list of Objects to be disabled
  8223. :return:
  8224. """
  8225. # if no objects selected then do nothing
  8226. if not self.collection.get_selected():
  8227. return
  8228. log.debug("Disabling plots ...")
  8229. # self.inform.emit(_("Working ..."))
  8230. for obj in objects:
  8231. if obj.options['plot'] is True:
  8232. obj.options.set_change_callback(lambda x: None)
  8233. obj.options['plot'] = False
  8234. try:
  8235. # only the Gerber obj has on_plot_cb_click() method
  8236. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8237. obj.ui.plot_cb.setDisabled(True)
  8238. except AttributeError:
  8239. pass
  8240. obj.set_form_item("plot")
  8241. try:
  8242. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8243. obj.ui.plot_cb.setDisabled(False)
  8244. except AttributeError:
  8245. pass
  8246. obj.options.set_change_callback(obj.on_options_change)
  8247. try:
  8248. self.delete_selection_shape()
  8249. except Exception as e:
  8250. log.debug("App.disable_plots() --> %s" % str(e))
  8251. def worker_task(objs):
  8252. with self.proc_container.new(_("Disabling plots ...")):
  8253. for plot_obj in objs:
  8254. # obj.options['plot'] = True
  8255. if isinstance(plot_obj, CNCJobObject):
  8256. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8257. else:
  8258. plot_obj.plot(visible=False)
  8259. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8260. def toggle_plots(self, objects):
  8261. """
  8262. Toggle plots visibility
  8263. :param objects: list of Objects for which to be toggled the visibility
  8264. :return: None
  8265. """
  8266. # if no objects selected then do nothing
  8267. if not self.collection.get_selected():
  8268. return
  8269. log.debug("Toggling plots ...")
  8270. self.inform.emit(_("Working ..."))
  8271. for obj in objects:
  8272. if obj.options['plot'] is False:
  8273. obj.options['plot'] = True
  8274. else:
  8275. obj.options['plot'] = False
  8276. self.app_obj.plots_updated.emit()
  8277. def clear_plots(self):
  8278. """
  8279. Clear the plots
  8280. :return: None
  8281. """
  8282. objects = self.collection.get_list()
  8283. for obj in objects:
  8284. obj.clear(obj == objects[-1])
  8285. # Clear pool to free memory
  8286. self.clear_pool()
  8287. def on_set_color_action_triggered(self):
  8288. """
  8289. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8290. :return:
  8291. """
  8292. new_color = self.defaults['gerber_plot_fill']
  8293. clicked_action = self.sender()
  8294. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8295. act_name = clicked_action.text()
  8296. sel_obj_list = self.collection.get_selected()
  8297. if not sel_obj_list:
  8298. return
  8299. # a default value, I just chose this one
  8300. alpha_level = 'BF'
  8301. for sel_obj in sel_obj_list:
  8302. if sel_obj.kind == 'excellon':
  8303. alpha_level = str(hex(
  8304. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  8305. elif sel_obj.kind == 'gerber':
  8306. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  8307. elif sel_obj.kind == 'geometry':
  8308. alpha_level = 'FF'
  8309. else:
  8310. log.debug(
  8311. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8312. continue
  8313. sel_obj.alpha_level = alpha_level
  8314. if act_name == _('Red'):
  8315. new_color = '#FF0000' + alpha_level
  8316. if act_name == _('Blue'):
  8317. new_color = '#0000FF' + alpha_level
  8318. if act_name == _('Yellow'):
  8319. new_color = '#FFDF00' + alpha_level
  8320. if act_name == _('Green'):
  8321. new_color = '#00FF00' + alpha_level
  8322. if act_name == _('Purple'):
  8323. new_color = '#FF00FF' + alpha_level
  8324. if act_name == _('Brown'):
  8325. new_color = '#A52A2A' + alpha_level
  8326. if act_name == _('White'):
  8327. new_color = '#FFFFFF' + alpha_level
  8328. if act_name == _('Black'):
  8329. new_color = '#000000' + alpha_level
  8330. if act_name == _('Custom'):
  8331. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8332. c_dialog = QtWidgets.QColorDialog()
  8333. plot_fill_color = c_dialog.getColor(initial=new_color)
  8334. if plot_fill_color.isValid() is False:
  8335. return
  8336. new_color = str(plot_fill_color.name()) + alpha_level
  8337. if act_name == _("Default"):
  8338. for sel_obj in sel_obj_list:
  8339. if sel_obj.kind == 'excellon':
  8340. new_color = self.defaults['excellon_plot_fill']
  8341. new_line_color = self.defaults['excellon_plot_line']
  8342. elif sel_obj.kind == 'gerber':
  8343. new_color = self.defaults['gerber_plot_fill']
  8344. new_line_color = self.defaults['gerber_plot_line']
  8345. elif sel_obj.kind == 'geometry':
  8346. new_color = self.defaults['geometry_plot_line']
  8347. new_line_color = self.defaults['geometry_plot_line']
  8348. else:
  8349. log.debug(
  8350. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8351. continue
  8352. sel_obj.fill_color = new_color
  8353. sel_obj.outline_color = new_line_color
  8354. sel_obj.shapes.redraw(
  8355. update_colors=(new_color, new_line_color)
  8356. )
  8357. return
  8358. if act_name == _("Opacity"):
  8359. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8360. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8361. if ok_button:
  8362. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8363. for sel_obj in sel_obj_list:
  8364. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8365. sel_obj.shapes.redraw(
  8366. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8367. )
  8368. return
  8369. new_line_color = color_variant(new_color[:7], 0.7)
  8370. if act_name == _("White"):
  8371. new_line_color = color_variant("#dedede", 0.7)
  8372. for sel_obj in sel_obj_list:
  8373. sel_obj.fill_color = new_color
  8374. sel_obj.outline_color = new_line_color
  8375. sel_obj.shapes.redraw(
  8376. update_colors=(new_color, new_line_color)
  8377. )
  8378. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  8379. group = self.collection.group_items["gerber"]
  8380. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  8381. new_c = (new_line_color, new_color)
  8382. for sel_obj in sel_obj_list:
  8383. if sel_obj.kind == 'gerber':
  8384. item = sel_obj.item
  8385. item_index = self.collection.index(item.row(), 0, group_index)
  8386. idx = item_index.row()
  8387. self.defaults["gerber_color_list"][idx] = new_c
  8388. def generate_cnc_job(self, objects):
  8389. """
  8390. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8391. :param objects: Selected objects in the Project Tab
  8392. :return:
  8393. """
  8394. self.defaults.report_usage("generate_cnc_job()")
  8395. # for obj in objects:
  8396. # obj.generatecncjob()
  8397. for obj in objects:
  8398. obj.on_generatecnc_button_click()
  8399. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8400. """
  8401. Saves the current project to the specified file.
  8402. :param filename: Name of the file in which to save.
  8403. :type filename: str
  8404. :param quit_action: if the project saving will be followed by an app quit; boolean
  8405. :param silent: if True will not display status messages
  8406. :param from_tcl True is run from Tcl Shell
  8407. :return: None
  8408. """
  8409. self.log.debug("save_project()")
  8410. self.save_in_progress = True
  8411. with self.proc_container.new(_("Saving FlatCAM Project")):
  8412. # Capture the latest changes
  8413. # Current object
  8414. try:
  8415. current_object = self.collection.get_active()
  8416. if current_object:
  8417. current_object.read_form()
  8418. except Exception as e:
  8419. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8420. pass
  8421. # Serialize the whole project
  8422. d = {
  8423. "objs": [obj.to_dict() for obj in self.collection.get_list()],
  8424. "options": self.options,
  8425. "version": self.version
  8426. }
  8427. if self.defaults["global_save_compressed"] is True:
  8428. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8429. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8430. # # Write
  8431. f.write(g)
  8432. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8433. else:
  8434. # Open file
  8435. try:
  8436. f = open(filename, 'w')
  8437. except IOError:
  8438. App.log.error("Failed to open file for saving: %s", filename)
  8439. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8440. return
  8441. # Write
  8442. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8443. f.close()
  8444. # verification of the saved project
  8445. # Open and parse
  8446. try:
  8447. saved_f = open(filename, 'r')
  8448. except IOError:
  8449. if silent is False:
  8450. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8451. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8452. return
  8453. try:
  8454. saved_d = json.load(saved_f, object_hook=dict2obj)
  8455. except Exception:
  8456. if silent is False:
  8457. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8458. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8459. f.close()
  8460. return
  8461. saved_f.close()
  8462. if silent is False:
  8463. if 'version' in saved_d:
  8464. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8465. else:
  8466. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8467. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8468. tb_settings = QSettings("Open Source", "FlatCAM")
  8469. lock_state = self.ui.lock_action.isChecked()
  8470. tb_settings.setValue('toolbar_lock', lock_state)
  8471. # This will write the setting to the platform specific storage.
  8472. del tb_settings
  8473. # if quit:
  8474. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8475. # t.start()
  8476. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8477. def start_delayed_quit(self, delay, filename, should_quit=None):
  8478. """
  8479. :param delay: period of checking if project file size is more than zero; in seconds
  8480. :param filename: the name of the project file to be checked periodically for size more than zero
  8481. :param should_quit: if the task finished will be followed by an app quit; boolean
  8482. :return:
  8483. """
  8484. to_quit = should_quit
  8485. self.save_timer = QtCore.QTimer()
  8486. self.save_timer.setInterval(delay)
  8487. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8488. self.save_timer.start()
  8489. def check_project_file_size(self, filename, should_quit=None):
  8490. """
  8491. :param filename: the name of the project file to be checked periodically for size more than zero
  8492. :param should_quit: will quit the app if True; boolean
  8493. :return:
  8494. """
  8495. try:
  8496. if os.stat(filename).st_size > 0:
  8497. self.save_in_progress = False
  8498. self.save_timer.stop()
  8499. if should_quit:
  8500. self.app_quit.emit()
  8501. except Exception:
  8502. traceback.print_exc()
  8503. def save_project_auto(self):
  8504. """
  8505. Called periodically to save the project.
  8506. 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
  8507. # progress.
  8508. :return:
  8509. """
  8510. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8511. self.on_file_saveproject()
  8512. def save_project_auto_update(self):
  8513. """
  8514. Update the auto save time interval value.
  8515. :return:
  8516. """
  8517. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8518. try:
  8519. if self.autosave_timer.isActive():
  8520. self.autosave_timer.stop()
  8521. except Exception:
  8522. pass
  8523. if self.defaults['global_autosave'] is True:
  8524. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8525. self.autosave_timer.start()
  8526. def on_options_app2project(self):
  8527. """
  8528. Callback for Options->Transfer Options->App=>Project. Copies options
  8529. from application defaults to project defaults.
  8530. :return: None
  8531. """
  8532. self.defaults.report_usage("on_options_app2project")
  8533. self.preferencesUiManager.defaults_read_form()
  8534. self.options.update(self.defaults)
  8535. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8536. """
  8537. Shows a message on the FlatCAM Shell
  8538. :param msg: Message to display.
  8539. :param show: Opens the shell.
  8540. :param error: Shows the message as an error.
  8541. :param warning: Shows the message as an warning.
  8542. :param success: Shows the message as an success.
  8543. :param selected: Indicate that something was selected on canvas
  8544. :return: None
  8545. """
  8546. if show:
  8547. self.ui.shell_dock.show()
  8548. try:
  8549. if error:
  8550. self.shell.append_error(msg + "\n")
  8551. elif warning:
  8552. self.shell.append_warning(msg + "\n")
  8553. elif success:
  8554. self.shell.append_success(msg + "\n")
  8555. elif selected:
  8556. self.shell.append_selected(msg + "\n")
  8557. else:
  8558. self.shell.append_output(msg + "\n")
  8559. except AttributeError:
  8560. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8561. def dec_format(self, val, dec=None):
  8562. """
  8563. Returns a formatted float value with a certain number of decimals
  8564. """
  8565. dec_nr = dec if dec is not None else self.decimals
  8566. return float('%.*f' % (dec_nr, val))
  8567. class ArgsThread(QtCore.QObject):
  8568. open_signal = pyqtSignal(list)
  8569. start = pyqtSignal()
  8570. stop = pyqtSignal()
  8571. if sys.platform == 'win32':
  8572. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8573. else:
  8574. address = ('/tmp/testipc', 'AF_UNIX')
  8575. def __init__(self):
  8576. super().__init__()
  8577. self.listener = None
  8578. self.thread_exit = False
  8579. self.start.connect(self.run)
  8580. self.stop.connect(self.close_listener)
  8581. def my_loop(self, address):
  8582. try:
  8583. self.listener = Listener(*address)
  8584. while self.thread_exit is False:
  8585. conn = self.listener.accept()
  8586. self.serve(conn)
  8587. except socket.error:
  8588. try:
  8589. conn = Client(*address)
  8590. conn.send(sys.argv)
  8591. conn.send('close')
  8592. # close the current instance only if there are args
  8593. if len(sys.argv) > 1:
  8594. try:
  8595. self.listener.close()
  8596. except Exception:
  8597. pass
  8598. sys.exit()
  8599. except ConnectionRefusedError:
  8600. if sys.platform == 'win32':
  8601. pass
  8602. else:
  8603. os.system('rm /tmp/testipc')
  8604. self.listener = Listener(*address)
  8605. while True:
  8606. conn = self.listener.accept()
  8607. self.serve(conn)
  8608. def serve(self, conn):
  8609. while self.thread_exit is False:
  8610. msg = conn.recv()
  8611. if msg == 'close':
  8612. break
  8613. self.open_signal.emit(msg)
  8614. conn.close()
  8615. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8616. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8617. @pyqtSlot()
  8618. def run(self):
  8619. self.my_loop(self.address)
  8620. @pyqtSlot()
  8621. def close_listener(self):
  8622. self.thread_exit = True
  8623. self.listener.close()
  8624. # end of file